/ THE IDEA
Imagine stock starts at ten. One worker sells two items and computes eight; another sells three and computes seven. Both read ten before either writes. If each later sends an unconditional instruction to set stock to their computed number, the second write replaces the first. This is a lost update. There are several defences. A row lock can require a worker to wait before reading and changing the row. A version check can reject a save if the record has changed since it was read. A database-side arithmetic update can apply a decrement to the current row rather than sending a stale replacement value.
THE FORMAL IDEA
UPDATE stock SET quantity = 7, version = version + 1 WHERE id = 1 AND version = 4
| UPDATE changes stored rows; quantity is the stock count; id selects this item. version is a number increased each time the row changes. | | The AND requires both conditions to hold. The application must check how many rows changed: zero means its expected version was no longer present, not that the sale succeeded. |
|
RUN THE TINY EXAMPLE
Change one thing. Predict what happens.
Both workers read quantity 10 at version 4. Worker A saves 8 and advances the version to 5. Unconditional worker B then saves 7: final stock is 7, although 10 − 2 − 3 = 5. Change only B’s save to require version 4: it changes zero rows. B rereads 8 at version 5, subtracts 3 and retries, producing 5.
|
The conflict becomes visible instead of silently discarding A’s sale. The application needs a deliberate retry or conflict response; noticing the problem is not the same as finishing the operation. The quantity change and version advance must themselves happen together.
/ SO WHAT?
Isolation levels govern overlapping transactions. Serializable execution promises a result equivalent to running them one at a time in some order, but may require restarting one. That guarantee concerns interactions between complete operations, not merely whether a saved number survives a crash.
ONE CAVEAT |
| Exact isolation behaviour depends on the database and statements used. PostgreSQL’s Read Committed mode handles concurrent arithmetic updates differently from this stale application read-and-replace pattern. A stronger isolation setting is not permission to ignore errors or retry only half a transaction. |
KEEP THIS
When a save depends on an earlier read, protect that dependency or explicitly detect that somebody changed it in between.
|
NEXT: Why expanding gas can lift a weight
|