-
Database
Handle concurrent writes without lost updates
Fixes read-modify-write races (counters, balances, inventory) with atomic operations or optimistic locking.
Free Prompt
Audit my app for lost-update bugs: anywhere the code reads a value, modifies it in application code, and writes it back. Counters (likes, views, credits), balances, inventory, seats available, and 'increment usage' logic are the classic spots.
For each one: replace the read-modify-write with an atomic operation the database performs (UPDATE ... SET count = count + 1, MongoDB's $inc, or the ORM's equivalent), so two concurrent requests can't both read 10 and both write 11. Where the logic genuinely needs the read (checking sufficient balance before a debit), do it inside a transaction with a conditional write (UPDATE ... WHERE balance >= amount) and verify the row actually updated, retrying or failing cleanly if it didn't. For records edited by users simultaneously (documents, settings), add optimistic locking with a version field: the write only succeeds if the version hasn't changed, and the loser gets told to reload.
Don't serialize everything through locks; atomic operations and conditional writes handle the common cases without contention. Don't change the user-facing behavior of counters.
Deliver: each race found, the fix applied, and a concurrency test: fire parallel increments or debits and confirm the final value is exactly right, not approximately right.
What This Does / How This Helps
Finds read-modify-write races and replaces them with atomic database operations, so concurrent requests can't overwrite each other's work. The bug: two requests both read a balance of 10, both subtract 5, both write 5. The customer spent 10 and the database says they spent 5. Under low traffic this never happens, which is exactly why it ships. Under real traffic it corrupts counts, balances, and inventory a little at a time. The concurrency test is the proof: fire the parallel writes and demand the arithmetic be exact.
Want to skip doing this by hand?
Fortivibe audits your app for all of the areas these prompts cover (and more).