Video in progress
What is write skew, and why does this code break even under REPEATABLE READ?
-- The rule: at least one doctor must be on call per shift.
-- Right now Ali and Vali are on call. Both press "I'm leaving" at the same time.
-- T1 (Ali) -- T2 (Vali)
BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM duty SELECT count(*) FROM duty
WHERE shift_id = 5 AND on_call; -- 2 WHERE shift_id = 5 AND on_call; -- 2
UPDATE duty SET on_call = false UPDATE duty SET on_call = false
WHERE shift_id = 5 AND doctor = 'Ali'; WHERE shift_id = 5 AND doctor = 'Vali';
COMMIT; COMMIT;
Write skew is when two transactions read the same data, each updates a different row, and together they violate an invariant. Because they didn't write to the same row, snapshot isolation doesn't notice the conflict. You need SERIALIZABLE or an explicit lock.
📖 Answer
Each transaction saw in its own snapshot "there are 2 on call, it's fine if one leaves". They updated different rows, so there is no row-level conflict and both commit successfully. The result: nobody is on duty for the shift.
The solutions:
1. SERIALIZABLE. PostgreSQL uses SSI (Serializable Snapshot Isolation): it tracks reads as predicate locks and, if it finds a dangerous chain of dependencies, aborts one of the transactions with 40001. There is no lock waiting, you just need a retry.
2. An explicit lock. Lock the rows you read:
SELECT * FROM duty WHERE shift_id = 5 AND on_call FOR UPDATE;
Now T2 waits for T1 to finish, and when it re-reads, the number on call is 1. But this works only for rows that exist: if the invariant depends on a row not existing (say, two bookings must not overlap in time), there is nothing to lock.
3. Locking the parent row: SELECT ... FROM shift WHERE id = 5 FOR UPDATE. Then all operations touching that shift run one after another.
4. A constraint. For time range overlaps there is EXCLUDE USING gist, where the database itself guarantees it.
In an interview, being able to say "snapshot isolation is not serializable" and give the write skew example is a good signal.
Sign up to mark studied questions and save your progress.