0

I just need a simple mutex, stored in MongoDB. I want a lock given a unique id. There seem to be many popular solutions with Redis, but in this case, since we are already using MongoDB, I am looking for some sort of library that I can use for locking with MongoDB, but I can't find any good packages. Is there a way to do a simple lock with Mongoose or the official MongoDB node.js driver?

I am especially looking for some mutex in MongoDB that has a built-in TTL (time to live). With Redis, you can give a key a TTL and it will remove itself after a period of time, that's an essential feature.

When I google "mongodb + ttl" this is what I see:

https://docs.mongodb.com/manual/core/index-ttl/

5
  • 1
    I think you will find that most DBMS (SQL or NoSQL) handle transactions / locking on their own (i.e. a read operation on a record will wait until a write operation is finished). Since there aren't transactions in MongoDB, they've provided a specifically helpful atomic operation called "findAndUpdate". Commented May 11, 2017 at 0:51
  • yeah but what about TTL Commented May 11, 2017 at 0:51
  • 1
    It sounds like Mongo supports specifying a TTL index on any date field. So, in your case you could consider adding an index like so: db.my_locks.createIndex( { "deleteAt": 1 }, { expireAfterSeconds: 1 } ) and specifying "deleteAt" on insert. Commented May 11, 2017 at 1:03
  • cool, thanks that should work - I figure if you try creating an index with the same name it will error out. Commented May 11, 2017 at 1:06
  • 1
    Yeah, there's only one way to find out ;) Commented May 11, 2017 at 1:16

1 Answer 1

1

To recap our discussion in the comments...

DBMS Transaction Locking

If you're asking about locking at the DBMS transaction level, I think you will find that most DBMS (SQL or NoSQL) handle transactions / locking on their own (i.e. a read operation on a record will wait until a write operation is finished). In MongoDB, since each operation is a single transaction, they've provided a specifically helpful atomic operation called "findAndUpdate".

Domain Specific Locking

Nothing is stopping you from creating some sort of "locks" collection which must be checked before certain operations are made. You will definitely need to consider and take note of the "edge" cases that could result in illegal state or data inconsistency. This is a good time to also reevaluate your architecture (hint: microservices).

TTL

Mongo supports specifying a TTL index on any date field. So, in your case you could consider adding an index like so: db.my_locks.createIndex( { "deleteAt": 1 }, { expireAfterSeconds: 1 } ) and specifying "deleteAt" on insert.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.