How it works
A wallet holds $100. Payment A debits $30 and Payment B debits $50, and each reads the balance, subtracts in code, and writes the result. Both read 100. A writes 70 and commits. B writes 50 and commits. The balance should be 20, but it is 50, and A’s debit has vanished. This is a lost update, and read committed allows it, since nobody saw uncommitted data.
An atomic operation lets the database do the arithmetic: UPDATE wallets SET balance = balance - 30 WHERE id = 7 AND balance >= 30. The second writer waits for the row lock, then applies its change to the latest value, and zero affected rows means insufficient funds. Use this when the change fits in one statement.
A row lock covers logic that does not fit. SELECT ... FOR UPDATE holds the row until commit, so a second transaction asking for the same lock waits. Do not hold it across a slow network call, since other writers queue behind you. Compare-and-set checks that nothing changed since you read: UPDATE ... SET balance = 70, version = 8 WHERE id = 7 AND version = 7. Zero rows affected means someone got there first, so re-read and recompute. It holds no lock between read and write, which suits a form left open for minutes, but retries pile up under heavy contention.
At repeatable read, Postgres aborts the second writer with a serialization error for the application to retry. MySQL InnoDB’s repeatable read does not detect this, and the second update simply applies.
A venue tool lets managers rearrange the pricing tiers of a section. A manager may keep the screen open for ten minutes before saving the whole layout, and last week one manager’s changes silently disappeared when another saved. Which guard do you choose?
Compare-and-set with a version column on the section. Load the version with the form, save with WHERE version = loaded, and on zero rows show the other manager’s changes so the person can merge. An atomic update does not fit, because a human computed the new layout from old data. A row lock held for ten minutes would block other managers and linger if the browser closes. The cost is a conflict screen the product has to design.
Keep in mind
- A read-modify-write cycle in application code can lose updates at read committed.
- Prefer an atomic update, then a short row lock, then compare-and-set when read and write are far apart.
- A compare-and-set that affects zero rows means re-read and recompute, not resend.