Transactions & Isolation Levels: Anomalies, Snapshots and Serializability


System Design Phase 5: Database Internals & Modeling
Core Lesson 19 of 86 15 min read Updated Nov 30, 2026

A conference room booking app runs on Postgres. The booking code is careful: inside a transaction it checks whether any booking overlaps 14:00 to 15:00 for room 7, and only inserts if none does. It has unit tests. It has passed QA. On the Monday after launch, two teams both receive confirmation emails for room 7 at 14:00.

The two requests arrived 12 ms apart. Both transactions ran the check, both saw zero overlapping rows, both inserted. Each transaction was correct on its own. Together they produced a state that no serial order of the two could have produced.

The team assumed “it’s in a transaction” meant “it’s safe”. A transaction guarantees atomicity: all of its writes commit or none do. How much it is protected from other transactions running at the same time is a separate dial called the isolation level, and the default on most databases is not the strongest setting.

What isolation levels are

Isolation is the I in ACID (the broader ACID picture lives in ACID vs BASE). The ideal is serializability: the result of running transactions concurrently is the same as running them one at a time in some order. Serializability is expensive, so databases offer weaker levels that allow specific anomalies in exchange for less blocking and fewer aborts.

Isolation is about concurrent transactions on one database. It is different from the replica consistency models in consistency models, which describe what readers see across copies of data. A database can be serializable and still serve stale reads from an async replica.

How it works: the anomalies

Each isolation level is defined by which anomalies it permits, so learn the anomalies first. Each one below has a concrete example you can reproduce with two psql sessions.

Dirty read

A transaction reads data another transaction has written but not committed. If the writer rolls back, the reader acted on a value that never existed.

sequenceDiagram
participant T1 as T1 refund
participant DB as Database
participant T2 as T2 report
T1->>DB: UPDATE balance 100 to 50 (uncommitted)
T2->>DB: SELECT balance
DB-->>T2: 50 (dirty)
T1->>DB: ROLLBACK
Note over T2: report shows 50, real value is 100

Postgres never allows dirty reads, even if you ask for READ UNCOMMITTED; it treats that level as READ COMMITTED.

Non-repeatable read

A transaction reads the same row twice and gets different values because another transaction committed in between. Example: an invoice job reads a product price of 10.00 to compute a subtotal, a price update to 12.00 commits, and the job reads the price again for the tax line. Subtotal and tax now disagree.

Phantom read

A transaction runs the same query with a predicate twice and gets a different set of rows because another transaction inserted or deleted matching rows. The room booking bug is a phantom problem: the “no overlapping rows” check is a predicate, and the row that would have made it fail did not exist yet.

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.

sequenceDiagram
participant A as T1 add 1 like
participant DB as Database
participant B as T2 add 1 like
A->>DB: SELECT likes
DB-->>A: 10
B->>DB: SELECT likes
DB-->>B: 10
A->>DB: UPDATE likes = 11
A->>DB: COMMIT
B->>DB: UPDATE likes = 11
B->>DB: COMMIT
Note over DB: two likes recorded as one

Read skew

A transaction reads two related rows at different moments and sees them in a state that never existed. Alice has 500 in checking and 500 in savings. A report reads checking (500). A transfer of 100 from checking to savings commits. The report reads savings (600) and tells Alice she has 1,100. Each read was of committed data; together they are inconsistent. Read skew is a non-repeatable read across two different rows, and it is why backups and analytics queries need a snapshot.

Write skew

Two transactions read an overlapping set of rows, make a decision based on what they read, and write to different rows. Neither overwrote the other, yet an invariant that spans the rows is broken.

The classic example: a hospital requires at least one doctor on call. Alice and Bob are both on call and both feel ill. Each runs “count doctors on call; if at least 2, set myself off call”. Both see 2, both update their own row, and nobody is on call.

sequenceDiagram
participant A as T1 Alice
participant DB as Database
participant B as T2 Bob
A->>DB: SELECT count WHERE on_call
DB-->>A: 2
B->>DB: SELECT count WHERE on_call
DB-->>B: 2
A->>DB: UPDATE alice SET on_call = false
B->>DB: UPDATE bob SET on_call = false
A->>DB: COMMIT
B->>DB: COMMIT
Note over DB: zero doctors on call, invariant broken

Write skew is the hardest anomaly to spot because there is no row both transactions wrote. The room double booking is write skew combined with a phantom: both transactions inserted different rows.

The ANSI levels, and why they are not enough

The SQL standard (SQL-92) defines four levels by three phenomena:

Level Dirty read Non-repeatable read Phantom
READ UNCOMMITTED Possible Possible Possible
READ COMMITTED Prevented Possible Possible
REPEATABLE READ Prevented Prevented Possible
SERIALIZABLE Prevented Prevented Prevented

In 1995 Berenson, Bernstein, Gray and colleagues published “A Critique of ANSI SQL Isolation Levels” and showed this table is broken in three ways:

  1. The definitions are ambiguous. Read strictly, they describe outcomes; read loosely, they describe any sequence that could lead to one. Only the loose reading matches what lock-based databases actually prevent.
  2. Anomalies are missing. The paper added dirty writes, lost updates, read skew and write skew to the vocabulary.
  3. Real systems did not fit. It defined snapshot isolation and showed that it prevents every anomaly in the ANSI table, including the ANSI phantom, yet still allows write skew. So snapshot isolation is not serializable, and it does not slot neatly into the four ANSI rows.

The practical result: the names are not portable. “REPEATABLE READ” in Postgres is snapshot isolation; in MySQL it is a snapshot for plain reads plus locking for writes; in the ANSI text it is something else again. Always check what your engine actually does.

Snapshot isolation

Under snapshot isolation (SI), each transaction reads from a consistent snapshot taken when it starts (Postgres takes it at the first statement). It never sees writes committed after that point. This falls out of the MVCC designs in storage engines: old row versions are already kept for readers.

For writes, SI uses “first committer wins”: if two concurrent transactions update the same row, the second one to commit is aborted. In Postgres REPEATABLE READ, the loser gets could not serialize access due to concurrent update (SQLSTATE 40001) and must retry. That prevents the lost update.

SI allows write skew because the conflict check only looks at rows both transactions wrote. Alice and Bob wrote different rows, so both commit.

Serializable snapshot isolation

Postgres SERIALIZABLE (since 9.1) implements serializable snapshot isolation (SSI), from Cahill, Rohm and Fekete’s 2008 work. Transactions still read from snapshots and never block each other for reads. Additionally, the database records what each transaction read (as predicate locks that do not block anyone) and watches for read-write dependencies between concurrent transactions. When it finds a pattern that could produce a non-serializable result, it aborts one transaction with SQLSTATE 40001.

In the doctor example, T1 read the rows T2 wrote and T2 read the rows T1 wrote. SSI sees that cycle and aborts one of them. The retry sees only one doctor on call and refuses.

The costs: some aborts are false positives, aborted work must be retried by the application, and the bookkeeping adds CPU and memory. Read-only transactions declared READ ONLY DEFERRABLE can wait for a safe snapshot and then run without any risk of abort, which suits long reports.

flowchart LR
RU["READ UNCOMMITTED<br/>dirty reads"] --> RC["READ COMMITTED<br/>each statement sees latest commit"]
RC --> SI["Snapshot isolation<br/>no lost updates, write skew possible"]
SI --> SSI["Serializable<br/>SSI or strict 2PL"]
RC -.->|"add FOR UPDATE<br/>or version checks"| SAFE["Correct for the<br/>specific invariant"]
SI -.->|"materialize the conflict"| SAFE
style RU fill:#FCEBEB,stroke:#A32D2D,color:#791F1F
style RC fill:#FAEEDA,stroke:#854F0B,color:#633806
style SI fill:#E1F5EE,stroke:#0F6E56,color:#085041
style SSI fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style SAFE fill:#F1EFE8,stroke:#888780,color:#444441

Defaults per database

Most bugs come from assuming a stronger level than the default.

Database Default Notes
PostgreSQL READ COMMITTED REPEATABLE READ is snapshot isolation. SERIALIZABLE is SSI.
MySQL InnoDB REPEATABLE READ Plain SELECTs read a snapshot taken at the first read. UPDATE, DELETE and locking reads see the latest committed row and take next-key locks. A plain SELECT then UPDATE can still lose an update.
Oracle READ COMMITTED Its SERIALIZABLE is snapshot isolation, so write skew is possible.
SQL Server READ COMMITTED (locking) READ_COMMITTED_SNAPSHOT turns it into statement-level snapshots, and Azure SQL Database enables that by default. A separate SNAPSHOT level gives transaction-level SI.
CockroachDB SERIALIZABLE READ COMMITTED is available and generally available since v24.1, for apps that want fewer retries.
Google Spanner SERIALIZABLE with external consistency Also offers REPEATABLE READ, implemented as snapshot isolation, for read-write transactions.
Amazon Aurora DSQL Snapshot isolation Equivalent to Postgres REPEATABLE READ, with optimistic concurrency: conflicts are detected at commit and the loser retries.

Note the MySQL subtlety. Its REPEATABLE READ sounds stronger than Postgres READ COMMITTED, but for a read-modify-write done with a plain SELECT, InnoDB happily lets the second UPDATE overwrite the first. Postgres REPEATABLE READ would abort it.

Pessimistic vs optimistic concurrency

Raising the isolation level for the whole application is rarely the first fix. Usually you protect the specific invariant.

Pessimistic: lock what you will change

SELECT ... FOR UPDATE takes a row lock that blocks other writers and other FOR UPDATE readers until commit. Read-modify-write becomes safe at READ COMMITTED:

BEGIN;
SELECT balance FROM accounts WHERE id = 42 FOR UPDATE;
-- application computes the new balance
UPDATE accounts SET balance = 450 WHERE id = 42;
COMMIT;

Variants: FOR UPDATE NOWAIT fails immediately instead of waiting, and FOR UPDATE SKIP LOCKED (Postgres 9.5 and later, MySQL 8.0 and later) skips rows another transaction holds. SKIP LOCKED is how you build a job queue on a table: each worker grabs the next unlocked job without contending with the others.

SELECT id, payload FROM jobs
WHERE status = 'ready'
ORDER BY id
LIMIT 10
FOR UPDATE SKIP LOCKED;

Pessimistic locking works well when conflicts are frequent. Its costs are lock waits that grow with transaction length, and deadlocks when two transactions lock the same rows in different orders. Always lock in a consistent order, such as ascending ID.

Optimistic: detect conflicts at write time

Add a version column. Read the row with its version, then make the write conditional:

UPDATE documents
SET body = 'new text', version = version + 1
WHERE id = 7 AND version = 12;
-- 1 row updated: you won. 0 rows: someone else changed it, re-read and retry.

No locks are held while the user edits or the service computes. This fits low-conflict workloads and long think time, such as a document editor or an HTTP API with If-Match ETags. DynamoDB condition expressions and compare-and-set in key-value stores are the same idea. When conflicts are frequent, optimistic schemes waste work on retries.

The simplest fix of all, when it applies: do the arithmetic in the database. UPDATE posts SET likes = likes + 1 WHERE id = 9 has no read-modify-write gap and no lost update at READ COMMITTED.

Where it breaks

Isolation stops at the database boundary. Two services, each with its own database, cannot be made serializable with each other by isolation levels. You need two-phase commit or a saga, and an idempotent retry path.

Serializable without retries is a bug. Under SSI, CockroachDB SERIALIZABLE, Spanner or Aurora DSQL’s optimistic model, aborts are a normal outcome. Code that treats SQLSTATE 40001 as a fatal error will fail under load. Retry the whole transaction, not the last statement.

Long transactions amplify everything. They hold locks longer, raise SSI abort rates, and block MVCC cleanup. Never hold a transaction open across a network call to another service or a user’s think time.

ORMs hide the read-modify-write. user.balance -= 50; user.save() reads, computes in the app and writes back: a textbook lost update at READ COMMITTED. Look for this pattern in code review.

Replicas break read-your-writes. A transaction that commits on the primary and then reads from a lagging replica sees old data regardless of isolation level; that is a replication problem covered in read replicas.

How to apply it

  • Start from your engine’s default and list the invariants that span rows or depend on reads: balances, inventory, uniqueness across a range, “at least one” rules.
  • For single-row counters, use atomic UPDATE ... SET x = x + 1.
  • For read-modify-write of one row with contention, use SELECT ... FOR UPDATE. With low contention and long think time, use a version column.
  • For invariants a constraint can express (uniqueness, non-overlap, foreign keys), use the constraint. It works at every isolation level.
  • For complex multi-row invariants, run those transactions at SERIALIZABLE and retry on 40001. You do not need the whole application at SERIALIZABLE.
  • Run reports and backups on a snapshot (REPEATABLE READ in Postgres) to avoid read skew.

Interview questions

1. What is the difference between snapshot isolation and serializable?

Snapshot isolation gives every transaction a consistent snapshot of committed data as of its start and aborts one of two concurrent transactions that write the same row. It prevents dirty reads, non-repeatable reads, read skew and lost updates. It allows write skew: two transactions read overlapping data and write different rows, each valid alone, together violating an invariant. Serializable guarantees the outcome equals some serial order, so write skew is impossible. Postgres achieves it with SSI, which tracks read-write dependencies and aborts a transaction when a dangerous pattern appears; the application must retry.

2. Two requests increment a counter by reading it and writing back the new value. Under which settings is an update lost, and how do you fix it?

At READ COMMITTED in any common database, and at MySQL InnoDB’s default REPEATABLE READ when the read is a plain SELECT, both transactions read 10 and both write 11. Postgres REPEATABLE READ and SERIALIZABLE would abort the second writer with a serialization error. The fixes, in order of preference: make it a single atomic statement (SET n = n + 1), lock the row with SELECT ... FOR UPDATE, or use an optimistic version check that updates only if the version is unchanged and retries otherwise.

3. Your team wants to switch Postgres to SERIALIZABLE everywhere to be safe. What do you advise?

It is correct but not free. Every transaction can now fail with SQLSTATE 40001, so every code path needs a retry loop that reruns the whole transaction, and side effects such as emails must happen after commit. Abort rates rise with contention and transaction length, and predicate tracking costs CPU and memory. Usually the better approach is targeted: constraints for invariants they can express, row locks or version columns for hot rows, and SERIALIZABLE only for the few transactions with complex multi-row invariants. Measure abort rates if you do switch.

✅ Key takeaways

  • A transaction gives atomicity; the isolation level decides which concurrency anomalies you still get.
  • Learn the six anomalies by example: dirty read, non-repeatable read, phantom, lost update, read skew and write skew.
  • The ANSI levels are ambiguous and incomplete; snapshot isolation prevents the ANSI phenomena but still allows write skew.
  • Defaults differ: Postgres, Oracle and SQL Server use READ COMMITTED, MySQL uses REPEATABLE READ, CockroachDB and Spanner use SERIALIZABLE.
  • Fix specific invariants with atomic updates, constraints, FOR UPDATE, SKIP LOCKED queues or version columns before raising the global level.
  • Serializable and optimistic schemes require retrying the whole transaction on SQLSTATE 40001.

🧠 Check your understanding

0 / 4
  1. 1Two doctors each check that two doctors are on call, then each sets only their own row to off call. Both commit. Which anomaly is this?

  2. 2Which isolation level in Postgres prevents the room double booking (check for overlap, then insert) without any extra locks or constraints?

  3. 3A MySQL InnoDB service at the default REPEATABLE READ does a plain SELECT of stock, then UPDATE stock = old value minus 1. What happens with two concurrent buyers?

  4. 4You build a job queue on a Postgres table with 20 workers. Which query lets workers claim jobs without blocking each other?

Where to go next

  • Indexing internals: how indexes make the predicates in these transactions fast, and why the planner sometimes ignores them.
  • Zero-downtime schema migrations: how DDL locks interact with long transactions, a common outage cause.
  • Two-phase commit: what to do when the transaction spans more than one database.
  • Saga pattern: the alternative to distributed transactions when you can tolerate compensations.

Finished this lesson?

Mark it complete to track your progress across the roadmap.