Dirty reads, lost updates, phantoms, write skew and deadlocks reproduced with two real PostgreSQL sessions, and what each isolation level actually prevents.
Two customers click "Deposit £10" on the same account at the same moment. Both requests read a balance of £100, both add £10, both write £110. One deposit has vanished, and no error was logged anywhere. This bug, the lost update, ships to production constantly. It passes every test, because tests run one request at a time.
Transactions and isolation levels are the database's tools for preventing this kind of bug. They are also widely misunderstood: most developers believe "I used a transaction" means "I'm safe from concurrency bugs". This article shows, with real concurrent sessions against PostgreSQL 16, exactly which anomalies each isolation level allows, and how to write code that's correct anyway.
How the demos work: a Python script opens two real database connections, T1 and T2, and runs their statements in a precise interleaving. Every output block below is copied from a real run. The full harness is at the end, so you can reproduce it.
A transaction groups statements into one unit of work. The classic guarantees are ACID:
| Letter | Promise | How databases deliver it |
|---|---|---|
| Atomicity | All of the statements happen, or none of them do | Undo information plus the commit record; on ROLLBACK or crash, partial work vanishes |
| Consistency | Constraints (keys, foreign keys, checks) hold after every transaction | Constraint checks at statement or commit time. Your business rules are your job |
| Isolation | Concurrent transactions don't see each other's half-finished work | Locks and/or MVCC snapshots, configurable by isolation level |
| Durability | Once COMMIT returns, the data survives a crash | Write-ahead log fsynced at commit (see How a Database Works Inside) |
Atomicity and durability are close to absolute. Isolation is the negotiable one, and the SQL standard defines four levels of it, each allowing more or fewer anomalies in exchange for performance.
BEGIN; -- or: BEGIN ISOLATION LEVEL SERIALIZABLE;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT; -- both happen, or (on ROLLBACK / crash) neither
PostgreSQL uses MVCC: an update writes a new version of the row and leaves the old one in place. Each transaction reads through a snapshot, a list of which transactions had committed at the moment the snapshot was taken. Row versions created by transactions outside the snapshot are invisible.
The isolation level decides when the snapshot is taken:
READ COMMITTED a fresh snapshot for EVERY STATEMENT
(you always see the latest committed data)
REPEATABLE READ one snapshot for the WHOLE TRANSACTION,
taken at its first query (a frozen view of the database)
SERIALIZABLE same snapshot as REPEATABLE READ, PLUS tracking of
read/write dependencies to abort transactions that
could not have happened in any serial order
PostgreSQL's default is READ COMMITTED. So is Oracle's and SQL Server's. MySQL InnoDB defaults to REPEATABLE READ. Each anomaly below shows what that choice means.
A dirty read means seeing another transaction's uncommitted changes, data that may be rolled back a moment later. Let's ask for the weakest level, READ UNCOMMITTED, and try:
=== 1. Dirty read (T2 asks for READ UNCOMMITTED)
T1: update alice balance = 0 (not committed)
T2: select -> [(100,)]
T1: rollback
T2 still sees 100. PostgreSQL never allows dirty reads: READ UNCOMMITTED is accepted as syntax but behaves exactly like READ COMMITTED, because with MVCC there's no performance gain in reading uncommitted data. Some other databases (SQL Server with NOLOCK, MySQL at READ UNCOMMITTED) really will show you the 0, and if T1 rolls back, you've acted on data that never existed.
Read the same row twice in one transaction and get two different answers:
=== 2. Non-repeatable read, T1 at READ COMMITTED
T1: select -> [(100,)]
T2: update balance = 999; commit
T1: select again -> [(999,)]
=== 2. Non-repeatable read, T1 at REPEATABLE READ
T1: select -> [(100,)]
T2: update balance = 999; commit
T1: select again -> [(100,)]
At READ COMMITTED, each statement gets a new snapshot, so the second SELECT sees T2's commit. At REPEATABLE READ, T1 keeps its original snapshot and sees 100 both times, even though 999 is committed.
When does this matter? Any time you compute something from several reads, such as a report that sums balances across several queries, an export, or a check followed by an action. At READ COMMITTED, your reads can come from different points in time and add up to a total that never existed.
The same query returns a different set of rows, because another transaction inserted (or deleted) rows that match:
=== 3. Phantom read, T1 at READ COMMITTED
T1: count(balance > 10) -> [(2,)]
T2: insert carol 75; commit
T1: count again -> [(3,)]
=== 3. Phantom read, T1 at REPEATABLE READ
T1: count(balance > 10) -> [(2,)]
T2: insert carol 75; commit
T1: count again -> [(2,)]
The SQL standard allows phantoms at REPEATABLE READ. PostgreSQL's snapshot implementation goes further and prevents them, because a snapshot hides all later changes, including new rows. This is a good example of why you must learn your database's actual behaviour, not just the standard's minimum.
Now the bug from the introduction. Both transactions deposit £10 using the very common read-modify-write pattern: read the balance into the application, add 10 in code, write it back.
b = q(t, "select balance from accounts where id = 1")[0][0] # read
q(t, "update accounts set balance = %s where id = 1", (b + 10,)) # write b + 10
t.commit()
The real run:
=== 4. Lost update, both at READ COMMITTED: each deposits 10 via read-then-write
T1: read 100
T2: read 100
T1: write 110; commit
T2: write 110; commit
final balance -> [(110,)] (expected 120)
=== 4. Lost update, both at REPEATABLE READ: each deposits 10 via read-then-write
T1: read 100
T2: read 100
T1: write 110; commit
T2: ERROR: could not serialize access due to concurrent update
final balance -> [(110,)] (expected 120)
At READ COMMITTED: the default, and money vanishes without an error. At REPEATABLE READ, PostgreSQL notices that T2 is trying to update a row that changed after T2's snapshot, and aborts T2. The balance is still 110, but now the application knows. It must retry T2, which will read 110 and correctly write 120.
Fix 1: make the database do the arithmetic. An atomic UPDATE … SET balance = balance + 10 reads and writes under the row lock, so the second transaction waits and then applies its change to the new value:
=== 5a. Fix: atomic update
T1: commit (T2 has been blocked for 0.5 s)
T2: update done (it waited for T1)
final -> [(120,)]
This is the best fix whenever the change can be expressed in SQL.
Fix 2: lock the row when you read it. SELECT … FOR UPDATE takes a row lock, so a second reader that also uses FOR UPDATE waits until the first transaction commits:
=== 5b. Fix: SELECT ... FOR UPDATE
T1: select for update -> 100
T1: write 110 ; commit
T2: select for update -> 110 (waited 0.51 s)
final -> [(120,)]
Use this when the logic really must happen in application code (calling an external service, complex validation).
Fix 3: optimistic concurrency. Add a version column. Update with WHERE id = 1 AND version = 7, then check the affected row count. Zero rows means someone else changed it first, so re-read and retry. This avoids holding locks across slow application logic, and it's the standard pattern for HTTP APIs (an ETag and If-Match header map to it directly).
UPDATE accounts SET balance = 110, version = version + 1
WHERE id = 1 AND version = 7; -- 0 rows updated → conflict → retry
This is the subtle one, and REPEATABLE READ does not prevent it. The textbook example: a hospital requires at least one doctor on call. Alice and Bob are both on call and both feel ill. Each checks "is someone else on call?" and, seeing two, takes themselves off:
n = q(t, "select count(*) from doctors where on_call")[0][0] # both see 2
if n >= 2:
q(t, "update doctors set on_call = false where name = %s", (me,))
t.commit()
=== 6. Write skew, both at REPEATABLE READ: 'at least one doctor must stay on call'
T1 (alice): on call count -> 2
T2 (bob): on call count -> 2
T1: alice goes off call
T2: bob goes off call
T1: commit OK
T2: commit OK
on call now -> []
=== 6. Write skew, both at SERIALIZABLE: 'at least one doctor must stay on call'
T1 (alice): on call count -> 2
T2 (bob): on call count -> 2
T1: alice goes off call
T2: bob goes off call
T1: commit OK
T2: ERROR: could not serialize access due to read/write dependencies among transactions
on call now -> [('bob',)]
At REPEATABLE READ, nobody is on call and both transactions succeeded. Why didn't snapshot isolation catch it? Because the two transactions updated different rows. There was no write-write conflict to detect. Each one's decision was based on a read that the other one invalidated.
T1 (alice) T2 (bob)
reads {alice ✓, bob ✓} ──────────┐ ┌──── reads {alice ✓, bob ✓}
writes alice = off │ │ writes bob = off
▼ ▼
T1's read depends on bob's row, which T2 wrote;
T2's read depends on alice's row, which T1 wrote.
A cycle: no serial order (T1 then T2, or T2 then T1)
could produce this result.
PostgreSQL's SERIALIZABLE level (an algorithm called Serializable Snapshot Isolation) tracks exactly these read-write dependencies and aborts one transaction when it finds a dangerous cycle. Bob's transaction failed, so Bob stays on call.
Write skew appears wherever a decision is based on a set of rows: double-booking a meeting room ("no overlapping booking exists" → insert), overselling stock spread across rows, enforcing "max 3 active sessions per user", or claiming a unique username across tables. Fixes: SERIALIZABLE with retries, SELECT … FOR UPDATE on the rows you're reasoning about, or a real constraint (a unique index or an exclusion constraint) so the database enforces the rule itself.
What each level allows, in the SQL standard versus PostgreSQL's real behaviour (✗ = can happen, ✓ = prevented):
| Anomaly | Read Uncommitted (std) | Read Committed | Repeatable Read (std) | Repeatable Read (PostgreSQL) | Serializable |
|---|---|---|---|---|---|
| Dirty read | ✗ | ✓ | ✓ | ✓ | ✓ |
| Non-repeatable read | ✗ | ✗ | ✓ | ✓ | ✓ |
| Phantom read | ✗ | ✗ | ✗ | ✓ | ✓ |
| Lost update | ✗ | ✗ | ✓ | ✓ (aborts) | ✓ |
| Write skew | ✗ | ✗ | ✗ | ✗ | ✓ |
Warning: the names don't mean the same thing in every database. MySQL InnoDB's REPEATABLE READ uses snapshots for plain SELECTs but current data for UPDATE and SELECT … FOR UPDATE, so a lost update can occur there where PostgreSQL would abort. Oracle's "SERIALIZABLE" is really snapshot isolation and allows write skew. Always test the database you actually run.
Writers take row locks, held until the transaction ends. If two transactions lock the same rows in opposite orders, each waits for the other forever: a deadlock.
=== 7. Deadlock: T1 locks 1 then 2, T2 locks 2 then 1
T1: locked row 1
T2: locked row 2
T1: ERROR: deadlock detected
T2: commit OK
(detected after ~0.8 s; deadlock_timeout = 1s)
T1 holds row 1 ──── wants row 2 ───▶ held by T2
▲ │
└──────── wants row 1 ◀──── T2 holds row 2
PostgreSQL waits deadlock_timeout (1 second by default), then checks the lock graph for a cycle, and kills one transaction to break it. The fix is in your code: always lock rows in a consistent order, such as ascending id. A money transfer between accounts 7 and 3 should lock 3 first, then 7, whichever direction the money moves.
-- lock both rows in id order, whichever is the sender
SELECT id FROM accounts WHERE id IN (3, 7) ORDER BY id FOR UPDATE;
| Level | Use it when | Cost |
|---|---|---|
| Read Committed (default) | Most OLTP where each statement is self-contained, or where you use atomic updates, FOR UPDATE and constraints deliberately |
Cheapest. You must think about every read-modify-write |
| Repeatable Read | Reports, exports and multi-query reads that need one consistent view; detecting lost updates | Must handle serialization failures (retry). Long transactions keep old row versions alive |
| Serializable | Correctness rules that span rows (bookings, quotas, ledgers), or when the team can't reason about every interleaving | Most retries under contention, and some tracking overhead. Still far cheaper than a data-corruption incident |
At REPEATABLE READ and SERIALIZABLE, aborting a transaction with SQLSTATE 40001 (serialization_failure) is normal behaviour, not an error. The application must retry the whole transaction, including the reads:
import psycopg2
from psycopg2 import errors
def run_transaction(conn, work, attempts=5):
for attempt in range(attempts):
try:
with conn: # BEGIN … COMMIT, or ROLLBACK on exception
with conn.cursor() as cur:
return work(cur)
except (errors.SerializationFailure, errors.DeadlockDetected):
if attempt == attempts - 1:
raise # give up after a few tries
# loop: the next attempt runs the whole transaction again with fresh reads
Never retry only the failed statement. The decision was based on reads that are now stale, so the whole transaction must run again from the start.
SET x = x + 1, INSERT … ON CONFLICT) over read-modify-write in application code.CHECK, and exclusion constraints can't be raced.This is the core of the script that produced every output in this article. It needs PostgreSQL and psycopg2:
import psycopg2
from psycopg2 import errors
DSN = "dbname=postgres user=postgres host=localhost"
def conn(level="READ COMMITTED"):
c = psycopg2.connect(DSN)
c.set_session(isolation_level=level)
return c
def q(c, sql, args=None):
cur = c.cursor(); cur.execute(sql, args)
return cur.fetchall() if cur.description else None
# Write skew under REPEATABLE READ vs SERIALIZABLE
for level in ["REPEATABLE READ", "SERIALIZABLE"]:
setup = psycopg2.connect(DSN); setup.autocommit = True
setup.cursor().execute("""drop table if exists doctors;
create table doctors (name text primary key, on_call bool);
insert into doctors values ('alice', true), ('bob', true);""")
t1, t2 = conn(level), conn(level)
q(t1, "select count(*) from doctors where on_call")
q(t2, "select count(*) from doctors where on_call")
q(t1, "update doctors set on_call = false where name = 'alice'")
q(t2, "update doctors set on_call = false where name = 'bob'")
for name, t in (("T1", t1), ("T2", t2)):
try:
t.commit(); print(level, name, "commit OK")
except errors.SerializationFailure as e:
t.rollback(); print(level, name, "ERROR:", str(e).splitlines()[0])
The one idea to keep: a transaction guarantees all-or-nothing, but on its own it doesn't guarantee that concurrent transactions can't interfere. Isolation is a dial, the default setting allows real anomalies, and preventing them is a design decision you make on purpose.