Full answer
Timeline under snapshot isolation:
- T1 reads: on-call count = 2. T2 reads: on-call count = 2.
- T1 sets Alice off call. T2 sets Bob off call. Different rows, so no write conflict.
- Both commit. On-call count is now 0.
Prevention:
SERIALIZABLEin PostgreSQL detects the dangerous read-write dependency and fails one transaction with a serialization error; the application retries it.- Explicit locking:
SELECT ... FROM doctors WHERE shift_id = :s AND on_call FOR UPDATElocks both rows, so T2 waits for T1 and then sees the new count. - Materialise the constraint: keep an on-call count row per shift and update it, turning the hidden conflict into a write conflict on one row.
SQLite serialises writers entirely, so this anomaly does not arise there in the same way. The PostgreSQL behaviour is described here, not run.
Key points
- Write skew: disjoint writes based on a shared read
- Snapshot isolation allows it
- SERIALIZABLE detects it and aborts one transaction
- FOR UPDATE on the read set also prevents it
- Retry serialization failures
Common mistakes
- Assuming REPEATABLE READ prevents all anomalies
- Not retrying serialization errors
Follow-ups
- How does write skew differ from a lost update?
- What does SERIALIZABLE cost in throughput?
Tips
- Walk through the timeline