4

If two agents run this update query concurrently on a Mongo cluster, what is the expected value of updateVersion at the end?

db.Task.findAndModify(
    {
        query:{"updateVersion":21},
        update:{$inc:{"updateVersion":1}}
    }
);

If the answer is "23", is there a way to have a guaranteed read/write synchronized operation?

Deroude
  • 1,052
  • 9
  • 24
  • Replying too late but might be helpful for whoever comes next. https://stackoverflow.com/questions/29025278/how-does-the-inc-modifier-work-with-concurrent-requests-in-mongodb – Srijan Aug 17 '20 at 16:32

1 Answers1

0

MongoDB have FAQ section about concurrent operations.

In your case, write conflict might happen but MongoDB still try to execute both commands:

A situation in which two concurrent operations, at least one of which is a write, attempt to use a resource in a way that would violate constraints imposed by a storage engine using optimistic concurrency control. MongoDB will transparently abort and retry one of the conflicting operations.

G07cha
  • 4,009
  • 2
  • 22
  • 39
  • So ... the answer is? 22 or 23? I had already read the FAQ section. Your quote doesn't really answer. First of all, the two ops might not cause a conflict at all: first finds the version 21 and increments to 22, second finds 22, no document to update, everyone happy - assuming read/write lock, which is not clear according to this: https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/. Also, in a cluster environment, what happens if the concurrent clients issue the command on different instances? – Deroude Aug 29 '16 at 08:06
  • The answer should be 22 because as you said if there will be no conflict, only first operation update version. If there will be a conflict, MongoDB will retry full operation(search too) and as expected, works the same as with the first scenario. – G07cha Aug 29 '16 at 08:12
  • That's my (wishful) thinking too :) -- but what if both ops find the document (no read lock), then take turns in incrementing the version field (write lock) and the end result is 23? How did you conclude that there may be a conflict? – Deroude Aug 29 '16 at 08:19
  • Find operation is performs read lock as far as I know. In another hand, `findAndModify` or `update` is checking for corresponding `id` before insertion which prevents duplicates and incorrect updates, see https://docs.mongodb.com/manual/core/write-operations-atomicity/#concurrency-control – G07cha Aug 29 '16 at 08:35