Chapter 28Down the Rabbit Hole: Two Doctors, Zero On Call, and the Database That Noticed
A hospital rota rule: at least one doctor on call tonight. Alice and Bob are both on call and both feel sick. Each request counts the on-call doctors, sees 2, decides it's safe, and marks its own doctor off. Both checks passed. Nobody is on call.
I ran exactly this on a scratch PostgreSQL 18.4 server. At REPEATABLE READ both commits went through and the count ended at 0, with no error. At SERIALIZABLE the first commit succeeded and the second got:
SQLSTATE 40001: ERROR: could not serialize access due to read/write
dependencies among transactionsOn retry Bob counted 1 doctor and the app refused to let him leave. This post is about what happened between those runs: Serializable Snapshot Isolation (SSI), and the small theorem that makes it cheap.
Why the first run was allowed#
Databases keep multiple row versions (MVCC) and each transaction reads from a snapshot: snapshot isolation (SI). Its one rule for writers is first-committer-wins: two concurrent writes to the same row, the second loses.
That's the hole. Alice changed Alice's row, Bob changed Bob's. The write sets were disjoint, so the rule said nothing. The result is a state no one-at-a-time order could produce. Berenson et al. named it write skew (A5B) in their 1995 critique of ANSI isolation levels. Fekete et al.'s bank version: X = 70, Y = 80, rule X + Y > 0; each transaction reads both, one withdraws 100 from X, the other 100 from Y.
R1(X0,70) R2(X0,70) R1(Y0,80) R2(Y0,80) W1(X1,-30) C1 W2(Y2,-20) C2Both commit, X + Y = -50. This ships under the word "serializable": Oracle's SERIALIZABLE is SI, TiDB documents that its SI allows write skew, and PostgreSQL's REPEATABLE READ is plain SI. Worse, Fekete, O'Neil and O'Neil showed in 2004 that even a pure reader can observe a state no serial order produces.
The two bad options before SSI#
- Strict two-phase locking. Correct, but readers block writers. On RUBiS (Ports and Grittner), SI served 435 requests per second and strict 2PL 208.
- Fix the app by hand. Fekete et al. (2005): analyse every pair of transaction programs and "materialize" dangerous conflicts with
SELECT ... FOR UPDATEor a dummy write, so first-committer-wins catches them. Works for fixed TPC-C, which they proved safe under SI. Not for a codebase that changes weekly.
The goal: serializable, no blocking read locks, cost near plain SI.
Thinking in arrows#
Each transaction is a node; an arrow means an operation forces an order.
- wr: T2 read what T1 wrote. T1 first.
- ww: T2 overwrote what T1 wrote. T1 first.
- rw (antidependency): T1 read a version T2 later replaced. T1 first.
A history is serializable exactly when the graph has no cycle. In the doctors run, Bob read Alice's row and Alice replaced it (rw, Bob to Alice); Alice read Bob's row and Bob replaced it (rw, Alice to Bob). A cycle of length two.
rw: Bob read the row Alice replaced
┌───────────────────────────────────────┐
│ ▼
┌───────┐ ┌───────┐
│ Bob │ │ Alice │
└───────┘ └───────┘
▲ │
└───────────────────────────────────────┘
rw: Alice read the row Bob replaced"Track the graph, abort on cycle" is expensive: every edge type plus a graph search on the commit path. SSI is allowed to do something cheaper.
Two arrows in a row#
Under SI, wr and ww arrows can never join two concurrent transactions: a reader only sees versions committed before its snapshot, and first-committer-wins forbids concurrent overwrites. So only rw arrows can connect transactions that overlap in time.
From that, Fekete et al. (2005, Theorem 2.1, building on Adya) prove:
Every cycle in the dependency graph of an SI history contains three consecutive transactions T1 → T2 → T3 where both arrows are rw, T1 is concurrent with T2, T2 is concurrent with T3, and T3 is the first transaction in the cycle to commit. (T1 and T3 may be the same.)
The proof, in one paragraph
Take the transaction in the cycle that committed first, T3, and the arrow into it from T2. If that arrow were wr or ww, T2 would have committed before T3 started, contradicting T3 being first. So it's rw, and the timing forces overlap. Step back to T1 and the same argument makes T1 to T2 rw and overlapping. Two rw arrows in a row are unavoidable.
So SSI spots a local dangerous structure: a pivot T2 with a concurrent rw arrow in and a concurrent rw arrow out, where the "out" side committed first.
exists T1, T3 : T1 -rw-> T2 -rw-> T3,
T1 || T2, T2 || T3,
commit(T3) <= min(commit(T1), commit(T2))Every cycle contains one, so it never misses a real anomaly. It can abort things that were fine.
Sticky notes on what you read#
To see rw arrows the database must know who read what. PostgreSQL's SIREAD lock blocks nobody; it's a sticky note on a row saying "this transaction looked here".
Alice (T1) Bob (T2)
────────── ────────
BEGIN
SELECT count -> 2 BEGIN
SELECT count -> 2
notes: SIREAD(T1) and SIREAD(T2)
on rows 1,2 + index page
arrows: none yetEach read leaves a SIREAD note. Nothing blocks.
Notes outlive the reader, plus read-only tricks and the payoff
The notes outlive the reader. Alice's SIREAD locks survive her commit: a concurrent transaction might write a row she read after she commits, and that write is when the arrow appears. They're dropped once every overlapping transaction finishes. To bound memory, PostgreSQL summarizes old committed transactions into an on-disk structure, pg_serial.
Sometimes no note is needed. If the writer committed before the reader looked, the reader's MVCC visibility check hits a newer version it can't see. That proves the rw arrow from version metadata.
Read-only is cheap. A read-only transaction can only be the "in" end of a dangerous structure. If no concurrent writer could become the committed "out" side at start, its snapshot is safe: it drops all SIREAD locks and can never fail. READ ONLY DEFERRABLE waits for one. Ports and Grittner report 90% found one within 6 seconds, all within 20. pg_dump --serializable-deferrable uses it.
Payoff (same paper): under 7% overhead versus plain SI, and 422 requests per second against strict 2PL's 208 on RUBiS.
Where the arrows lie: false aborts#
A structure T1 → T2 → T3 with no path back from T3 to T1 is serializable (run T1, T2, T3), and SSI may kill it anyway. The bigger source in practice is granularity. SIREAD locks live in shared memory, so PostgreSQL promotes them. With the PostgreSQL 18 defaults I read off a live server (max_pred_locks_per_transaction = 64, max_pred_locks_per_page = 2, max_pred_locks_per_relation = -2): more than 2 tuple locks on a page become one page lock, and more than 32 on a relation become a relation lock. A relation lock means any write anywhere in the table creates an arrow.
The dive's script made this concrete: two transactions on unrelated rows.
| Case | A's SIREAD locks | Outcome |
|---|---|---|
| Far apart in the index (day3 vs day1500) | page, tuple | A ok, B ok |
| Same index leaf page (day3 vs day4) | page, tuple | A ok, B 40001 |
| Far apart, forced seq scan | relation | A ok, B 40001 |
Case 4: unrelated rows sharing a btree leaf page. The index scan took a page-granular lock and (my reading of the mechanism; the abort itself is measured) the update inserted a new index entry into that page. Case 5: a sequential scan always takes a relation lock.
tuple lock --(more than 2 on one page)--> page lock page lock --(more than 32 on a relation)--> relation lock index scan: tuple, then page a write nearby -> maybe an arrow seq scan: relation at once ANY write in table -> an arrow
So the planner decides your abort rate. A query that flips to a sequential scan, from stale statistics, a missing index or a small table, silently goes from tuple locks to a table lock. The docs suggest raising max_pred_locks_* and preferring index scans when 40001s spike.
More ways this goes wrong, and the retry loop
- Hot spots. Many check-then-act transactions on one counter row abort each other. Every 40001 becomes a retry, retries add load: a route into a metastable retry storm. Backoff matters.
- Idle in transaction. A wandered-off serializable session pins the SIREAD state of everything that overlapped it, without holding an ordinary lock.
- Mixed levels. SSI only protects
SERIALIZABLEtransactions. OneREAD COMMITTEDwriter is invisible to tracking, and write skew is back. - No retry loop, no serializability. The cost moves from "reads block" to "some commits fail". The app must rerun the whole transaction:
for attempt in range(5):
try:
with conn: # BEGIN ... COMMIT
run_transaction(conn)
break
except psycopg2.errors.SerializationFailure: # SQLSTATE 40001
time.sleep(0.01 * 2 ** attempt) # back off, then retryA sound algorithm doesn't make a sound implementation. Jepsen's 2020 analysis of PostgreSQL 12.3 found G2-item anomalies (antidependency cycles, exactly what SSI prevents) under SERIALIZABLE: six in a two-minute run, all involving a freshly inserted row whose conflict was attributed to the wrong transaction. It reached back to 9.5 and was fixed in the August 2020 minor releases. Jepsen's 2023 look at MySQL 8.0.34 on AWS RDS found G-single and G2-item at SERIALIZABLE in fault-free clusters.
What everyone else does#
| System | Approach |
|---|---|
| PostgreSQL (since 9.1, 2011) | SSI, built by Grittner and Ports on Cahill, Röhm and Fekete's 2008 algorithm. Cahill used two bits per transaction; PostgreSQL keeps real edge lists, enabling commit-order checks, pivot-first aborts and safe snapshots. |
| CockroachDB | Timestamp ordering and read refresh, same 40001 retry contract. |
| FoundationDB | Optimistic concurrency; aborts on any single overwritten read, not two rw arrows. |
The open question#
SSI itself looks settled. I found no 2024 to 2026 paper that changes Cahill or Ports. What's open is the trade-off: how close to exact cycle detection can you get cheaply? Exact detection needs wr and ww edges plus a graph search on the commit path. Ports and Grittner rejected that as too costly, citing a reported abort reduction of up to 40% for cycle testing (I couldn't check that at its source). The Extended Serial Safety Net certifier (2025) commits more transactions while staying serializable. Nobody has a scheme both near-exact and as cheap as SSI's local test.
Second: SIREAD locks are shared memory on one machine. Across shards they become distributed conflict tracking with clock skew and partial failures, and production systems chose OCC or timestamp ordering instead. I found no recent primary source on distributed SSI. Meanwhile Elle, PolySI, VeriStrong and Boomslang check from outside whether a database delivers the isolation it claims, which, given the Jepsen record, seems the right instinct.
The takeaway: the doctors bug is every check-then-act in a booking, quota or inventory system. SI lets it through quietly. SSI catches it by noticing two arrows in a row, and asks only for a retry loop and a watch on your query plans.
Sources#
- Berenson et al., A Critique of ANSI SQL Isolation Levels, SIGMOD 1995
- Fekete et al., Making Snapshot Isolation Serializable, ACM TODS 2005
- Cahill, Röhm, Fekete, Serializable Isolation for Snapshot Databases, SIGMOD 2008
- Ports and Grittner, Serializable Snapshot Isolation in PostgreSQL, PVLDB 2012
- PostgreSQL docs, Transaction Isolation
- PostgreSQL source, README-SSI
- Jepsen, PostgreSQL 12.3 and MySQL 8.0.34
- Kingsbury and Alvaro, Elle, VLDB 2020
- CockroachDB transactions and FoundationDB developer guide
- Kitazawa et al., Extended Serial Safety Net, 2025
- Cai et al., VeriStrong, VLDB 2026