Full answer
Timeline under snapshot isolation:
text
T1: SELECT count(*) FROM doctors WHERE on_call; -- 2, fine to leave
T2: SELECT count(*) FROM doctors WHERE on_call; -- 2, fine to leave
T1: UPDATE doctors SET on_call = false WHERE name = 'Ravi';
T2: UPDATE doctors SET on_call = false WHERE name = 'Mei';
T1: COMMIT; T2: COMMIT; -- nobody on callThe two updates touch different rows, so row locks never collide. Each transaction's snapshot was valid when read, but the combination breaks the rule.
Fixes:
- SERIALIZABLE in PostgreSQL tracks read/write dependencies and aborts one of the two with SQLSTATE 40001. Code must retry.
SELECT ... FOR UPDATEon all on-call rows makes the second transaction wait and then see the first one's change.- Materialize the rule as a row that both must update, such as a shift row with a counter and a CHECK.
SQLite avoids this specific case because its writers are serialized. The multi-session PostgreSQL behaviour is described from its documentation and was not run here.
Key points
- Write skew: decisions on overlapping reads, writes to different rows
- Snapshot isolation allows it
- SERIALIZABLE prevents it with retryable errors
- FOR UPDATE on the read set or a shared counter row also work
Common mistakes
- Assuming REPEATABLE READ prevents every anomaly
- Running SERIALIZABLE without retry logic
Follow-ups
- How would you implement retries for serialization failures?
- Why do row locks not help here by default?
Tips
- Tell it as a two-transaction timeline