← Back to SQL, page 12

sql-0231 · Hard senior

Two on-call doctors each check that at least one other doctor is on call, then go off call at the same time, leaving nobody. Which anomaly is this, and which isolation level prevents it?

This is write skew: each transaction reads an overlapping set of rows, makes a decision based on it, and writes a different row, so neither write conflicts directly. Snapshot isolation (PostgreSQL REPEATABLE READ) allows it. SERIALIZABLE prevents it; in PostgreSQL one transaction fails with a serialization error and must be retried. Explicit locks on the rows read also work.

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 call

The 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 UPDATE on 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