Full answer
Example: a hospital rule says at least one doctor must stay on call. Alice and Bob are both on call. Each runs: read the number on call (2), see that it is safe to leave, set own on_call to false. Run at the same time, both see 2, both update their own row, and both commit. Nobody is on call.
Why other levels miss it
- No row is updated by both transactions, so there is no write-write conflict to detect. Each transaction's snapshot was consistent when it read, but the combined result is not valid.
Fixes
- SERIALIZABLE: the database detects the dangerous dependency cycle (each transaction read data the other changed) and aborts one with 40001 (serialization_failure). Retry the whole transaction. Keep transactions short, because the tracking has a cost and can produce false positives.
- Explicit locking: lock the rows that form the rule (SELECT ... FOR UPDATE on all on-call rows, or on a parent row), so the transactions run one after the other.
- Constraints: model the rule so the database can enforce it (a counter row updated atomically, an exclusion constraint, a unique index). This is often the simplest.
- Materialise the conflict: update a shared row so that two transactions write the same row and conflict.
Every SERIALIZABLE write path needs retry logic with a limit and jitter.
const { Client } = require('pg');
(async () => {
const a = new Client(), b = new Client();
await Promise.all([a.connect(), b.connect()]);
const reset = () => a.query(`DROP TABLE IF EXISTS bk31_doctors; CREATE TABLE bk31_doctors (name text PRIMARY KEY, on_call boolean NOT NULL);
INSERT INTO bk31_doctors VALUES ('alice', true), ('bob', true)`);
const onCall = async (c) => (await c.query('SELECT count(*)::int AS n FROM bk31_doctors WHERE on_call')).rows[0].n;
// Each doctor asks to go off call only when at least two are on call.
async function scenario(level) {
await reset();
await a.query(`BEGIN ISOLATION LEVEL ${level}`); await b.query(`BEGIN ISOLATION LEVEL ${level}`);
const [seenByA, seenByB] = [await onCall(a), await onCall(b)]; // both see 2
if (seenByA >= 2) await a.query("UPDATE bk31_doctors SET on_call = false WHERE name = 'alice'");
let outcome = 'both committed';
try {
if (seenByB >= 2) await b.query("UPDATE bk31_doctors SET on_call = false WHERE name = 'bob'");
await a.query('COMMIT');
await b.query('COMMIT');
} catch (err) {
outcome = `second transaction failed with ${err.code}`;
await a.query('COMMIT').catch(() => {}); await b.query('ROLLBACK');
}
return `${level.padEnd(16)} ${outcome}, on call afterwards: ${await onCall(a)}`;
}
console.log(await scenario('REPEATABLE READ'));
console.log(await scenario('SERIALIZABLE'));
// The retry sees the new state and refuses the change.
await b.query('BEGIN ISOLATION LEVEL SERIALIZABLE');
const nowOnCall = await onCall(b);
console.log('retry of the failed request: on call =', nowOnCall, '->', nowOnCall >= 2 ? 'allowed' : 'refused, one doctor must stay');
await b.query('ROLLBACK');
await a.query('DROP TABLE bk31_doctors');
await Promise.all([a.end(), b.end()]);
})();Two connections are interleaved in a fixed order against the local PostgreSQL. The serializable failure can appear on the update or on the commit of the second transaction, and the script handles both places. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): REPEATABLE READ both committed, on call afterwards: 0 SERIALIZABLE second transaction failed with 40001, on call afterwards: 1 retry of the failed request: on call = 1 -> refused, one doctor must stay
Key points
- Write skew is a rule broken by two transactions that update different rows.
- Snapshot isolation does not detect it.
- SERIALIZABLE aborts one transaction with 40001; retry it.
- Alternatives: locks on the rule's rows, constraints, or a shared row.
- Always add retry logic for serializable transactions.
Common mistakes
- Assuming REPEATABLE READ is enough for multi-row rules.
- Using SERIALIZABLE and not retrying 40001.
- Long transactions that make serialization failures frequent.
- Checking the rule in the application only, with no database support.
- Retrying forever with no limit.
Follow-ups
- How does PostgreSQL implement serializable snapshot isolation?
- How would a unique or exclusion constraint prevent double booking?
- What is a phantom, and how is it related to write skew?
Tips
- Tell the on-call story.
- State why snapshots miss it.
- List four fixes.