Isolation levels and the anomalies catalogue
The four ANSI levels, the seven anomalies they were meant to name, and what Postgres and MySQL actually do at each one
Two agents, alice and bob, are on call. Two Postgres transactions at REPEATABLE READ each run SELECT count(*) FROM support_rota WHERE on_call; see 2; then each sets its own row to on_call = false and commits. What happens?
The previous chapter showed how a snapshot decides which row versions a transaction sees. An isolation level is a promise about which interleavings of concurrent transactions you might observe, and therefore which bugs your code must defend against by itself. This chapter is the catalogue: the anomalies by name, which level forbids which, what Postgres and MySQL actually implement under each name, and what code you write in response.
The ANSI levels and why they are not enough
SQL-92 defined four isolation levels by three phenomena it forbade:
| level | dirty read (P1) | non-repeatable read (P2) | phantom (P3) |
|---|---|---|---|
| READ UNCOMMITTED | possible | possible | possible |
| READ COMMITTED | not possible | possible | possible |
| REPEATABLE READ | not possible | not possible | possible |
| SERIALIZABLE | not possible | not possible | not possible |
A dirty read is reading a row another transaction wrote but has not committed. A non-repeatable read is reading the same row twice and getting two values because someone committed in between. A phantom is running the same predicate query twice and getting a different set of rows because someone inserted or deleted a matching row.
In 1995 Berenson, Bernstein, Gray, Melton and the O’Neils published “A Critique of ANSI SQL Isolation Levels”. Its argument has three parts, and every one of them still matters when you read a vendor’s documentation.
First, the phenomena are written in English that admits a strict reading (the bad history is forbidden) and a loose one (only the bad outcome is forbidden). The paper rewrites them as patterns over histories, so that w1[x]...r2[x]... (T1 writes x, T2 reads it before T1 ends) is P1 whatever happens afterwards.
Second, the table leaves out anomalies that matter. It adds:
- P0, dirty write: T2 overwrites a value T1 wrote but has not committed. If T1 then rolls back, there is no correct value to restore. Every real engine forbids this at every level, by holding write locks to commit.
- P4, lost update: T1 and T2 both read x, both write x based on what they read, and one write disappears. It is the stock-counter bug from the first chapter of this course.
- A5A, read skew: T1 reads x, T2 updates x and y and commits, T1 reads y. T1 sees an x from before and a y from after, a state that never existed. A transfer between two accounts read this way makes money vanish from the total.
- A5B, write skew: T1 reads x and y, T2 reads x and y, T1 writes x, T2 writes y. Each decision was valid against what it read; together they break a constraint that spans both rows. The on-call doctors problem.
Third, and most influential, the paper defines snapshot isolation: each transaction reads from a snapshot taken at its start and may commit only if no row it wrote was written by a transaction that committed after its snapshot. Snapshot isolation forbids P0, P1, P2, P3 in its strict ANSI form, P4 and A5A. It passes every phenomenon in the ANSI table for SERIALIZABLE, and it still allows A5B. So “no anomalies in the table” is not the same as serializable, and an engine that called snapshot isolation SERIALIZABLE (Oracle did, and still does) was conforming to the letter of the standard while permitting write skew.
Later work by Adya formalised all of this as cycles in a dependency graph between transactions (G0, G1, G2-item, G2), which is the vocabulary Jepsen and Hermitage use. Write skew is G2-item: a cycle made entirely of read-write anti-dependencies, which is why a level that tracks only writes can never catch it.
Watch each anomaly appear and disappear
The simulation runs four fixed schedules of two transactions against a small multi-version store. The slider sets the isolation level both transactions run at, using Postgres’s semantics for each. Step through DIRTY READ at level 0, then raise it to 1 and watch A’s read change from B’s uncommitted 900 to the committed 500. Run NON-REPEATABLE READ at 1 and then 2; at 2 the second read comes from the same snapshot as the first. PHANTOM behaves the same way, because at 2 a range query also reads from the snapshot. Then run WRITE SKEW at 2 and confirm that both transactions commit with nobody on call. Only at 3 does one of them abort, and the abort message names the read-write cycle.
Isolation levels as this sim implements them (PostgreSQL-style MVCC)
===================================================================
Level reads see commit rule
READ UNCOMMITTED other txns' uncommitted writes always commits
READ COMMITTED latest committed, at each read always commits
REPEATABLE READ snapshot taken at BEGIN abort if a row I write
changed since my snapshot
SERIALIZABLE snapshot taken at BEGIN same, plus abort on a
read-write dependency cycle
dirty read non-repeatable phantom write skew
READ UNCOMMITTED possible possible possible possible
READ COMMITTED no possible possible possible
REPEATABLE READ no no no* possible
SERIALIZABLE no no no no
* The ANSI standard allows phantoms at REPEATABLE READ. Snapshot-based
REPEATABLE READ (PostgreSQL) does not show them, because the re-run
query reads the same snapshot. It still allows write skew.
PostgreSQL treats READ UNCOMMITTED as READ COMMITTED; the RU row here
shows what the standard permits.
Write skew: T1 and T2 both read {alice, bob}; T1 writes alice, T2 writes bob.
T1 read what T2 wrote (rw edge T1 -> T2) and T2 read what T1 wrote
(rw edge T2 -> T1). That cycle has no serial order, so SERIALIZABLE
aborts whichever commits second. No row was written by both, so
first-committer-wins never fires. Alice and Bob are both on call. Each checks that at least two doctors are on call, then takes themself off. Start at 0 and raise ISOLATION one level at a time. Find the lowest level at which the hospital always keeps a doctor on call.
GOAL: at least one doctor is still on call after both transactions finish
What the simulation proves is the shape of the ladder: each level forbids one more class of history, and the last class, write skew, is invisible to anything that only compares writes. That is the cost structure too. Each step up the ladder either holds more locks or tracks more information, and the last step tracks every read.
What Postgres actually does at each level
Postgres accepts all four names and implements three behaviours. Its documentation table is worth memorising:
| requested level | what you get | dirty read | non-repeatable | phantom | lost update | write skew |
|---|---|---|---|---|---|---|
| READ UNCOMMITTED | READ COMMITTED | no | yes | yes | yes, for app-side read-modify-write | yes |
| READ COMMITTED (default) | a new snapshot per statement | no | yes | yes | yes, for app-side read-modify-write | yes |
| REPEATABLE READ | snapshot isolation | no | no | no | refused with 40001 | yes |
| SERIALIZABLE | serializable snapshot isolation | no | no | no | refused with 40001 | refused with 40001 |
READ UNCOMMITTED is READ COMMITTED. Postgres never shows you uncommitted data. The visibility rules from the previous chapter have no way to express it.
READ COMMITTED takes a fresh snapshot for every statement. Two SELECTs in one transaction can see different data. The subtle part is what an UPDATE does when it finds that a row matching its WHERE clause is being updated by another transaction: it waits for that transaction to finish, then, if it committed, re-reads the newest version of that row and re-evaluates the WHERE clause against it, and updates that version. So UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 7 is safe at READ COMMITTED: two of them serialise on the row lock and both decrements land. What is not safe is reading on_hand into your application, subtracting in Python, and writing the number back. That is P4, and READ COMMITTED permits it. Most lost updates in production are this pattern behind an ORM.
REPEATABLE READ is snapshot isolation. The snapshot is taken at the first query in the transaction, not at BEGIN, and kept until the end. If an UPDATE, DELETE or SELECT ... FOR UPDATE finds that the row was changed by a transaction that committed after the snapshot, it fails with ERROR: could not serialize access due to concurrent update, SQLSTATE 40001. This is first-updater-wins, and it is what turns the app-side lost update into an error you can retry. Phantoms are impossible because range queries read the snapshot too; the standard permits phantoms here and Postgres is stricter. Write skew is allowed.
SERIALIZABLE is serializable snapshot isolation (SSI), added in 9.1 and described by Ports and Grittner in their 2012 VLDB paper. It runs snapshot isolation and also records what each transaction read, as SIRead locks on tuples, pages or whole relations. These are not locks in the blocking sense: they never make anyone wait and cannot cause a deadlock. They are bookkeeping. When a transaction writes something another concurrent transaction read, Postgres records a read-write dependency. Fekete and colleagues proved in 2005 that every non-serialisable history under snapshot isolation contains a “dangerous structure”: two consecutive read-write dependencies between concurrent transactions. When SSI sees one, it aborts a transaction in it with ERROR: could not serialize access due to read/write dependencies among transactions, again SQLSTATE 40001.
SSI has false positives. It aborts on the dangerous structure, which every anomaly contains but which some correct histories contain too, and it coarsens its tracking under memory pressure: more than max_pred_locks_per_page (default 2) tuple locks on one page become a page lock, and enough page locks on one relation become a relation lock. A sequential scan always takes a relation-level SIRead lock, so a serializable transaction that scans orders conflicts with every concurrent writer to orders. The Postgres documentation’s advice for SERIALIZABLE workloads follows from that: keep transactions short, declare read-only ones READ ONLY, make sure hot queries use index scans, raise max_pred_locks_per_transaction (default 64, needs a restart) if you see relation-level SIRead locks in pg_locks, and drop explicit FOR UPDATE locks that SERIALIZABLE already makes unnecessary.
For long reports there is BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE: it may wait when it starts, until it can take a snapshot that is guaranteed safe, and then runs with no SSI overhead and no risk of being aborted. It is the right way to run a consistent backup-style read against a busy serializable workload.
The rule your code must follow at REPEATABLE READ or SERIALIZABLE: any transaction can fail with 40001 at any statement, including COMMIT, and the correct response is to roll back and re-run the whole transaction from the beginning, including the reads, because the decision you made was based on data that is now stale. Retrying only the failed statement is wrong. Retrying forever is wrong too; cap it at a handful of attempts with jittered backoff and surface the failure.
MySQL InnoDB is different under the same names
InnoDB’s default level is REPEATABLE READ, not READ COMMITTED, and its REPEATABLE READ is not snapshot isolation. Teams porting code between the two engines meet this as a bug in production.
At InnoDB REPEATABLE READ, a plain SELECT is a consistent read from a snapshot established by the transaction’s first read, as in Postgres. But UPDATE, DELETE, SELECT ... FOR UPDATE and SELECT ... FOR SHARE are locking reads that act on the latest committed version of the row, not the snapshot, and they do not fail if that version is newer than the snapshot. So the read-modify-write pattern loses updates silently: T1 and T2 both SELECT 100 from their snapshots, T1 writes 150 and commits, T2 writes 70 over it and commits. Hermitage, Martin Kleppmann’s test suite, records InnoDB REPEATABLE READ as permitting P4, where Postgres prevents it. The MySQL manual itself advises against mixing locking and non-locking reads in one REPEATABLE READ transaction for this reason.
What InnoDB adds instead is gap locking. A locking read or UPDATE with a range condition takes next-key locks: a lock on each index record it scans and on the gap before it, so no other transaction can insert into the range until it commits. That prevents phantoms for locking reads by blocking, not by snapshot, and it is why an InnoDB UPDATE ... WHERE created_at > ? on an unindexed column can lock most of a table against inserts. At READ COMMITTED, gap locking is turned off except for foreign-key and duplicate-key checks.
InnoDB SERIALIZABLE is REPEATABLE READ with every plain SELECT silently converted to SELECT ... FOR SHARE when autocommit is off. It is two-phase locking: it is serialisable, and it buys that by blocking readers behind writers and by producing deadlocks, which InnoDB detects and reports as error 1213.
| Postgres RR | InnoDB RR | Postgres SER | InnoDB SER | |
|---|---|---|---|---|
| plain SELECT | snapshot | snapshot | snapshot + SIRead | shared lock |
| UPDATE on a row changed after snapshot | 40001 | proceeds on newest | 40001 | blocks, then proceeds |
| app-side lost update | refused | allowed | refused | refused by blocking or deadlock |
| write skew | allowed | allowed unless reads are locking | refused | refused by blocking |
| phantoms in a range read | none (snapshot) | none for plain reads; locking reads block inserts | none | blocked by gap locks |
Choosing what to do about write skew
You have three ways to stop write skew in Postgres, and the lab does all three.
Run the transaction at SERIALIZABLE and retry on 40001. The database finds every instance, including ones you did not think of. The cost is the retry loop in every caller, some false-positive aborts, and SIRead bookkeeping. It works best when every transaction touching the data runs at SERIALIZABLE; a transaction at a lower level is invisible to SSI’s tracking.
Materialise the conflict with a row lock. SELECT ... FROM support_rota WHERE on_call FOR UPDATE locks every row the check read, so the second transaction blocks on the first and, at READ COMMITTED, re-evaluates its WHERE clause when it gets the lock. You must know which rows embody the constraint, and the trick fails when the constraint is about rows that do not exist yet (a booking that must not overlap any other booking; there is no row to lock until someone inserts it). For that case, lock a parent row (the meeting room) or use an exclusion constraint.
Express the rule as a constraint the database enforces. UNIQUE, EXCLUDE USING gist, a CHECK on a single row, or a trigger. When the rule fits a constraint, this is the strongest option, because no code path can forget it.
You will create a small rota table in the shop database, reproduce write skew by hand in two psql sessions, stop it with SERIALIZABLE and with FOR UPDATE, and then write the retry loop that SERIALIZABLE requires.
1. Create the table. In terminal 1:
docker compose exec db psql -U atlas shopCREATE TABLE support_rota (agent text PRIMARY KEY, on_call boolean NOT NULL);
INSERT INTO support_rota VALUES ('alice', true), ('bob', true);CREATE TABLE and INSERT 0 2. The rule the application enforces, and the database does not: at least one row has on_call = true.2. Write skew at REPEATABLE READ. Open terminal 2 with the same psql command. Run the statements in the order of the comments, alternating terminals.
-- T1 (terminal 1)
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM support_rota WHERE on_call; -- 2
-- T2 (terminal 2)
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM support_rota WHERE on_call; -- 2
-- T1
UPDATE support_rota SET on_call = false WHERE agent = 'alice';
COMMIT;
-- T2
UPDATE support_rota SET on_call = false WHERE agent = 'bob';
COMMIT;
-- either terminal
SELECT * FROM support_rota;on_call = f. No error anywhere. Each transaction wrote a row the other never wrote, so first-updater-wins had nothing to refuse.3. The same schedule at SERIALIZABLE. Reset, then repeat step 2 with SERIALIZABLE in both BEGINs.
UPDATE support_rota SET on_call = true;
-- now step 2 again, with BEGIN ISOLATION LEVEL SERIALIZABLE; in both terminalsUPDATE or its COMMIT fails with ERROR: could not serialize access due to read/write dependencies among transactions, followed by a DETAIL: Reason code: ... line and HINT: The transaction might succeed if retried. T2 is now aborted; type ROLLBACK;. The table shows bob still on call. If you run SELECT locktype, relation::regclass, mode FROM pg_locks WHERE mode = 'SIReadLock'; in T2 before its update, you see the predicate locks its count took: a relation-level lock, because a two-row table is read by a sequential scan.4. The fix by row lock, at READ COMMITTED. Reset, then:
-- T1
BEGIN;
SELECT agent FROM support_rota WHERE on_call FOR UPDATE; -- alice, bob
-- T2
BEGIN;
SELECT agent FROM support_rota WHERE on_call FOR UPDATE; -- blocks
-- T1
UPDATE support_rota SET on_call = false WHERE agent = 'alice';
COMMIT;
-- T2: the SELECT returns now
ROLLBACK;SELECT ... FOR UPDATE hangs until T1 commits, then returns one row, bob: at READ COMMITTED a locked row that changed is re-checked against the WHERE clause, and alice no longer matches. An application that counts the returned rows sees 1 and refuses. Try the same at REPEATABLE READ: T2’s FOR UPDATE fails instead with could not serialize access due to concurrent update, because it may not lock a row version newer than its snapshot. Either way the rule holds.5. The retry loop. Reset with UPDATE support_rota SET on_call = true;, then save this as rota.py on the host:
import sys, threading, time, random
import psycopg
from psycopg import IsolationLevel, errors
DSN = "postgresql://atlas:atlas@localhost:5432/shop" # your SHOP_PORT instead of 5432 if you set one
LEVEL = IsolationLevel[sys.argv[1]] # READ_COMMITTED, REPEATABLE_READ or SERIALIZABLE
LOCK = " FOR UPDATE" if "--for-update" in sys.argv else ""
def go_off_call(agent):
with psycopg.connect(DSN) as conn:
conn.isolation_level = LEVEL
for attempt in range(1, 6):
try:
with conn.transaction():
rows = conn.execute(f"SELECT agent FROM support_rota WHERE on_call{LOCK}").fetchall()
if attempt == 1:
time.sleep(0.5) # let the other thread read before either writes
if len(rows) < 2:
print(f"{agent}: only {len(rows)} on call, staying on")
return
conn.execute("UPDATE support_rota SET on_call = false WHERE agent = %s", (agent,))
print(f"{agent}: off call (attempt {attempt})")
return
except errors.SerializationFailure as e:
print(f"{agent}: attempt {attempt} failed: {e.diag.message_primary}")
time.sleep(random.uniform(0, 0.05 * 2 ** attempt))
print(f"{agent}: gave up after 5 attempts")
threads = [threading.Thread(target=go_off_call, args=(a,)) for a in ("alice", "bob")]
[t.start() for t in threads]; [t.join() for t in threads]
with psycopg.connect(DSN) as conn:
print("on call now:", [r[0] for r in conn.execute("SELECT agent FROM support_rota WHERE on_call")])
conn.execute("UPDATE support_rota SET on_call = true")python3 rota.py REPEATABLE_READ
python3 rota.py SERIALIZABLE
python3 rota.py READ_COMMITTED --for-updateoff call (attempt 1) and on call now: []. SERIALIZABLE: one goes off call on attempt 1, the other prints attempt 1 failed: could not serialize access due to read/write dependencies among transactions, retries with a fresh snapshot, sees one agent on call, prints staying on, and on call now: lists it. READ_COMMITTED with --for-update: no error at all; the second thread blocks for about half a second in its SELECT, then sees one row and stays on. The script resets the table at the end of each run.python3 rota.py SERIALIZABLE again, but first change only alice’s connection to IsolationLevel.REPEATABLE_READ (for example, set the level inside go_off_call based on the agent name). Write skew comes back intermittently: SSI tracks only serializable transactions, so a single caller at a lower level opens the hole for everyone. That is why SERIALIZABLE is set with ALTER DATABASE shop SET default_transaction_isolation = 'serializable' or per role, not per call site. Drop the table with DROP TABLE support_rota; when you are done.The shop is adding store credit. A customer's credit balance is the sum of rows in a credit_ledger table; a purchase inserts a negative row if the sum is large enough. The service runs at the Postgres default, READ COMMITTED, and two concurrent checkouts by the same customer can each see a balance of 50 and each spend 40. About 200 checkouts per second, a handful per customer per day. How do you make overspending impossible?
- PAPER A Critique of ANSI SQL Isolation Levels Berenson, Bernstein, Gray, Melton, O'Neil and O'Neil, 1995
The paper that named dirty write, lost update, read skew and write skew, and defined snapshot isolation. Ten pages and still the clearest statement of why the standard's table is not enough. Skip the cursor stability section unless you use it. Read: sections 2 to 4, and Table 4 (the isolation types characterised by possible anomalies).
- PAPER Serializable Snapshot Isolation in PostgreSQL Dan R. K. Ports and Kevin Grittner, 2012
How SERIALIZABLE in Postgres works from the people who built it: the dangerous-structure test, SIRead locks, the read-only optimisations behind DEFERRABLE, and the memory limits that cause lock promotion. Read sections 2 to 4 and the evaluation; the feature-interaction section is optional. Read: sections 2 (snapshot isolation versus serializability), 3 (SSI), 4 (read-only optimisations), 7 (evaluation).
- DOC Transaction Isolation
The authoritative table of what each level permits in Postgres, the exact error messages, and the list of practices for SERIALIZABLE workloads. Read all of section 13.2; it is short and every sentence matters.
- CODE Hermitage: testing transaction isolation levels Martin Kleppmann
Hand-run test scripts for each anomaly against Postgres, MySQL, Oracle, SQL Server and others, with a table of results. The fastest way to find out what a given engine really does at a given level; run the Postgres and MySQL files side by side.
- POST Jepsen: PostgreSQL 12.3 Kyle Kingsbury, 2020
Finds G2-item under SERIALIZABLE (a real SSI bug, fixed in 12.4) and explains why REPEATABLE READ allowing write skew is defensible under the standard. Read it for the Adya vocabulary and for the method of finding anomalies by checking histories.
- DOC Transaction Isolation Levels (InnoDB)
What InnoDB does at each level: consistent reads, next-key and gap locks, semi-consistent reads at READ COMMITTED, and SERIALIZABLE's implicit FOR SHARE. Read it next to the Postgres page and list every behaviour that differs under the same name.
- PAPER Making Snapshot Isolation Serializable Fekete, Liarokapis, O'Neil, O'Neil and Shasha, 2005
The theorem SSI rests on: every non-serialisable snapshot isolation history contains two consecutive read-write anti-dependencies. Read the first half for the static dependency graph; the TPC-C proof can be skipped. Read: the first half: definitions, the dependency graph and the dangerous-structure theorem.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.