Skip to content

Lesson 20 of 29Transactions and concurrency

Isolation Levels and Anomalies

Lost updates, read skew, phantoms and write skew: what each isolation level allows in Postgres, MySQL and SQLite, and how to choose and retry.

22 min read0/4 questions

Two customers buy the last laptop at the same moment and both get a confirmation email. Two on-call doctors each take themselves off call because the other one is still on, and now nobody is. A finance report sums account balances while a transfer runs and is off by exactly the amount transferred. None of these are bugs in the database. Each one is an anomaly that the default isolation level allows, and each one passes every test you run with a single user. This lesson names the anomalies, shows which levels prevent which, and gives you the patterns teams actually use to stay safe.

Why isolation is a dial

The safest possible behaviour is serial execution: run transactions one at a time, so none of them can interfere. Every database could do that, and it would be correct and slow. Real databases run transactions concurrently and give you isolation levels that decide how much interference is allowed in exchange for throughput and fewer aborted transactions.

The SQL standard defines four levels by the anomalies they forbid:

LevelDirty readNon-repeatable readPhantom read
Read Uncommittedallowedallowedallowed
Read Committedpreventedallowedallowed
Repeatable Readpreventedpreventedallowed
Serializablepreventedpreventedprevented

That table is what most tutorials stop at, and it is misleading in two ways. First, the standard only lists three anomalies, so it says nothing about lost updates or write skew, which are the ones that cause most production bugs. Researchers pointed this out back in 1995 (the paper "A Critique of ANSI SQL Isolation Levels"). Second, real databases implement the levels differently, and the same name can mean different behaviour in Postgres and MySQL. You need to know the anomalies by name, then know what your database really does.

The anomalies, one by one

  • Dirty read. You read a row another transaction wrote but has not committed. If it rolls back, you acted on data that never existed.
  • Non-repeatable read. You read a row twice in one transaction and get different values, because another transaction committed in between.
  • Phantom read. You run the same WHERE query twice and get a different set of rows, because another transaction inserted or deleted matching rows.
  • Read skew. You read two related rows at different moments and see a combination that never existed at any single point in time.
  • Lost update. Two transactions read the same value, both compute a new value from it, and both write. The second write silently overwrites the first.
  • Write skew. Two transactions read the same data, each checks a rule, each writes a different row, and together they break the rule that each one checked.

Read skew: the report that does not add up

Read skew under Read Committed
ReportPostgresTransferBEGIN; SELECT balance FROM accounts WHERE id = 1 → 500BEGIN; move 100 from account 1 to 2; COMMITSELECT balance FROM accounts WHERE id = 2 → 600total = 1,100fix: BEGIN ISOLATION LEVEL REPEATABLE READ

A month-end report reads account 1 first. The two accounts hold 500 + 500 = 1,000 in total.

1/5

Read skew is why reports, exports and backups (pg_dump uses a snapshot for exactly this reason) should run in a single transaction at Repeatable Read or higher.

Lost update: run it

The lost update is the one anomaly SQLite lets you reproduce for real, because it does not need two transactions to overlap inside the database. It only needs your code to read, compute in Python, and write back in separate steps. That is the most common shape of the bug in web apps.

Pythonlost_update.py
import os, sqlite3from shopdb import connect, show PATH = "/tmp/shop.db"for f in (PATH, PATH + "-journal", PATH + "-wal", PATH + "-shm"): if os.path.exists(f): os.remove(f)connect(PATH).close() # Two separate connections, like two web requests. Each statement commits on its own.alice = sqlite3.connect(PATH, autocommit=True, timeout=0)bob = sqlite3.connect(PATH, autocommit=True, timeout=0) def read_stock(conn): return conn.execute("SELECT stock FROM products WHERE id = 1").fetchone()[0] # The bug: read, compute in Python, write back.a = read_stock(alice)b = read_stock(bob)alice.execute("UPDATE products SET stock = ? WHERE id = 1", (a - 1,))bob.execute("UPDATE products SET stock = ? WHERE id = 1", (b - 1,))print("two laptops sold, stock went from 12 to", read_stock(alice)) # The fix: one atomic statement, with the rule in the WHERE clause.alice.execute("UPDATE products SET stock = 1 WHERE id = 1") # one laptop leftfor name, conn in (("alice", alice), ("bob", bob)): cur = conn.execute("UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock > 0") print(name, "bought it" if cur.rowcount == 1 else "sold out (rowcount 0)")print("final stock:", read_stock(alice))
Output
Press Run (⌘ Enter) to see what happens.

The atomic UPDATE reads and writes the row in one step that holds the row's write lock, so the second buyer sees the first buyer's change. The AND stock > 0 puts the business rule where the database can enforce it, and rowcount (or RETURNING in Postgres) tells you whether you won. When you can express the change as one statement, this is the best fix at every isolation level: no extra locks, no retries.

What Postgres does when the read-modify-write happens inside a transaction depends on the level. Under Read Committed, the second UPDATE ... SET stock = 4 simply overwrites the first (after waiting for its row lock if it has not committed yet): the update is still lost. Under Repeatable Read, the second UPDATE fails with could not serialize access due to concurrent update (SQLSTATE 40001), and you retry. MySQL's InnoDB at its default Repeatable Read does not detect this: the second write wins and the update is lost.

Write skew: two doctors

Write skew under Repeatable Read
AlicePostgresBobSELECT count(*) FROM doctors WHERE on_call → 2SELECT count(*) FROM doctors WHERE on_call → 2UPDATE doctors SET on_call = false WHERE name = 'alice'; COMMITUPDATE doctors SET on_call = false WHERE name = 'bob'; COMMITdoctors on call: 0

The rule: at least one doctor must be on call. Alice wants to go home. Her transaction sees two doctors on call, so it is fine for her to leave.

1/5

Write skew is the anomaly interviewers ask about, because snapshot isolation does not prevent it. The same shape appears in "a username must be unique" checks done in code, "a meeting room can only have one booking per slot", and "a user can have at most three active API keys". Your fixes, from simplest:

  1. Put the rule in a constraint. A UNIQUE index, or in Postgres an exclusion constraint for overlapping bookings (EXCLUDE USING gist (room WITH =, during WITH &&)). The database checks it atomically.
  2. Lock the rows you read. SELECT ... FROM doctors WHERE on_call FOR UPDATE makes Bob wait for Alice, and then his count is 1. This only works when the rows exist. You cannot lock a booking that has not been inserted yet, which is why phantoms need option 1 or 3.
  3. Run at Serializable and retry on 40001.

What each database really does

AnomalyPG Read Committed (default)PG Repeatable ReadPG SerializableMySQL InnoDB Repeatable Read (default)
Dirty readpreventedpreventedpreventedprevented
Non-repeatable readallowedpreventedpreventedprevented for plain reads
Read skewallowedpreventedpreventedprevented for plain reads
Phantom readallowedpreventedpreventedprevented for plain reads
Lost updateallowederror 40001error 40001allowed
Write skewallowedallowederror 40001allowed

The details that interviewers and incident reviews care about:

  • Postgres never allows dirty reads. If you ask for Read Uncommitted, you get Read Committed.
  • Postgres Repeatable Read is snapshot isolation. The whole transaction reads one snapshot, so it is stronger than the standard asks (no phantoms) but still allows write skew.
  • Postgres Serializable is SSI (serializable snapshot isolation). It runs like Repeatable Read and also tracks which transactions read data that others wrote. When it sees a pattern that could not happen in any serial order, it aborts one transaction. It does not block more than Repeatable Read; the cost is more aborted transactions and some memory for tracking. The guarantee only covers transactions that all run at Serializable.
  • MySQL InnoDB defaults to Repeatable Read, but it is a hybrid. Plain SELECTs read a snapshot. Locking reads and writes (SELECT ... FOR UPDATE, UPDATE, DELETE) read the latest committed row and take next-key locks (a row lock plus a lock on the gap before it) so others cannot insert into the range. So in one transaction a plain SELECT and an UPDATE can see different data.
  • SQLite is serializable, because only one connection can write at a time. In WAL mode, readers keep their snapshot while a writer commits. If a reader with an old snapshot then tries to write, SQLite refuses with SQLITE_BUSY_SNAPSHOT, its version of a serialization failure.

MVCC in one picture

Postgres and InnoDB implement snapshots with multi-version concurrency control: an UPDATE does not overwrite a row, it creates a new version, and each transaction reads the versions that were committed as of its snapshot. That is why readers never block writers and writers never block readers. How versions are stored on disk, and why it causes bloat, is in How Databases Store Data. Here is what the reader sees:

Row versions of product 1 in Postgres
  1. v1: stock = 12 xmin = 100 xmax = 205created by transaction 100, replaced by 205
  2. v2: stock = 11 xmin = 205 xmax = 0created by 205, still current
  3. Snapshot A, taken before 205 committeda Repeatable Read transaction that started early
  4. Snapshot B, taken after 205 committedany new statement or transaction

Every row version carries xmin, the transaction that created it, and xmax, the transaction that deleted or replaced it. An UPDATE is really insert-new plus mark-old.

1/4

Serialization failures must be retried

At Repeatable Read and Serializable, Postgres does not wait its way out of conflicts. It aborts a transaction with SQLSTATE 40001 (serialization_failure). Deadlocks, covered in Locks, deadlocks and safe concurrency, abort with 40P01. Both mean "this transaction did nothing; run it again". If your code does not retry, the user sees a 500 for a perfectly valid request.

SQLite can show the same pattern for real. In WAL mode, Bob reads stock inside a transaction, Alice commits a change, and Bob's write is refused because his snapshot is stale. The retry runs the whole transaction again, including the read:

Pythonretry.py
import os, random, sqlite3, timefrom shopdb import connect PATH = "/tmp/shop.db"for f in (PATH, PATH + "-journal", PATH + "-wal", PATH + "-shm"): if os.path.exists(f): os.remove(f)connect(PATH).close() alice = sqlite3.connect(PATH, autocommit=True, timeout=0)bob = sqlite3.connect(PATH, autocommit=True, timeout=0)alice.execute("PRAGMA journal_mode = WAL") def read_stock(conn): return conn.execute("SELECT stock FROM products WHERE id = 1").fetchone()[0] def with_retry(conn, work, attempts=5): for attempt in range(1, attempts + 1): try: conn.execute("BEGIN") result = work(conn, attempt) conn.execute("COMMIT") return result except sqlite3.OperationalError as err: conn.execute("ROLLBACK") if err.sqlite_errorname != "SQLITE_BUSY_SNAPSHOT" or attempt == attempts: raise print(f" attempt {attempt} failed: {err} ({err.sqlite_errorname}), retrying") time.sleep(random.uniform(0, 0.01 * 2 ** attempt)) # backoff with jitter def alice_buys(conn, attempt): stock = read_stock(conn) conn.execute("UPDATE products SET stock = ? WHERE id = 1", (stock - 1,)) def bob_buys(conn, attempt): stock = read_stock(conn) print(f"bob attempt {attempt} reads stock = {stock}") if attempt == 1: with_retry(alice, alice_buys) # alice commits between bob's read and write print("alice committed, stock is now", read_stock(alice)) conn.execute("UPDATE products SET stock = ? WHERE id = 1", (stock - 1,)) with_retry(bob, bob_buys)print("final stock:", read_stock(alice))
Output
Press Run (⌘ Enter) to see what happens.

Two sales, stock 12 to 10, no lost update. The Postgres version with psycopg looks like this:

db/retry.py
import random
import time
 
from psycopg import errors
 
RETRYABLE = (errors.SerializationFailure, errors.DeadlockDetected)  # 40001, 40P01
 
def run_serializable(pool, work, attempts=5):
    for attempt in range(1, attempts + 1):
        try:
            with pool.connection() as conn, conn.transaction():
                conn.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
                return work(conn)          # COMMIT happens as the block exits
        except RETRYABLE:
            if attempt == attempts:
                raise
            time.sleep(random.uniform(0, 0.05 * 2 ** attempt))

The rules that make retries safe:

  • Retry the whole transaction, from BEGIN, re-reading everything. Retrying only the failed statement reuses stale values.
  • The commit can fail too. Under Serializable, COMMIT itself may raise 40001, so the try block must include it.
  • No side effects inside the transaction. If work sends an email or calls a payment API, a retry repeats it. Do those after the commit, or through an outbox table written in the same transaction.
  • Cap the attempts and add jitter, so a hot row does not turn into a retry storm.
  • Only retry the retryable codes. A unique violation (23505) will fail the same way every time.
Quick check
What are the default isolation levels in Postgres and in MySQL's InnoDB?
Need a nudge? A hint rules out a wrong answer.
Predict the outputPython

Two connections in autocommit mode, stock starts at 12. What is printed?

a = alice.execute("SELECT stock FROM products WHERE id = 1").fetchone()[0]
b = bob.execute("SELECT stock FROM products WHERE id = 1").fetchone()[0]
alice.execute("UPDATE products SET stock = ? WHERE id = 1", (a - 1,))
bob.execute("UPDATE products SET stock = stock - 1 WHERE id = 1")
print(alice.execute("SELECT stock FROM products WHERE id = 1").fetchone()[0])
Need a nudge? Hints walk you through it.
Match the pairs0/6 matched

Match each anomaly to an example.

Choose an item, then its match on the other side.
Quick check
A booking system checks 'no other booking overlaps this slot' and then inserts. It runs at Postgres Repeatable Read. What actually stops double bookings?
Need a nudge? A hint rules out a wrong answer.

Choosing a level at work

Most production Postgres apps run at Read Committed and handle the dangerous cases explicitly:

  • Write single-statement changes: SET stock = stock - 1 WHERE stock > 0, SET balance = balance + $1, INSERT ... ON CONFLICT.
  • Put invariants in constraints: unique indexes, CHECK, foreign keys, exclusion constraints.
  • Lock rows you read and then update with SELECT ... FOR UPDATE when the logic cannot be one statement, or use optimistic version checks. Both are in Locks, deadlocks and safe concurrency.
  • Use Repeatable Read for reports and exports that need one consistent view. For long read-only reports at Serializable, BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE waits for a safe snapshot and then can never be aborted.

Choose Serializable when the invariants are complex, span many rows or tables, and are hard to express as constraints, and when every code path that touches that data can retry. Its big advantage is that you stop reasoning about each race one by one. Its cost is more 40001 errors under contention, so keep those transactions short and small.

Key terms
isolation level
A setting that decides which anomalies concurrent transactions may show. Postgres defaults to Read Committed, InnoDB to Repeatable Read.
snapshot isolation
Each transaction reads one consistent snapshot taken at its start. Postgres Repeatable Read. Prevents phantoms, allows write skew.
lost update
Two read-modify-write cycles on the same row where the second write overwrites the first.
write skew
Two transactions read overlapping data and write different rows, together breaking a rule each one checked.
SSI
Serializable snapshot isolation. Postgres's Serializable level: snapshot reads plus conflict tracking that aborts one transaction in a dangerous pattern.
MVCC
Multi-version concurrency control. Writes create new row versions, so readers see their snapshot without blocking writers.
serialization failure
SQLSTATE 40001. The database aborted a transaction to keep isolation; the app must retry it from the start.