Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomicity and CAS operations in MongoDB

Tags:

mongodb

Currently I am trying to understand how to implement a CAS operation in mongodb properly to support optimistic locking. I've found out that updates in mongodb are atomic but I am not sure what this means (only the document rewrite is atomic or all cycle of update, including search for corresponding document and its rewriting, is atomic?). Lets consider following example.

  1. Some document exists in some collection with _id value set to 123 and has attribute cas_val set to 10.
  2. The first client wants to update cas_val of the document with _id equal to 123 to 11.
  3. The second client wants to update cas_val of the document with _id equal to 123 to 11.
  4. Both clients operate at the same time and operations can interleave.

So, is it possible that both operation succeed in case when no other updates to the document with _id 123 were performed?

P.S. Is there some build in technique in mongodb for the optimistic locking scenario?

like image 813
gkuzmin Avatar asked Dec 11 '22 15:12

gkuzmin


1 Answers

The correct technique for optimistic locking is to use the "update if current" which is described in detail in MongoDB docs.

The key to this technique is that the update condition cannot simply be {_id:123} but rather it has to be {_id:123, cas_val: 10} and the update clause would $set appropriate fields including incrementing the cas_val to 11.

Now the thread that "loses" the race and arrives second will NOT find a matching document to update and will need to "retry" by refetching the document (now with cas_val 11) and trying again. The way you find out if the update succeeded or not is by checking the writeConcern structure (it will indicate how many records were affected in "n" and whether existing record was updated in "updatedExisting" field).

like image 195
Asya Kamsky Avatar answered Dec 16 '22 04:12

Asya Kamsky