# Transaction Isolation

**Also known as:** Read committed · Snapshot · Serializable  
**Category:** Data & Storage (Where the data lives)  
**Complexity:** 4/5  
**Guide:** https://layra4.dev/architectures/data-storage/transaction-isolation

*What one transaction may see of another, and which bugs each level lets through.*

Many transactions run at once. Isolation decides how much they can see of each other's unfinished or just-finished work. Full isolation, called serializable, means the result is the same as if they had run one after another. Weaker levels let some interleavings through in exchange for less blocking and fewer aborts.

The SQL standard names four levels, but real engines implement them differently. Postgres defaults to read committed. MySQL's InnoDB defaults to repeatable read. Oracle's "serializable" is really snapshot isolation. The names are less useful than the question: which anomalies can my default produce, and which of my transactions care?

> **In one sentence.** An isolation level is a list of anomalies the database promises to prevent. Know your engine's default, fix lost updates with atomic writes or locks, and retry when serializable aborts.

## Origin (1976)

Jim Gray and colleagues described "degrees of consistency" for lock-based databases, which became the four SQL-92 levels. In 1995 Berenson et al. showed the standard's definitions were ambiguous and named snapshot isolation. In 2008 Cahill, Röhm and Fekete made snapshot isolation serializable (SSI), which Postgres adopted in 9.1.

## The anomalies and the levels

### Dirty read and non-repeatable read (Fuzzy read)

A dirty read sees another transaction's uncommitted write, which may later roll back. A non-repeatable read reads the same row twice and gets two values, because someone committed in between.

- Read committed prevents dirty reads
- Each statement sees a fresh snapshot, so two reads can differ
- A report that sums several tables can see a mix of before and after

### Phantom

A query by condition returns a different set of rows the second time, because another transaction inserted or deleted a matching row. Locking the rows you read does not help, because the new row did not exist yet.

> select count(*) from bookings where room = 7 and day = '2026-11-06';

### Lost update

Two transactions read the same value, each changes it in application code, and each writes it back. The second write silently replaces the first. This is the most common isolation bug in web apps.

> both read stock = 10; both write stock = 9; one sale is gone

### Write skew

Two transactions read the same set of rows, check a rule, and each write a different row. Each write is fine alone; together they break the rule. Snapshot isolation allows it.

> two doctors each see two on call, and each goes off call

### Snapshot isolation and MVCC (Repeatable read in Postgres)

The database keeps several versions of each row (MVCC, multi-version concurrency control). Each transaction reads from one consistent snapshot taken at its start, so readers never block writers. It prevents dirty reads, non-repeatable reads and phantoms, but not write skew.

- Postgres repeatable read aborts a concurrent update to the same row
- InnoDB repeatable read does not: plain reads use the snapshot, writes see the latest row
- Oracle calls it serializable

### Serializable (SSI · Two-phase locking)

Every anomaly is prevented. Postgres does it with SSI: transactions run on snapshots, and the database aborts one when it detects a dangerous pattern of reads and writes. MySQL and SQL Server do it mostly with locks, which block instead.

> ERROR: could not serialize access ... (SQLSTATE 40001)

## Design rules

### Know your default, and write it down

Postgres, SQL Server and Oracle default to read committed; InnoDB defaults to repeatable read. Check the setting your driver or pool actually uses, and note in the code which transactions rely on something stronger.

### Fix lost updates in the write, not the read

Prefer an atomic statement such as update stock set n = n - 1 where n > 0. When the logic must live in code, lock the row with select … for update, or add a version column and update where version matches.

### Guard invariants that span rows

A rule like "at least one doctor on call" or "no two bookings overlap" needs serializable, a for update on every row the check reads, or a constraint. Postgres exclusion constraints stop overlapping ranges in the database itself.

### Retry the whole transaction on a serialization failure

Serializable and Postgres repeatable read abort with SQLSTATE 40001; deadlocks give 40P01. Roll back, wait a jittered moment and rerun everything from the first read. Keep emails and API calls outside the retried block.

## Examples

### Serializable with a retry loop, guarding a rule across rows

```typescript
const RETRYABLE = new Set(['40001', '40P01']);  // serialization_failure, deadlock_detected

export async function inTransaction<T>(
  work: (tx: Tx) => Promise<T>,
  { isolation = 'serializable', attempts = 5 } = {},
): Promise<T> {
  for (let attempt = 1; ; attempt++) {
    const tx = await pool.begin('isolation level ' + isolation);
    try {
      const result = await work(tx);
      await tx.commit();                       // the conflict can surface here, at commit
      return result;
    } catch (err) {
      await tx.rollback();
      const code = (err as { code?: string }).code ?? '';
      if (!RETRYABLE.has(code) || attempt === attempts) throw err;
      await sleep(Math.random() * 10 * 2 ** attempt);   // jittered backoff, then rerun it all
    }
  }
}

// The rule spans rows: at least one doctor must stay on call for the shift.
export const goOffCall = (shiftId: string, doctorId: string) =>
  inTransaction(async (tx) => {
    const { onCall } = await tx.queryOne(
      'select count(*)::int as "onCall" from on_call where shift_id = $1 and on_duty',
      [shiftId],
    );
    if (onCall < 2) throw new ConflictError('someone must stay on call');
    await tx.query(
      'update on_call set on_duty = false where shift_id = $1 and doctor_id = $2',
      [shiftId, doctorId],
    );
  });
```

Two calls for the last two doctors on call can both pass the count check. Under serializable, Postgres aborts one of them with 40001, and the loop reruns it against the new data, where the check fails. At read committed or repeatable read both would commit.

## When to use

- Two requests can change the same row or the same rule at once
- Money, stock, seats or quotas, where a lost update is a real loss
- Reports that must read several tables at one point in time

## When not to use

- Raising every transaction to serializable by default without retries in place
- Single-statement atomic updates, which are already safe at read committed
- Coordinating across services: isolation stops at one database

## Benefits

- A named, testable promise about which races cannot happen
- Snapshot reads give consistent reports without blocking writers
- Serializable lets you write the check in plain code and trust it

## Costs

- Stronger levels abort more transactions under contention
- Every caller must handle a retryable error
- Lock-based levels add waiting and deadlocks

## Pitfalls

- Assuming repeatable read means the same thing in Postgres and MySQL. InnoDB still loses a read-then-write update.
- Retrying only the failed statement instead of the whole transaction, so the retry uses values read from the old snapshot.
- Sending an email inside a retried transaction, so a conflict sends it twice.
- Using for update to stop phantoms. It locks rows that exist, not the row that is about to be inserted.

## Related patterns

- [Optimistic Locking](https://layra4.dev/architectures/infrastructure/optimistic-locking) — a version column that turns a lost update into a conflict
- [Pessimistic Locking](https://layra4.dev/architectures/infrastructure/pessimistic-locking) — select … for update, and when blocking beats retrying
- [Consistency Models](https://layra4.dev/architectures/key-design-principles/consistency-models) — the same questions, asked across replicas instead of transactions
- [Retry with Backoff](https://layra4.dev/architectures/resilience/retry-with-backoff) — the loop every serializable caller needs
- [Unit of Work](https://layra4.dev/architectures/infrastructure/unit-of-work) — where an application usually draws the transaction boundary

## Further reading

- *A Critique of ANSI SQL Isolation Levels* — Hal Berenson et al. (SIGMOD 1995) — Why the standard's definitions leak, and the first definition of snapshot isolation.
- *Designing Data-Intensive Applications, ch. 7* — Martin Kleppmann (2017) — Transactions: every anomaly here, with the doctors-on-call example.
- *Serializable Isolation for Snapshot Databases* — Michael Cahill, Uwe Röhm, Alan Fekete (SIGMOD 2008) — The SSI algorithm behind Postgres serializable.
