Avoid Lost Updates in Read–Modify–Write Operations

Reading a value, changing it, and saving it in separate steps can lose concurrent updates; make the operation atomic or protect it with a transaction.

Omar Alalwi Article

Suppose a points balance is 100 and two requests arrive together, each adding 10. If both read 100, calculate 110, and save it, the final value may be 110 instead of 120 because the last write overwrites the first.

For a simple change, use an atomic database update, such as incrementing the column by a specified amount under a clear condition. The database can then apply concurrent changes without separating the read from the write in application code.

When an operation reads multiple records or checks conditions before writing, place it in a transaction and use appropriate locking or isolation. Add database constraints for essential invariants, and test with parallel requests; a sequential test alone will not expose this class of failure.

Share your perspective

I’d be glad to hear your perspective. Leave a comment on the original article on social media.

Related articles