Question 44 / 50
ImportantHardScenarioConcurrency
Two requests credit the same wallet document at the same time using find, add in JS, then $set balance. How do you make this safe?
Think about it first.
Short answer
Do not compute the new balance in the application from a stale read. $inc the amount on the server, or use a version field (optimistic concurrency) so the second writer retries. If credits must pair with another document, use a transaction.
Why?
Lost update is the name of the bug: last $set wins and the other credit vanishes. $inc is the MongoDB-shaped fix for counters. For more complex invariants — 'balance cannot go negative and we write a ledger row' — combine a filtered update with a transaction or an append-only ledger.
Interview tip
Say 'lost update', then $inc. Vocabulary plus a concrete operator is a strong combo.
Common mistake
Putting a mutex in Node.js. That does not work across processes or instances.
How did you do?
Cheat Sheet