How it works
A general-admission section has 100 places, and each sale inserts a booking row. With 99 sold, two buyers check out at once. Each transaction runs SELECT count(*), sees 99, and inserts one row. Both commit, and the section has 101 bookings. Snapshot isolation stopped neither, because they wrote different new rows, so no write-write conflict existed to detect.
This is write skew: transactions read overlapping data, write different rows, and jointly break a rule each respected alone. The same shape appears when two on-call engineers each see a colleague on the schedule and both sign off. The booking case adds a phantom, where a write changes which rows another transaction’s search would match. Locking the 99 visible rows does not stop a new row from appearing.
One fix is to materialize the conflict: create a row that stands for the contended thing, giving locks something to attach to. Keep a sold counter on a section row, and run UPDATE sections SET sold = sold + 1 WHERE id = 5 AND sold < 100 in the booking transaction. The second buyer waits on that row, then at read committed matches no rows and reports the section full. At snapshot isolation Postgres aborts it, and the retry reaches the same answer.
When the rule concerns one key, a constraint is simpler: a unique index on show and seat makes a second insert for seat 14B fail. Materializing adds a table purely for concurrency, and a section’s bookings all queue on one row. With many such rules, use serializable isolation.
A meeting-room app stores bookings as rows with a room, a start time, and an end time. Two people book overlapping slots in the same room at the same moment, and both succeed. The database is Postgres at repeatable read, and you have one afternoon to fix it. What do you do?
This is write skew with a phantom: each checked for overlaps, found none, and inserted a different row. A unique index cannot express overlapping ranges, but a Postgres exclusion constraint can, and it is the smallest correct fix while the rule stays this simple. Otherwise start the transaction by updating a per-room row, so a concurrent booking aborts and retries at this level, or run these transactions at serializable and retry. A per-room row queues bookings for that room, which is rarely a problem at human booking rates. A plain SELECT ... FOR UPDATE is not enough at repeatable read, because the waiting transaction keeps its old snapshot and still cannot see the new booking.
Keep in mind
- Write skew breaks a rule across rows that no single write conflicts on.
- A phantom is a new row that would have changed another transaction’s query.
- Materializing a conflict gives locks a row to attach to, at the cost of a contended row.