Skip to the page

Correctness under concurrency · senior

Isolation levels and anomalies

Isolation levels decide which effects of concurrent transactions you can see: Postgres defaults to Read Committed (each statement sees data committed before it started), Repeatable Read gives one snapshot for the whole transaction, and Serializable makes the result equal to some one-at-a-time order, at the cost of retrying failed transactions.

The notes

What you must know

  • Anomalies: dirty read (seeing uncommitted data), non-repeatable read (same row read twice gives different values), phantom read (a re-run query returns new rows), serialization anomaly (a result no serial order could produce), and lost update (two read-modify-write cycles overwrite each other).
  • Postgres implements three levels: Read Uncommitted behaves as Read Committed (no dirty reads ever); Read Committed is the default; Repeatable Read (snapshot isolation, also prevents phantoms in Postgres); Serializable (SSI).
  • MySQL InnoDB defaults to Repeatable Read. Know your database's default.
  • Repeatable Read and Serializable can fail with SQLSTATE 40001 ('could not serialize access'); the application must retry the whole transaction.
  • Read Committed does not stop lost updates in read-then-write code; use atomic UPDATEs, SELECT ... FOR UPDATE, or optimistic version checks.
  • Higher isolation = fewer anomalies but more retries or blocking; pick per use case (reports might use Repeatable Read for a consistent snapshot).

The red pen

Common traps: mistake → fix

  • Mistake: Transactions make concurrent code safe automatically

    Fix: at Read Committed, two transactions can still read the same value and both write (lost update).

  • Mistake: Serializable is 'free correctness'

    Fix: it aborts conflicting transactions, and you must retry them.

Easy to hard

Questions interviewers ask, easy to hard

  1. What isolation levels exist? What is Postgres's default?
  2. Explain dirty, non-repeatable and phantom reads with examples.
  3. What is a lost update, and which levels prevent it?
  4. Your Serializable transaction failed with 40001. What should the code do?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview