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.
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:
| Level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| Read Uncommitted | allowed | allowed | allowed |
| Read Committed | prevented | allowed | allowed |
| Repeatable Read | prevented | prevented | allowed |
| Serializable | prevented | prevented | prevented |
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
WHEREquery 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
A month-end report reads account 1 first. The two accounts hold 500 + 500 = 1,000 in total.
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.
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
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.
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:
- Put the rule in a constraint. A
UNIQUEindex, or in Postgres an exclusion constraint for overlapping bookings (EXCLUDE USING gist (room WITH =, during WITH &&)). The database checks it atomically. - Lock the rows you read.
SELECT ... FROM doctors WHERE on_call FOR UPDATEmakes 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. - Run at Serializable and retry on
40001.
What each database really does
| Anomaly | PG Read Committed (default) | PG Repeatable Read | PG Serializable | MySQL InnoDB Repeatable Read (default) |
|---|---|---|---|---|
| Dirty read | prevented | prevented | prevented | prevented |
| Non-repeatable read | allowed | prevented | prevented | prevented for plain reads |
| Read skew | allowed | prevented | prevented | prevented for plain reads |
| Phantom read | allowed | prevented | prevented | prevented for plain reads |
| Lost update | allowed | error 40001 | error 40001 | allowed |
| Write skew | allowed | allowed | error 40001 | allowed |
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 plainSELECTand anUPDATEcan 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:
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.
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:
Press Run (⌘ Enter) to see what happens.Two sales, stock 12 to 10, no lost update. The Postgres version with psycopg looks like this:
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,
COMMITitself may raise40001, so the try block must include it. - No side effects inside the transaction. If
worksends 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.
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])Match each anomaly to an example.
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 UPDATEwhen 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 DEFERRABLEwaits 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.
- 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.