Course contents

04. Database Fundamentals Lesson 8 of 10

Isolation Levels

Watch two concurrent transactions produce dirty reads, non-repeatable reads, lost updates and write skew, and see what each Postgres isolation level prevents.

20 minAdvanced10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Isolation levels decide which concurrency anomalies a transaction can run into.
  • Postgres READ COMMITTED (default) reads the latest committed data per statement: no dirty reads, but non-repeatable reads, lost updates and write skew remain.
  • REPEATABLE READ is snapshot isolation in Postgres: one snapshot per transaction, concurrent updates of a row abort with 40001; write skew is still possible.
  • SERIALIZABLE (SSI) guarantees an outcome equal to some serial order by aborting transactions; applications must retry.
  • Atomic updates and SELECT … FOR UPDATE fix lost updates at READ COMMITTED, but a row lock caps a hot row at 1 ÷ hold time.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

An isolation level states how much concurrent transactions may affect each other. The SQL standard defines four levels (READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE) by the anomalies they rule out. Real databases implement them differently, so the useful question is always "what does my database allow at this level?". This lesson uses Postgres semantics.

Why it exists

Running transactions strictly one after another would be correct and very slow. Databases run them concurrently and use snapshots and locks so that each one sees a sensible view of the data. Full protection (serializability) costs aborts or blocking, so databases offer weaker levels that are cheaper but let specific anomalies through. Knowing which ones is the difference between "works in testing" and "loses money under load".

How it works

The anomalies.

  • Dirty read: reading another transaction's uncommitted change.
  • Non-repeatable read: reading the same row twice in one transaction and getting different committed values. Phantoms are the same with rows appearing or disappearing from a query result.
  • Lost update: two transactions read a value, both compute a new one and write it; the second write erases the first.
  • Write skew: two transactions read overlapping data, then write different rows based on what they read; each is fine alone, together they break an invariant (two doctors both leave the on-call rota).

Postgres levels. Postgres uses MVCC: readers see a snapshot of committed row versions and never block writers.

  • READ UNCOMMITTED is accepted and behaves exactly like READ COMMITTED.
  • READ COMMITTED (the default) takes a new snapshot for each statement. When an UPDATE has to wait for another transaction's row lock, it re-checks the newest committed version of the row after the wait and applies itself to it. So SET balance = balance - 50 is safe, while writing a value computed in the application is not.
  • REPEATABLE READ takes one snapshot at the first statement of the transaction (snapshot isolation). Non-repeatable reads and phantoms cannot occur. If the transaction tries to update or delete a row that a concurrent transaction changed and committed after the snapshot, it fails with SQLSTATE 40001 ("could not serialize access due to concurrent update").
  • SERIALIZABLE uses Serializable Snapshot Isolation (SSI): REPEATABLE READ plus tracking of read/write dependencies between concurrent transactions. When a pattern appears that no serial order could produce, one transaction fails with 40001. Reads still do not block.
Anomaly READ COMMITTED REPEATABLE READ SERIALIZABLE
Dirty read No No No
Non-repeatable read / phantom Possible No No
Lost update (read-modify-write) Possible No (40001 abort) No
Write skew Possible Possible No (40001 abort)

Explicit locking. At any level, SELECT … FOR UPDATE locks the selected rows until the transaction ends, so a second transaction doing the same waits before reading. FOR NO KEY UPDATE, FOR SHARE and SKIP LOCKED / NOWAIT refine this. A lock on a frequently updated row serialises all its writers: the row can complete at most 1 ÷ (lock hold time) changes per second.

When to use it

  • READ COMMITTED for most OLTP work, with atomic statements (SET x = x + 1, INSERT … ON CONFLICT, conditional UPDATE … WHERE) and constraints protecting invariants.
  • REPEATABLE READ for reports and exports that run several queries and need them to agree, and for read-modify-write code that can retry on 40001.
  • SERIALIZABLE when invariants span rows or tables and are hard to express as constraints or locks (rotas, double bookings, quota checks), provided every such transaction is retried on 40001.
  • FOR UPDATE when a short critical section must decide based on current data and retrying is undesirable.

When not to

  • Do not raise the whole application to SERIALIZABLE without retry logic: serialization failures become user-facing errors.
  • Do not use long REPEATABLE READ or SERIALIZABLE transactions for interactive work: old snapshots keep dead rows from being vacuumed and raise abort rates.
  • Do not take FOR UPDATE locks on hot rows across network round trips or user think time.

Trade-offs

Choice You gain You pay
READ COMMITTED No aborts from isolation, simplest You must guard read-modify-write and cross-row invariants yourself
REPEATABLE READ Stable snapshot, no lost updates 40001 aborts on contended rows; still allows write skew
SERIALIZABLE Correct as if run one at a time More aborts (including false positives), tracking overhead, mandatory retries
SELECT … FOR UPDATE Simple mental model, no retries Blocking, deadlock risk, hot rows capped by lock hold time
Atomic single statement Shortest lock, no retries Only works when the logic fits in one statement

Alternatives

  • Constraints and unique indexes: often the cleanest way to make an invariant impossible to break (UNIQUE, CHECK, exclusion constraints for overlapping bookings).
  • Optimistic concurrency control: a version column, UPDATE … WHERE id = $1 AND version = $2, retry when zero rows changed. Common in ORMs; works at READ COMMITTED.
  • Advisory locks (pg_advisory_xact_lock) to serialise work on a logical key that is not a single row.
  • Sharding a hot counter into several rows and summing them on read.

Failure modes

  • Silent lost updates from read-modify-write code at READ COMMITTED, often hidden inside ORM "load, change, save" flows.
  • Write skew under snapshot isolation that nobody tested for: double-booked rooms, overdrawn shared limits.
  • Retry storms: SERIALIZABLE or REPEATABLE READ under heavy contention aborting and retrying the same transactions repeatedly.
  • Lock queues on hot rows: one popular counter or inventory row limits the whole system; waits exceed lock_timeout or request timeouts.
  • Porting assumptions between databases: MySQL InnoDB's default REPEATABLE READ lets an UPDATE act on the latest committed row instead of aborting, so lost updates need explicit locking there.

In production

Know the default of every database you use (Postgres and SQL Server: READ COMMITTED; MySQL InnoDB: REPEATABLE READ; Oracle: READ COMMITTED, with "SERIALIZABLE" meaning snapshot isolation). Wrap REPEATABLE READ and SERIALIZABLE transactions in a retry loop for SQLSTATE 40001 (and 40P01 deadlocks) with jittered backoff, and keep them short. Set lock_timeout so lock queues fail fast. Find hot rows through lock waits (log_lock_waits, pg_locks) and fix them with atomic statements, SKIP LOCKED work queues or split counters.

Common misconceptions

  • "REPEATABLE READ means serializable enough." It allows write skew.
  • "SERIALIZABLE means transactions run one at a time." They run concurrently; the database aborts the ones that would break the illusion.
  • "Higher isolation is always slower." SSI readers do not block; the cost shows up as aborts under contention, not as uniformly slower queries.
  • "Isolation levels mean the same thing everywhere." The names are standard, the behaviour is not.

Interview angle

Expect a concurrency bug to diagnose: "two users book the last seat" or "a counter loses increments". A strong answer names the anomaly, says which level prevents it in the given database, and proposes the cheapest correct fix (an atomic conditional UPDATE, a unique constraint, FOR UPDATE, or SERIALIZABLE with retries), noting the hot-row ceiling of locking and the need for retry logic.

Model assumptions

Steps 1–7 are scripted illustrations of Postgres behaviour, not simulations: the engine has no snapshots, row versions, locks or serialization checks. Packets are slowed down so the interleaving is visible; values and outcomes are annotations, and where Postgres may raise the SERIALIZABLE error at different points, the illustration shows it at commit. Steps 8–9, the sandbox and the challenge are simulated: the hot row's lock is modelled as a resource with a single slot, each purchase holds it for an average of 15 ms (FOR UPDATE transaction) or 1.5 ms (atomic UPDATE), and a purchase that waits more than 1 s fails, like lock_timeout = 1s. Arrivals are random (Poisson), hold times lognormal. Numbers are illustrative, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. Never see uncommitted data

    Two transactions run at the same time. Tx A changes Alice’s balance from 500 to 400 but has not committed. Tx B reads Alice’s balance. Then A rolls back.

    If B had seen 400, it would have acted on a value that never existed: a *dirty read*. Postgres never allows this, at any level (it accepts READ UNCOMMITTED but treats it as READ COMMITTED): B sees the last committed value, 500.

    The isolation level decides which of these concurrency effects (*anomalies*) a transaction can run into. These steps are scripted illustrations with Postgres semantics, slowed down; the engine does not model snapshots or locks.

    Scene: Illustration: Tx A updates Alice’s row to 400 without committing; Tx B reads the row and gets the committed 500; Tx A rolls back and its change is discarded.

    Key idea: A dirty read sees another transaction’s uncommitted change. Postgres never allows it.

  2. 2. READ COMMITTED: the same query, two answers

    READ COMMITTED is Postgres’s default. Each statement gets a fresh snapshot of everything committed when it starts.

    B reads Alice: 500. Meanwhile A sets her balance to 400 and commits. B reads again in the same transaction: 400. Nothing uncommitted was seen, yet B’s two reads disagree: a *non-repeatable read*. New rows can appear between two queries the same way (*phantoms*). For a report that adds up several queries, the parts may not fit together.

    Scene: Illustration: Tx B reads Alice’s balance (500), Tx A updates it to 400 and commits, and Tx B’s second read returns 400.

    Key idea: READ COMMITTED: every statement sees the latest committed data, so two reads in one transaction can differ.

  3. 3. REPEATABLE READ: one snapshot for the whole transaction

    Same interleaving, but B runs at REPEATABLE READ. In Postgres that is snapshot isolation: the snapshot is taken at B’s first statement and kept until B ends.

    B reads 500, A commits 400, B reads again: still 500. Every query in B sees the database as of one moment, so reports add up and phantoms cannot appear either (Postgres is stricter here than the SQL standard requires). A’s change is not lost: it is visible to transactions that start after A committed.

    Scene: Illustration: the same interleaving at REPEATABLE READ. Tx B reads 500 twice, even though Tx A committed 400 in between, because B keeps the snapshot from its first statement.

    Key idea: REPEATABLE READ in Postgres = snapshot isolation: a transaction reads one consistent snapshot from start to end.

  4. 4. Read, compute, write: a change disappears

    Back at READ COMMITTED. Both transactions withdraw from Alice by reading her balance in the application and writing the computed result: A withdraws 100, B withdraws 50.

    Both read 500. A writes 400. B’s UPDATE … SET balance = 450 has to wait for A’s row lock, and when A commits it simply overwrites: Alice ends at 450 instead of 350. A’s withdrawal is gone: a *lost update*. No error, no warning.

    At this level the fixes are an atomic update (SET balance = balance - 50, which is re-evaluated against the committed row after the wait) or a locking read (SELECT … FOR UPDATE, so B waits before reading).

    Scene: Illustration: Tx A and Tx B both read Alice’s balance of 500. A writes 400 and commits; B’s write of 450 waits for A’s lock and then overwrites it. Alice ends at 450 instead of 350.

    Key idea: Read-modify-write in application code loses updates under READ COMMITTED. Update atomically or lock the row before reading.

  5. 5. REPEATABLE READ refuses to overwrite

    The same race at REPEATABLE READ. B’s UPDATE again waits for A’s lock. When A commits, Postgres sees that the row changed after B’s snapshot was taken and aborts B with ERROR: could not serialize access due to concurrent update (SQLSTATE 40001).

    B’s transaction must be retried from the start: it reads 400 and writes 350, the correct result. Snapshot isolation prevents lost updates by aborting, so code running at this level needs a retry loop.

    Not every database does this: MySQL’s InnoDB, whose default is REPEATABLE READ, lets the UPDATE proceed on the latest committed row, so there you still need atomic updates or SELECT … FOR UPDATE.

    Scene: Illustration: the same race at REPEATABLE READ. After Tx A commits, Tx B’s waiting update fails with a serialization error. B retries, reads 400 and writes 350.

    Key idea: In Postgres, REPEATABLE READ aborts the second writer of a row with 40001; the application retries the whole transaction.

  6. 6. Two valid decisions, one broken rule

    A hospital rule: at least one doctor must be on call. Alice and Bob are both on call and both feel unwell. Each runs, at REPEATABLE READ: count the doctors on call; if more than one, take myself off call.

    Both count 2 in their snapshots. A updates Alice’s row, B updates Bob’s. They write different rows, so there is no lock conflict and no concurrent-update error: both commit, and nobody is on call. This is *write skew*: each transaction was correct alone, the combination breaks an invariant that spans rows. Snapshot isolation does not prevent it.

    Scene: Illustration: both transactions count two doctors on call, then Tx A takes Alice off call and Tx B takes Bob off call. They write different rows, both commit, and nobody is on call.

    Key idea: Write skew: transactions read overlapping data and write different rows. Snapshot isolation lets both commit.

  7. 7. SERIALIZABLE detects the conflict

    Run both at SERIALIZABLE. Postgres uses serializable snapshot isolation (SSI): transactions still read snapshots without blocking, but Postgres also tracks what each one read and checks whether reads and writes of concurrent transactions form a pattern that no serial order could produce.

    Here it does: A’s write changes what B read, and B’s write changes what A read. Once A has committed, B fails with 40001 (here at its commit). B retries, now counts only one doctor on call and stays on duty. The guarantee: the result equals some one-at-a-time order of the transactions.

    The cost is aborts, occasionally false positives, and some tracking overhead. Every transaction at this level must be retryable.

    Scene: Illustration: at SERIALIZABLE, Tx A commits but Tx B’s commit fails with a serialization error. B retries, sees only one doctor on call and rolls back, so Bob stays on call.

    Key idea: SERIALIZABLE: the result equals some serial order. Postgres gets there by aborting transactions that could break it; you retry them.

  8. 8. Locking reads on a hot row queue up

    Locking is the other way to stop lost updates: SELECT seats_left … FOR UPDATE, check in the application, UPDATE, COMMIT. Correct at READ COMMITTED, but only one transaction at a time can hold the row lock, and it holds it across all those round trips, about 15 ms here. That caps the row at about 66 purchases per second.

    This part is simulated: the row lock is modelled as a resource with a single slot. Ticket sales open at 50 purchases per second, already enough to make buyers queue for the lock. One second in, demand jumps to 90 per second: the queue grows, and purchases that wait longer than lock_timeout (1 s) fail.

    Scene: Ticket buyers update one seats_left row with SELECT FOR UPDATE transactions that hold the lock for about 15 ms. When demand rises to 90 per second, purchases queue for the lock and some fail after waiting a second.

    Key idea: A row lock serialises its writers: throughput ≤ 1 ÷ lock hold time, whatever the isolation level.

  9. 9. One statement, short lock

    One second in, the purchase becomes a single statement: UPDATE events SET seats_left = seats_left - 1 WHERE id = 42 AND seats_left > 0. The check and the write happen inside the database, and the lock is held only for the statement and its commit, about 1.5 ms in this model.

    The queue drains within moments, failures stop and P95 drops to a few milliseconds. The isolation level did not change; the lock just got ten times shorter. For a hot row this is usually the first fix; beyond that, split the counter into several rows or batch the updates.

    Scene: One second in, purchases become a single atomic UPDATE that holds the row lock for about 1.5 ms. The queue drains and nothing fails.

    Key idea: Shorten what you hold: an atomic UPDATE keeps the row lock for one statement instead of a whole conversation.

  10. 10. Which level, which fix

    In Postgres: READ COMMITTED (default) prevents dirty reads; non-repeatable reads, lost updates and write skew remain possible. REPEATABLE READ adds one snapshot per transaction and aborts concurrent updates of the same row (40001), but allows write skew. SERIALIZABLE prevents all of these by aborting transactions; you retry them.

    Defaults differ: Postgres and SQL Server use READ COMMITTED, MySQL InnoDB uses REPEATABLE READ with different semantics. Rather than raising the level everywhere, many systems stay at READ COMMITTED and protect the few critical paths with atomic updates, FOR UPDATE, constraints, or SERIALIZABLE for just those transactions.

    Scene: Summary of the isolation levels with the two transactions and rows, and the ticket buyers updating the hot row with short atomic updates.

    Key idea: Know your database’s default and what it allows. Protect invariants explicitly: atomic statements, locks, constraints, or SERIALIZABLE with retries.