Isolation Levels

Dirty reads, non-repeatable reads, phantoms, lost updates and write skew; the SQL isolation levels and what PostgreSQL and MySQL really do; snapshot isolation and serializability.

Advanced 4 min readLesson 10 of 14 Interview Q&A

Perfect isolation — every transaction behaving as if it ran alone — is expensive. Databases offer weaker isolation levels that allow certain anomalies in exchange for more concurrency. Many real bugs (double-booked seats, negative balances, oversold inventory) come from not knowing which anomalies your level permits.

The anomalies

AnomalyWhat happens
Dirty readT1 reads T2's uncommitted change; T2 rolls back, so T1 saw data that never existed
Non-repeatable readT1 reads a row twice and gets different values because T2 committed an update in between
Phantom readT1 runs the same range query twice and gets different rows because T2 inserted or deleted matching rows
Lost updateT1 and T2 both read a value, both compute a new one, both write; one update is silently overwritten
Write skewT1 and T2 read overlapping data, make decisions, and write different rows; each write is fine alone, but together they break an invariant

Lost update

T1 (buy 1)T2 (buy 1)read stock = 10read stock = 10write stock = 9write stock = 9
Two sales, but stock only dropped by one.

Write skew

Rule: at least one doctor must be on call. Alice and Bob are both on call; both request leave at the same moment.

T1 (Alice)T2 (Bob)count on call = 2 ✓count on call = 2 ✓set alice offset bob offcommitcommit
Each transaction saw two doctors on call; now there are none.

No row was written by both transactions, so row locks or "first committer wins" checks don't catch it.

The SQL standard levels

LevelDirty readNon-repeatable readPhantom
Read UncommittedPossiblePossiblePossible
Read Committed✗PossiblePossible
Repeatable Read✗✗Possible (per the standard)
Serializable✗✗✗ — and no write skew: equivalent to some serial order

What real databases do

DatabaseDefaultNotes
PostgreSQLRead CommittedRepeatable Read is snapshot isolation (no phantoms; write skew possible). Serializable is SSI: true serializability with aborts on conflict
MySQL InnoDBRepeatable ReadConsistent snapshot for plain reads; locking reads (FOR UPDATE) see the latest data and take gap/next-key locks to block phantoms
OracleRead Committed"Serializable" is snapshot isolation
SQL ServerRead Committed (locking)Optional snapshot isolation (READ_COMMITTED_SNAPSHOT)
CockroachDBSerializableDistributed SSI

Fixing the anomalies in practice

Lost updates

SQL
-- 1. Atomic update: let the database do the read-modify-write
UPDATE products SET stock = stock - 1 WHERE id = 42 AND stock > 0;

-- 2. Pessimistic: lock the row while deciding
BEGIN;
SELECT stock FROM products WHERE id = 42 FOR UPDATE;
UPDATE products SET stock = 9 WHERE id = 42;
COMMIT;

-- 3. Optimistic: version column, retry if someone else won
UPDATE products SET stock = 9, version = version + 1
WHERE id = 42 AND version = 7;      -- 0 rows updated → reload and retry

Write skew

  • Run the transaction at SERIALIZABLE and retry on serialisation failure (the cleanest fix in PostgreSQL and CockroachDB).
  • Or lock the rows the decision depends on: SELECT … FROM doctors WHERE on_call FOR UPDATE.
  • Or materialise the conflict: create a row both transactions must update (a per-shift row), or use a constraint (a unique index on bookings for the same room and time slot).
Retrying serialization failures
for (int attempt = 1; ; attempt++) {
    try {
        tx.execute(status -> { bookSeat(userId, seatId); return null; });
        break;
    } catch (CannotSerializeTransactionException | DeadlockLoserDataAccessException e) {
        if (attempt == 5) throw e;
        Thread.sleep((long) (Math.random() * 50 * attempt));   // jittered backoff
    }
}
Key takeaways
  • Anomalies: dirty read, non-repeatable read, phantom, lost update, write skew.
  • Levels: Read Uncommitted < Read Committed < Repeatable Read < Serializable.
  • Postgres defaults to Read Committed, MySQL to Repeatable Read; "Repeatable Read" is often snapshot isolation.
  • Snapshot isolation still allows write skew; Serializable (SSI) prevents it but requires retries.
  • Fix lost updates with atomic updates, FOR UPDATE, or optimistic versioning.
Interview questions
QTwo users try to book the last seat at the same time. How do you prevent double booking?medium

Make the database enforce it: a unique constraint on (event_id, seat_id) in the bookings table, or a conditional atomic update (UPDATE seats SET booked_by = ? WHERE id = ? AND booked_by IS NULL and check the affected row count). Alternatively lock the seat row with SELECT … FOR UPDATE, or use SERIALIZABLE isolation with retries.

QWhat's the difference between repeatable read and serializable?hard

Repeatable read guarantees a row you've read won't change underneath you (typically via a snapshot). Serializable additionally guarantees the overall result equals some serial execution, which rules out phantoms (in the strict standard) and write skew, where transactions read overlapping data and write different rows.