How-To Guide

How to Choose the Right Transaction Isolation Level

Pick the right isolation level by understanding the anomalies each prevents: dirty reads, lost updates, write skew, phantoms and their costs.

On this page

  1. Introduction
  2. The Anomalies Named
  3. What Each Level Actually Guarantees
  4. Write Skew: The Subtle One
  5. Choosing Per Operation, Not Globally
  6. The Cost of Serialisable
  7. Testing Isolation Behaviour
  8. Common Pitfalls and Conclusion

Introduction

Isolation level is the trade-off between concurrency and correctness, and choosing wrong causes either subtle data corruption or unnecessary blocking. The standard levels, read uncommitted, read committed, repeatable read and serialisable, prevent progressively more anomalies at progressively more cost, but the details are full of surprises: repeatable read does not mean what many people think, and write skew slips through below serialisable. Choosing well means knowing which anomalies your application can tolerate and which it cannot.

The Anomalies Named

A dirty read sees another transaction’s uncommitted data. A non-repeatable read sees the same row change between two reads in one transaction. A phantom read sees new rows appear between two reads. A lost update is two transactions reading a value and writing back, one overwriting the other. Write skew is two transactions reading overlapping data and writing disjoint data, each individually valid but jointly violating a constraint.

These are ordered by severity and by the level needed to prevent them. The higher levels prevent more anomalies but allow less concurrency, so the choice is about which anomalies your invariants require you to prevent.

# anomaly -> minimum level that prevents it (typical engines)
dirty read            -> read committed
non-repeatable read   -> repeatable read (snapshot isolation)
phantom read          -> serialisable (or repeatable read, engine-dependent)
lost update           -> repeatable read with locking, or serialisable
write skew            -> serialisable (snapshot isolation does NOT prevent it)
# the trap: repeatable read often = snapshot isolation, which allows write skew

What Each Level Actually Guarantees

Read committed, the default in PostgreSQL and common elsewhere, prevents dirty reads but allows non-repeatable reads and phantoms. Each statement sees a fresh snapshot. It is adequate for most simple read-modify-write where the update is atomic in SQL, but not for multi-statement invariants.

Repeatable read in PostgreSQL is snapshot isolation: the whole transaction sees one snapshot, so reads are repeatable and phantoms are largely prevented, but two concurrent transactions can still each satisfy their own reads and violate a shared invariant (write skew). Serialisable adds predicate locking to prevent that, at the cost of more conflicts and retries.

# PostgreSQL level semantics
read committed : fresh snapshot per statement; dirty reads prevented
repeatable read: one snapshot for the whole tx (= snapshot isolation)
                 -> no non-repeatable reads, few/no phantoms
                 -> STILL allows write skew
serialisable   : snapshot isolation + predicate locks
                 -> prevents write skew; may abort tx with serialization error

Write Skew: The Subtle One

Write skew is the anomaly that catches teams using repeatable read expecting full correctness. Two transactions read a set of rows, each decides its own write is safe given what it read, and the two writes together break a constraint. Classic example: two on-call doctors each go off call because the other is on call, and both rules are satisfied at read time but the system ends with nobody on call.

Snapshot isolation cannot prevent write skew because the transactions write disjoint rows, so there is no write conflict to detect. Only serialisable isolation, with predicate locking or equivalent, catches it. If your invariants span rows you read but do not write, you need serialisable or an explicit lock.

-- Write skew: each tx checks "another doctor is on call" then goes off call.
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM doctors WHERE on_call AND id <> my_id;  -- sees 1 -> ok
UPDATE doctors SET on_call = false WHERE id = my_id;         -- both commit
COMMIT;
-- result: zero doctors on call; the invariant was jointly violated
-- fix: SERIALIZABLE, or SELECT ... FOR UPDATE on the other rows to conflict

Choosing Per Operation, Not Globally

A single global isolation level is usually wrong: most operations are fine at read committed, a few need strict serialisable, and a few need a specific lock. Choose per operation, using the lowest level that prevents the anomalies that operation’s invariants require, so you pay the concurrency cost only where it matters.

Atomic single-statement updates are safe at read committed because the statement sees a consistent snapshot and the update is atomic. Multi-statement read-then-write invariants need repeatable read or serialisable. An explicit row lock (SELECT … FOR UPDATE) is often a simpler and cheaper fix than raising the whole transaction to serialisable.

-- Cheaper than serialisable: lock the rows the invariant depends on.
BEGIN;  -- read committed is fine with an explicit lock
SELECT balance FROM accounts WHERE id = $1 FOR UPDATE;  -- lock the row
UPDATE accounts SET balance = balance - $2 WHERE id = $1;
COMMIT;
-- the lock conflicts with a concurrent transaction, preventing the anomaly

The Cost of Serialisable

Serialisable prevents every anomaly listed but introduces serialization failures: a transaction that conflicts with another is aborted and must be retried. At high contention this means retries and throughput loss, so an application using serialisable must handle the retry explicitly, with backoff and a limit.

Because serialisable aborts on conflict, it is best used for the specific transactions whose invariants demand it, not as a blanket default. If you do use it broadly, instrument the retry rate: a rising serialization failure rate is a sign the workload is contending and that either the design or the isolation choice needs revisiting.

async function serializableWithRetry<T>(db: Db, fn: (tx: Tx) => Promise<T>, attempts = 5): Promise<T> {
  for (let i = 0; i < attempts; i++) {
    try {
      return await db.transaction('serializable', fn);
    } catch (err) {
      if (isSerializationFailure(err) && i < attempts - 1) {
        await delay(2 ** i * 10);   // backoff and retry
        continue;
      }
      throw err;                    // real error or retries exhausted
    }
  }
  throw new Error('unreachable');
}

Testing Isolation Behaviour

Isolation bugs do not appear in serial tests; they need two concurrent transactions. Test the anomalies your application must survive by opening two connections and interleaving operations: attempt a lost update, a write skew, a non-repeatable read, and assert that the chosen level prevents it (or that your retry recovers from the serialization failure).

These tests are the only way to know that the level you chose actually protects the invariant you rely on, because level semantics vary between engines. A test that passes on your engine documents the real behaviour and catches a regression when an engine upgrade changes it.

# isolation tests to write
[ ] lost update: two read-modify-writes on one row -> assert no loss
[ ] write skew: two txs satisfying reads but violating an invariant
[ ] retry: serializable conflict -> assert the retry succeeds
[ ] phantom: insert matching a predicate read in another tx
# run on a real engine; semantics differ and change across versions

Common Pitfalls and Conclusion

Do not assume repeatable read prevents write skew; it usually does not. Do not raise everything to serialisable without handling retries, or you trade corruption for spurious failures. Do not rely on the default level without knowing what it prevents. Do not test isolation with serial tests. And do not forget that an explicit row lock often gives the needed guarantee more cheaply than a higher level.

Isolation level is a deliberate choice per operation: read committed for atomic single statements, repeatable read (snapshot isolation) for multi-statement reads where no cross-row invariant is at stake, and serialisable or an explicit lock where write skew or cross-row invariants matter. Know which anomalies each level prevents, test the concurrent cases, and handle serialization retries.

Sources: PostgreSQL: Transaction isolation, SQL standard isolation levels (Wikipedia), A Critique of Snapshot Isolation (Ports & Grittner).

FAQ

Does repeatable read prevent lost updates?
In engines where repeatable read is snapshot isolation, a write conflict on the same row is usually detected (often as a serialization error) so a lost update is prevented, but write skew on disjoint rows is not. Use an explicit row lock or serialisable for invariants spanning rows you read but do not write.
Is serialisable too slow to use generally?
It aborts conflicting transactions, so it needs retry handling and costs throughput under contention. Use it for the transactions whose invariants require it, and instrument the serialization failure rate, rather than making it a blanket default.

Related Examples