Document-level locking for MongoDB via Mongoid
Clone or download


Gem Version Build Status Code Climate

Document-level locking for MongoDB via Mongoid. The need arose at Jux from multiple processes on multiple servers trying to act upon the same document and stepping on each other's toes. Mongoid-Locker is an easy way to ensure only one process can perform a certain operation on a document at a time.

Tested against:

  • MRI: 2.3.6, 2.4.3, 2.5.0
  • Mongoid: 2, 3, 4, 5, 6, 7

See .travis.yml for the latest test matrix.


Add to your Gemfile:

gem 'mongoid-locker'

and run bundle install. In the model you wish to lock, include Mongoid::Locker after Mongoid::Document. For example:

class QueueItem
  include Mongoid::Document
  include Mongoid::Locker

  field :completed_at, :type => Time

Then, execute any code you like in a block like so:

queue_item.with_lock do

  # do stuff

  queue_item.completed_at =!

The #with_lock function takes an optional handful of options around retrying, so make sure to take a look.

The default timeout can also be set on a per-class basis:

class QueueItem
  # ...
  timeout_lock_after 10

Note that these locks are only enforced when using #with_lock, not at the database level. It's useful for transactional operations, where you can make atomic modification of the document with checks. For example, you could deduct a purchase from a user's balance ... unless they are broke.

More in-depth method documentation can be found at

Copyright & License

Copyright (c) 2012-2018 Aidan Feldman & Contributors

MIT License, see LICENSE for more information.