Many users update the same data at the same time in mongdb

Viewed 76

I am new to mongdb. I store a counter variable in the database. Every time a user performs a certain action, the counter variable's value will be incremented by 1. The question I wonder is if multiple users update the counter at the same time, will the counter hold the correct value? (expect that the counter will increment exactly by the number of updates). If this causes a logic error, how do I resolve it?

1 Answers

A good question, this race condition can be solved in the similar fashion that you have mentioned already.

{
  item_id : <id>,
  version : <Number>,
  updated_by : <something>
}

When you fetch this document to update you will get the whole document, now during the write the system takes a granular document level lock, so that won't be a problem.

While updating update's query part should have both item_id & version and along with other content you update - increment the version of the document as well.

If two copy of the same document has been received for update by the backend, the one which comes late will have previous version therefore it won't be able to update anything.

Now handle that flow where the document was changed before the user can push their change to the system.

Related