← Back to SQL, page 19

sql-0364 · Hard senior

A nightly report that checks 'at least one doctor is on call' let both doctors go off call at the same time. Which isolation problem is this, and how do you prevent it?

This is write skew: two transactions each read that two doctors are on call, each updates a different row to go off call, and neither sees the other's change, so the rule breaks. Snapshot isolation (PostgreSQL REPEATABLE READ) allows it. Use SERIALIZABLE, which aborts one transaction, or lock the rows read with SELECT ... FOR UPDATE.

Full answer

Timeline under snapshot isolation:

  1. T1 reads: on-call count = 2. T2 reads: on-call count = 2.
  2. T1 sets Alice off call. T2 sets Bob off call. Different rows, so no write conflict.
  3. Both commit. On-call count is now 0.

Prevention:

  • SERIALIZABLE in 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 UPDATE locks 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