Part 12 / Topic 5 of 9
The anomalies — and the one that bites first
Names for the ways concurrency corrupts data, each blocked by some level:
| Anomaly | What happens | Blocked from |
|---|---|---|
| Dirty read | seeing uncommitted data | never possible in Postgres |
| Non-repeatable read | re-read differs mid-transaction | Repeatable Read |
| Phantom | re-run query finds new rows | Repeatable Read (in Postgres) |
| Lost update | read-modify-write races erase an update | FOR UPDATE / Repeatable Read |
| Write skew | two txns each check, then both write | Serializable only |
The one every application hits first is the lost update — and no isolation level default saves naive code from it. Two checkouts, each "read stock, subtract one, write back". Real transcript:
-- Session A -- Session B
BEGIN;
SELECT stock FROM products
WHERE product_id = 1; → 15
BEGIN;
SELECT stock FROM products
WHERE product_id = 1; → 15
UPDATE products SET stock = 14
WHERE product_id = 1;
COMMIT;
UPDATE products SET stock = 14
WHERE product_id = 1;
COMMIT;
SELECT stock FROM products WHERE product_id = 1; → 14 ← two sales, one decrement
Both read 15, both wrote 14: a sale vanished, silently, with every statement individually "correct". Section 7 fixes it with a lock; the other fix is making the write atomic — SET stock = stock - 1 computes from the row's current version at write time, so there is nothing to lose. Prefer the atomic form whenever the new value is derivable; lock when you genuinely must read, think, then write.
🧪 Quick quiz — answer from memory, then check.
- Why does the lost update happen even though every statement succeeded?
- The two fixes?
Show the answers
- Both transactions read the same old value and computed their writes from it — the second write overwrote the first's effect.
- Atomic writes (
SET stock = stock - 1), or lock the row across the read-think-write (SELECT ... FOR UPDATE).
Done here? The practice set for Part 12 — 6 exercises with solutions — is on the part page.