Explaining write skew with doctors example
Write skew occurs under snapshot isolation when two concurrent transactions read overlapping data and write disjoint rows, allowing both to commit without conflict but violating constraints spanning multiple rows. The classic example involves two doctors both on call; each transaction sees the other as on call, so each updates their own on_call status to off concurrently, resulting in no doctors on call—a state impossible under serializable isolation.
What makes snapshot isolation attractive to implementers is that it lets you take a consistent picture of the database at the start of a transaction, run against that picture, and then only check at commit time whether you have a write–write conflict with someone else. If no one else has touched the rows you are going to overwrite, you can commit without ever having been blocked.
That policy is sufficient to prevent lost updates, but it is weaker than full serializability. In particular it allows what Berenson et al. dubbed a “write skew”: two transactions make decisions based on the same snapshot and then go on to update different rows in a way that, taken together, violates an invariant.
The on‑call doctor example makes this concrete. Suppose you have a table
Doctors(doctor_id PRIMARY KEY, on_call BOOLEAN)
and an application‑level invariant “at least one doctor must be on call at all times”. Initially both rows are true:
Alice on_call = TRUE
Bob on_call = TRUE
When a doctor wants to go off call, the application does:
BEGIN;
SELECT on_call FROM Doctors WHERE doctor_id <> :me; -- is someone else on?
IF someone_else_on_call THEN
UPDATE Doctors SET on_call = FALSE WHERE doctor_id = :me;
COMMIT;
ELSE
ROLLBACK;
END IF;
Now start two such transactions concurrently, one for Alice (T1) and one for Bob (T2). Under snapshot isolation both T1 and T2 read the same snapshot in which the other doctor is still on call, so the IF test passes in both cases. They each update their own row – there is no write‑write conflict because they touch different primary keys – and both commits succeed. The final state has Alice = FALSE, Bob = FALSE, violating the “at least one on call” constraint.
There is no serial execution of those two transactions that produces that outcome: if T1 ran to completion before T2 started, T2 would see Alice off call and would not take Bob off call, and vice versa. A serializable scheduler would therefore force an abort or delay to prevent both commits. Under plain snapshot isolation, with its “first‑committer wins only on overlapping writes” rule, the anomaly is allowed.