Skip to content

Instantly share code, notes, and snippets.

@coffeemug
Last active February 2, 2018 15:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coffeemug/5894410 to your computer and use it in GitHub Desktop.
Save coffeemug/5894410 to your computer and use it in GitHub Desktop.
Atomic get and set in RethinkDB 1.7

Suppose you have a number of nodes on a network that spin up cron jobs to perform various tasks. However, you need the nodes to cooperate to ensure that multiple nodes don't spin up the same task. You can easily implement this functionality on top of RethinkDB as follows:

// A single node atomically pushes jobs onto an array in the database
r.table('admin').get('jobs').update({ job_list: r.row('job_list').append(JOB_DESCRIPTION)) })

// You can now have multiple nodes atomically pop jobs off the queue
r.table('admin').get('jobs').update({ job_list: r.row('job_list').deleteAt(0) },
                                    return_vals: true)

// The client node can now grab the first value from the `job_list` in
// the `old` field of the result, and execute the job.

This system wouldn't be as efficient as dedicated queueing systems, but for many use cases you can just use RethinkDB without having to introduce dedicated queueing software into your stack. We're also looking forward to introducing triggers in future releases to allow the database to inform clients of database-side changes.

See more about the 1.7 release in the release announcement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment