Module 3 · Database designLesson 29 of 888 minAdvanced

Isolation levels

Isolation levels decide how much transactions running at the same time can see of each other's changes.

Try it

Step through the four levels from weakest to strongest. Count the surprises transaction 1 runs into at each level.

Databases run many transactions at the same time. Full isolation, making each one act as if it were alone, is safe but slow. So databases offer isolation levels, trading safety for speed.

The surprises (anomalies)

  • Dirty read: you see another transaction's change before it commits, and then it rolls back.
  • Non-repeatable read: you read a row twice and get different values, because someone committed in between.
  • Phantom read: you run the same query twice and new rows appear.
  • Lost update: two transactions read the same value, both change it, and one change silently overwrites the other.

The levels

LevelPrevents
Read uncommittedAlmost nothing
Read committedDirty reads
Repeatable read / snapshotAlso non-repeatable reads (and often phantoms)
SerializableEverything: the result matches some one-at-a-time order

PostgreSQL defaults to read committed; MySQL (InnoDB) to repeatable read. Most modern databases use MVCC (multi-version concurrency control): they keep old versions of rows, so readers see a consistent snapshot without blocking writers.

The lost update, in practice

Two people buy the last ticket at the same time. Both read "1 left", both write "0 left", both get a ticket. Fixes:

  • Atomic update: UPDATE stock SET n = n - 1 WHERE id = 7 AND n > 0, and check one row changed.
  • Lock the row: SELECT ... FOR UPDATE.
  • Optimistic check: store a version number and only write if it hasn't changed.
  • Serializable isolation: let the database detect the conflict and abort one transaction, then retry.

Stronger isolation costs throughput: more waiting, more aborts. Use the default where it's safe, and step up for money, stock and anything where a lost update would hurt.

Quick check

In one transaction you read a balance twice and get two different values, because another transaction committed in between. What is this called?