Isolation Levels

Difficulty: Advanced

Question

Describe the four standard SQL isolation levels and which read anomalies each one prevents. What do popular databases use by default?

Answer

The SQL standard defines four isolation levels, from weakest to strongest: Read Uncommitted, Read Committed, Repeatable Read and Serializable. Each one rules out more concurrency anomalies: Read Committed prevents dirty reads, Repeatable Read also prevents non-repeatable reads, and Serializable also prevents phantom reads and every other anomaly, making concurrent transactions behave as if they ran one after another. Stronger levels are safer but cost more in locking, aborts or throughput.

The anomalies, with examples

  • Dirty read: T1 updates a balance to ₹0 but has not committed; T2 reads ₹0; T1 rolls back. T2 acted on data that never existed.
  • Non-repeatable read: T1 reads a product price of ₹499, T2 updates it to ₹549 and commits, T1 reads again and sees ₹549 inside the same transaction.
  • Phantom read: T1 runs SELECT COUNT(*) FROM bookings WHERE slot = '10am' and gets 4; T2 inserts a fifth booking and commits; T1 re-runs and gets 5. The rows matching a predicate changed.
  • Lost update and write skew: not in the original standard table, but real. Two doctors both check "at least one doctor is on call", both go off call, and now nobody is. Only Serializable prevents write skew in general.

The standard matrix

LevelDirty readNon-repeatable readPhantom read
Read UncommittedPossiblePossiblePossible
Read CommittedPreventedPossiblePossible
Repeatable ReadPreventedPreventedPossible (per standard)
SerializablePreventedPreventedPrevented

What real databases actually do

  • PostgreSQL: default Read Committed. Its Repeatable Read is snapshot isolation, which also prevents phantoms but still allows write skew. Serializable uses SSI (Serializable Snapshot Isolation) and aborts conflicting transactions with SQLSTATE 40001. Read Uncommitted behaves like Read Committed, so dirty reads never happen.
  • MySQL InnoDB: default Repeatable Read. Plain SELECTs read from a consistent snapshot; locking reads (SELECT ... FOR UPDATE) use next-key locks that block inserts into the gap, which prevents most phantoms.
  • SQL Server and Oracle: default Read Committed. SQL Server can use row versioning with READ_COMMITTED_SNAPSHOT; Oracle's "Serializable" is really snapshot isolation.

How they are implemented

Older engines used locking: shared locks for reads, held longer at higher levels. Modern engines mostly use MVCC: each transaction reads a snapshot, so readers do not block writers. Read Committed takes a new snapshot per statement; Repeatable Read keeps one snapshot for the whole transaction. Serializable adds either predicate/range locks or conflict detection.

Choosing a level in practice

Most applications run at Read Committed and protect critical sections explicitly with SELECT ... FOR UPDATE, atomic updates (SET stock = stock - 1 WHERE stock > 0) or optimistic version checks. Use Serializable for logic with complex invariants (seat booking, double-entry ledgers) and be ready to retry on serialization failures.

Isolation levels from weakest to strongest. Each level prevents everything the one above it does, plus one more anomaly.
  1. Read Uncommitted: May see other transactions' uncommitted changes.
  2. Read Committed: No dirty reads; new snapshot per statement.
  3. Repeatable Read: Rows you read do not change under you.
  4. Serializable: Equivalent to running transactions one at a time.

Code examples

Non-repeatable read at Read Committed vs Repeatable Read (PostgreSQL)

-- Session A
BEGIN ISOLATION LEVEL READ COMMITTED;
SELECT price_paise FROM products WHERE id = 1;   -- 49900

-- Session B (autocommit)
UPDATE products SET price_paise = 54900 WHERE id = 1;

-- Session A again
SELECT price_paise FROM products WHERE id = 1;   -- 54900 (changed!)
COMMIT;

-- Repeat with a stronger level
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT price_paise FROM products WHERE id = 1;   -- 54900
-- Session B updates to 59900 and commits
SELECT price_paise FROM products WHERE id = 1;   -- still 54900
COMMIT;

Read Committed takes a fresh snapshot for each statement, so committed changes appear mid-transaction. Repeatable Read pins one snapshot for the whole transaction.

Retrying a serialization failure

import psycopg
from psycopg import errors

def book_seat(conn, show_id, seat):
    for attempt in range(3):
        try:
            with conn.transaction():
                conn.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
                taken = conn.execute(
                    "SELECT 1 FROM bookings WHERE show_id=%s AND seat=%s",
                    (show_id, seat)).fetchone()
                if taken:
                    return False
                conn.execute("INSERT INTO bookings(show_id, seat) VALUES (%s, %s)",
                             (show_id, seat))
                return True
        except errors.SerializationFailure:
            continue  # SQLSTATE 40001: safe to retry
    raise RuntimeError("too much contention")

Serializable transactions can abort under contention, so the application must retry the whole transaction rather than treat the error as fatal.

Key points

  • Read Committed prevents dirty reads; Repeatable Read adds stable rows; Serializable prevents all anomalies.
  • Defaults: PostgreSQL, Oracle and SQL Server use Read Committed; MySQL InnoDB uses Repeatable Read.
  • Snapshot isolation prevents phantoms but still allows write skew.
  • Serializable transactions can fail and must be retried.
  • Most apps use Read Committed plus explicit locks or atomic updates for hot spots.

Common follow-up questions

  • What is write skew and which isolation level prevents it?
  • How does MVCC let readers avoid blocking writers?
  • What are gap locks and next-key locks in InnoDB?
  • How would you prevent overselling the last item in stock at Read Committed?

Interview tips

  • Draw the matrix, then immediately say how Postgres and MySQL differ from the standard; that is what impresses.
  • Give a concrete timeline example for each anomaly instead of only naming it.
  • Mention retries on serialization failure; many candidates forget Serializable can abort.

Concepts covered

Read Committed, Repeatable Read, Serializable, Dirty Read, Phantom Read, MVCC

More Database Design questions