Core Concept

Transaction Isolation and MVCC

Isolation decides which concurrency anomalies a transaction can observe, and MVCC lets readers and writers proceed without blocking each other. Pick the narrowest tool that protects the invariant, from an atomic UPDATE to row locks, version checks, or SERIALIZABLE with retries.


1. What It Is

Isolation is the I in ACID. It promises that each transaction behaves as if it ran alone even though thousands run at once. Real databases sell weaker, cheaper versions of that promise, so the level you choose decides which concurrency bugs your code must handle itself.

What:

The rules for what one transaction may observe of other transactions that run at the same time. The strongest form, serializability, means the outcome equals some one-at-a-time ordering of the transactions. MVCC (multi-version concurrency control) is the common implementation, keeping several versions of each row so readers and writers do not block each other.

Primary purpose:

Protect invariants such as stock never going negative, a seat selling once, and debits equalling credits, while many transactions run in parallel and without forcing all work into a single queue.

Usually used for:

Inventory decrements, seat and room booking, balance transfers, counters, and any read-modify-write on rows that several requests can touch.

2. Core Mental Model

Think of isolation levels as a menu of anomalies you agree to tolerate. Every protection against the rest is one of three mechanisms, and good answers name the invariant first and then pick the cheapest mechanism that defends it.

πŸ“Έ Snapshot (MVCC)

Each read sees a consistent set of committed row versions, so readers never wait for writers. This gives you a stable view but does not stop two writers from acting on stale data.

πŸ”’ Lock first (pessimistic)

Claim the row with SELECT ... FOR UPDATE before deciding. Competing writers queue behind you, so the decision is made on data nobody else can change.

βœ… Check at write time (optimistic)

Work without blocking, then write only if nothing changed, using a version column or a conditional UPDATE. The loser retries or reports a conflict.

In the room

Do not say "I will use SERIALIZABLE" and stop. Name the invariant (stock never below zero), name the anomaly that breaks it (two transactions read stock 1 and both sell it), then pick the narrowest fix, which is usually one atomic conditional UPDATE or a row lock. State which database you assume, because defaults differ.

3. Why It Matters in HLD

Many correctness bugs in booking, payment, and inventory designs are concurrency bugs on a few shared rows, so isolation is where those designs are won or lost. Three lenses:

Needed When:

Two requests can touch the same row, code reads a value before writing a new one, or a rule spans several rows such as a balance, a capacity, or a minimum staffing level.

Avoids:

Overselling, double booking, lost updates, unbalanced ledgers, and reports that mix data from before and after a transfer.

Optimizes For:

Correctness per unit of contention, reads that never block on writes, and the lowest isolation level and shortest lock time that still protects the invariant.

4. Architecture & Data Flow

Walk a read and a write through MVCC as interview steps. Step 1 (begin): the transaction takes a snapshot that records which other transactions had committed. READ COMMITTED takes a fresh snapshot per statement, while REPEATABLE READ and SERIALIZABLE take one at the first query and keep it. Step 2 (read): return the newest row version visible to that snapshot, taking no lock that blocks writers. Step 3 (write): never overwrite what an older snapshot can still see. Create a new version and mark the old one as ended by this transaction (PostgreSQL keeps both in the table, while InnoDB updates the row and keeps the old image in undo), and a second writer on the same row waits until the first commits or aborts. Step 4 (commit): the new version becomes visible to snapshots taken afterwards, while older snapshots keep seeing the old one. Step 5 (cleanup): once no live snapshot can see an old version, vacuum or purge reclaims it.

Loading...

A version is visible to a snapshot when the transaction that created it committed before the snapshot (or is the reader itself) and no transaction that committed before the snapshot has ended it. PostgreSQL stores this as xmin and xmax on each tuple and keeps old versions in the table, which is why VACUUM exists. InnoDB keeps only the newest version in the table and rebuilds older ones from undo records, and a purge process discards them when no read view needs them.

In the room

Say that readers do not block writers and writers do not block readers, but writers still block writers on the same row. That last clause is what separates a prepared answer from a slogan, and the interviewer will often ask what happens to the second writer next.

5. Key Characteristics

Five anomalies cover almost every interview question. Each timeline uses two concurrent transactions, T1 and T2, against the same database.

Dirty read

Allowed only at READ UNCOMMITTED. PostgreSQL never allows it and treats READ UNCOMMITTED as READ COMMITTED.

T1: BEGIN;
T1: UPDATE accounts SET balance = 0 WHERE id = 7;
T2: SELECT balance FROM accounts WHERE id = 7;     -- returns 0, T1 has not committed
T1: ROLLBACK;                                      -- balance is 500 again
T2: acted on a balance of 0 that never officially existed
Non-repeatable read

Allowed at READ UNCOMMITTED and READ COMMITTED, because each statement sees the newest committed data.

T1: BEGIN;
T1: SELECT balance FROM accounts WHERE id = 7;     -- 500
T2: UPDATE accounts SET balance = 300 WHERE id = 7;  COMMIT;
T1: SELECT balance FROM accounts WHERE id = 7;     -- 300, same row, same transaction, new answer
Phantom read

The standard allows it up to REPEATABLE READ. PostgreSQL REPEATABLE READ prevents it. A row lock cannot protect a row that does not exist yet.

T1: BEGIN;
T1: SELECT count(*) FROM bookings WHERE room_id = 12 AND night = '2026-12-24';   -- 0, looks free
T2: INSERT INTO bookings (room_id, night, guest_id) VALUES (12, '2026-12-24', 88);  COMMIT;
T1: SELECT count(*) FROM bookings WHERE room_id = 12 AND night = '2026-12-24';   -- 1, a new row matches
Lost update

Happens whenever code reads a value, computes in the application, and writes it back. Possible at READ COMMITTED. PostgreSQL REPEATABLE READ fails the second writer, InnoDB REPEATABLE READ does not.

items.stock = 10 for id 42
T1: SELECT stock FROM items WHERE id = 42;         -- 10
T2: SELECT stock FROM items WHERE id = 42;         -- 10
T1: UPDATE items SET stock = 9 WHERE id = 42;  COMMIT;     -- application computed 10 - 1
T2: UPDATE items SET stock = 9 WHERE id = 42;  COMMIT;     -- application computed 10 - 1
Final stock is 9 after two sales, and it should be 8
Write skew

Allowed at PostgreSQL REPEATABLE READ (snapshot isolation) and at InnoDB REPEATABLE READ (snapshot reads). Only SERIALIZABLE (or an explicit lock or constraint) prevents it.

Rule: at least one doctor stays on call. Alice and Bob are both on call.
T1: SELECT count(*) FROM doctors WHERE on_call;    -- 2, so Alice may leave
T2: SELECT count(*) FROM doctors WHERE on_call;    -- 2, so Bob may leave
T1: UPDATE doctors SET on_call = false WHERE name = 'Alice';  COMMIT;
T2: UPDATE doctors SET on_call = false WHERE name = 'Bob';    COMMIT;
Zero doctors on call. The writes touched different rows, so no write conflict was ever seen

Isolation levels and the standard anomalies

The SQL standard defines the four levels by the first three anomalies only:

Isolation levelDirty readNon-repeatable readPhantom read
READ UNCOMMITTEDPossiblePossiblePossible
READ COMMITTEDPreventedPossiblePossible
REPEATABLE READPreventedPreventedPossible by the standard, engine dependent in practice
SERIALIZABLEPreventedPreventedPrevented

What real engines do

Lost update and write skew are not in the standard table, so reason about them per engine:

Engine and levelPhantom readLost update (read, compute, write back)Write skew
PostgreSQL READ COMMITTED (default)PossiblePossiblePossible
PostgreSQL REPEATABLE READ (snapshot isolation)PreventedPrevented, the second writer gets a serialization failurePossible
PostgreSQL SERIALIZABLE (SSI)PreventedPreventedPrevented, but a transaction may abort and must be retried
MySQL InnoDB REPEATABLE READ (default)Prevented for plain reads by the snapshot, and for locking reads by next-key locksPossible with plain reads, so use a locking read or an atomic UPDATEPossible
MySQL InnoDB SERIALIZABLEPrevented, plain reads inside a transaction take shared locksPreventedPrevented, with more blocking and deadlocks
  • PostgreSQL REPEATABLE READ is snapshot isolation. It prevents phantoms, which is stricter than the standard requires, but it still allows write skew. It also fails the second writer of a row that changed since its snapshot, so it needs a retry loop too.
  • PostgreSQL SERIALIZABLE uses serializable snapshot isolation (SSI). Transactions run on snapshots without blocking, the database tracks read and write dependencies, and it aborts one transaction with SQLSTATE 40001 (serialization failure) when it sees a pattern that no serial order could produce. The caller must retry the whole transaction, and some aborts are false alarms because detection is conservative.
  • MySQL InnoDB REPEATABLE READ uses next-key locks. Plain SELECTs read from a snapshot, while locking reads and writes that scan a range take a record lock plus a gap lock that blocks inserts into the scanned range (an equality lookup on a unique index locks only the record). An UPDATE sees the newest committed rows rather than the snapshot, so mixing plain reads and writes can still surprise you.
  • Defaults differ. PostgreSQL defaults to READ COMMITTED and MySQL InnoDB to REPEATABLE READ, so the same code can behave differently on each. Name the engine you assume.

6. Strategic Tradeoffs

Every option trades protection against throughput in a different way, so we state both sides before choosing:

ApproachBenefitCost
Raise the isolation levelFewer anomalies to reason about, and the database enforces the rule for youAborts that callers must retry, tracking overhead, and lower throughput under contention
Atomic conditional UPDATEOne statement with no lock held across round trips, correct at READ COMMITTEDOnly expresses a rule on one row or a simple predicate, not a multi step decision
Pessimistic lock (SELECT ... FOR UPDATE)Correct by construction with no retry loop, ideal when conflicts are likelyWaiters queue on hot rows, hold connections, and can deadlock
Optimistic check (version column)No lock held while a user or service thinks, and it scales when conflicts are rareLosers must retry or return 409, and heavy conflicts cause retry storms

Contention decides between locks and version checks. Assume a transaction holds a hot row's lock for 5 ms including network round trips. That row completes at most 1 / 0.005 s = 200 transactions per second, however many app servers you add. A flash sale with 500,000 buyers on one SKU then needs 500,000 / 200 = 2,500 s, about 42 minutes, to drain, so the hot counter has to leave the row.

Optimistic checks avoid the queue but not the conflict. If 100 writers read version 7 together and retry in lockstep, one wins per round, so the attempts total 100 + 99 + ... + 1 = 100 x 101 / 2 = 5,050 against 100 with a lock, about 50 attempts per writer. Jittered backoff spreads them out, but high conflict is still where version checks collapse. The rule is simple: rare conflicts favor version checks, frequent conflicts on a few rows favor an atomic conditional UPDATE or a lock, and beyond what one row can serialize you move the counter to Redis or shard it.

7. Failure / Bottleneck Awareness

Lost updates, unretried aborts, bloat, and deadlocks are the failures interviewers probe, so we volunteer the mitigations:

πŸ•³οΈ Lost Update from Read, Compute, Write Back

Problem: The application selects stock, subtracts in code, and writes the result back. Two requests both read 10 and both write 9, so a sale vanishes. It passes single-user tests and fails under concurrency, and READ COMMITTED does not stop it.

Mitigation: Push the arithmetic into the statement (SET stock = stock - 1 WHERE stock >= 1), lock the row with FOR UPDATE before reading, or write with a version check. Add CHECK (stock >= 0) so a bug fails loudly instead of overselling.

πŸ” Serialization Failures Nobody Retries

Problem: PostgreSQL REPEATABLE READ and SERIALIZABLE abort correct transactions that conflict (SQLSTATE 40001), and deadlock victims get 40P01. A handler with no retry loop turns this into random 500 errors under load.

Mitigation: Retry the whole transaction, including its reads, with jittered backoff and a small attempt cap. Keep transactions short to shrink the conflict window, and make the operation idempotent so a retried request cannot apply twice.

🧹 Long Transactions Bloat Storage

Problem: An open snapshot must keep every old row version it could still see, including each version replaced or deleted since it began, so vacuum or purge cannot reclaim them. A report running for hours, or a connection left idle in transaction, makes tables and indexes bloat, scans slower, and lets the InnoDB undo history grow.

Mitigation: Set statement and idle-in-transaction timeouts, never hold a transaction open across a call to a payment provider or any slow service, run long reports on a replica, and alert on the age of the oldest open transaction.

πŸ’€ Deadlocks

Problem: T1 holds a lock and wants the one T2 holds, while T2 wants T1's. Neither can proceed, so the database detects the cycle and aborts one victim. Transfers between two accounts and multi seat holds are the usual cause.

Mitigation: Lock rows in one global order such as ascending id, keep transactions short, and treat the deadlock error as retryable.

Loading...

8. Common HLD Usage

The same few moves appear across booking, payment, and inventory designs. Read the rows as a scale of contention, from a conditional UPDATE through row locks to Redis admission control:

ProblemPatternRationale
Payment GatewaySELECT ... FOR UPDATE on the idempotency key row, plus a version column on the payment state machineA retry and the original request serialize on the key row, so only one runs the charge. The version column guards status transitions, balance mutations use SERIALIZABLE, and dashboards stay at READ COMMITTED.
Banking Ledger SystemFOR UPDATE on the account row plus CHECK (balance >= 0)Two concurrent withdrawals queue on the account row, and the second sees the reduced balance. Hot merchant accounts spread credits over bucket sub-accounts that each commit durably and are swept into the main row every few seconds, which cuts row contention without holding money outside the database.
Hotel Booking SystemFOR UPDATE on the pre created room night rows for the whole stay, at READ COMMITTEDBooking only updates existing rows, so phantom inserts cannot occur and SERIALIZABLE is not needed. Every night commits together or rolls back together.
Ticketing SystemORDER BY seat_id FOR UPDATE, a version column, SKIP LOCKED in the hold expiry worker, Redis holds in frontA fixed order avoids deadlocks on multi seat holds and SKIP LOCKED lets cleanup workers take different expired holds. Pure row locks exhaust connection pools in an on-sale burst, so Redis absorbs the first wave.
Relational Database (PostgreSQL)MVCC tuple versions with xmin and xmax, snapshot visibility, VACUUMReaders use a snapshot and take no row locks that conflict with writers. VACUUM reclaims dead versions only after no active transaction can see them, so long transactions hold back cleanup.
Inventory Management SystemFOR UPDATE plus CHECK constraints for normal stock, a Redis counter for hot SKUsRow locks are safe, but a flash sale of 1,000 units with 500K buyers piles waiters on one row. The hot path decrements in Redis and PostgreSQL is reconciled afterwards.
Flash Sale SystemOne atomic Redis Lua script instead of database locksA script runs without interleaving, so the stock check, decrement and per user limit are one step. It marks where database isolation stops being the answer, and orders reach PostgreSQL asynchronously.
Ecommerce PlatformFOR UPDATE, an atomic conditional decrement, or Redis, chosen by contentionThe conditional decrement is the recommended default for standard stock. Multi item orders update rows in a deterministic product order to reduce deadlock risk, and flash sales move to Redis admission control.

9. Decision Signals

Choose the tool from the invariant and the contention level, not from the name of an isolation level. The four classic interview cases are the first four rows:

SituationRight toolWhy
Prevent overselling inventoryUPDATE ... SET stock = stock - 1 WHERE id = ? AND stock >= 1, check rows affected, plus CHECK (stock >= 0)The check and the decrement are one statement, so two buyers cannot both take the last unit. Multi item orders lock rows in a fixed order, and a hot SKU moves its counter to Redis.
Prevent double booking a specific seat or room nightFOR UPDATE on the existing inventory row, or a conditional UPDATE guarded by status, plus a UNIQUE constraint as the last barrierPre created rows give the lock something to hold. If rows are inserted on demand, a row lock has nothing to hold, so a UNIQUE constraint, SERIALIZABLE, a lock on a parent row, or in InnoDB a gap lock must stop the phantom insert.
Keep a ledger balancedOne transaction writing both entries, accounts locked in id order, CHECK (balance >= 0), a unique idempotency keyAtomicity keeps debit and credit together, ordered locks avoid deadlocks, and the CHECK and unique key still hold if application code has a bug.
Counter increment (views, likes, quota used)UPDATE t SET n = n + 1, one atomic statementThe database re-reads the newest committed row once the lock frees, so no explicit lock or higher level is needed. Pair it with an event id if retries can repeat the increment.
Pick any free seat or job without waitingFOR UPDATE SKIP LOCKEDEach worker skips rows another transaction holds, so workers spread across distinct rows instead of queueing on one.
Invariant over many rows (at least one on call, a total under a cap)SERIALIZABLE with a retry loop, or lock every row the decision readPlain snapshots allow write skew, so the conflict must be forced into a write conflict or detected by SSI.
Low conflict edits with long think time (profile, document, admin form)Optimistic version column, return 409 on mismatchNo lock is held while the user thinks, and conflicts are rare enough that a retry is cheap.
Long read only reportA read only REPEATABLE READ snapshot, or a replica, with a statement timeoutA stable snapshot gives a consistent report, but an old snapshot pins old row versions, so keep it bounded.
🎯 Raise the isolation level when:
  • The rule spans rows or a predicate such as a minimum on-call count or a capacity total, so write skew is possible and there is no single row to lock.
  • You can afford a retry loop and contention is moderate, so aborts stay rare.
  • A read only report needs one consistent snapshot across many queries.
⏭️ Do not rely on isolation when:
  • A single atomic statement already enforces the rule (conditional UPDATE, UNIQUE, CHECK), so a higher level only adds aborts.
  • The work spans services or databases, because isolation covers one database transaction and a saga gives it up.
  • One row cannot serialize the traffic, which means the counter belongs in Redis or in sharded rows.
  • Reads come from a lagging replica, since no isolation level fixes stale replica data.

In the room

Expect these follow-ups: what happens to the second writer, whether REPEATABLE READ stops write skew (not in PostgreSQL and not in InnoDB), what the caller does on a serialization failure (retry the whole transaction), and what changes when one SKU takes 100 times the traffic (move the counter off the row). The classic mistakes are read-modify-write in application code, assuming a higher level removes the need for retries, and holding a transaction open across a network call.

11. Deep Dive (Optional)

Four Ways to Protect One Row

These four statements cover most booking and inventory answers. SKIP LOCKED suits work queues and "any free seat" picks, but not reads that need a complete answer, because it silently skips locked rows.

SQL
-- 1. Atomic conditional UPDATE: no explicit lock, safe at READ COMMITTED
UPDATE items SET stock = stock - 1 WHERE id = 42 AND stock >= 1;
-- rows affected = 1 means reserved, 0 means sold out

-- 2. Pessimistic: lock rows in a fixed order, then decide
BEGIN;
SELECT id, stock FROM items WHERE id IN (7, 42) ORDER BY id FOR UPDATE;
-- verify every stock >= 1 in application code, then:
UPDATE items SET stock = stock - 1 WHERE id IN (7, 42);
COMMIT;

-- 3. Optimistic: compare-and-set on a version column
UPDATE seats SET status = 'held', held_by = 501, version = version + 1
WHERE id = 88 AND version = 3;
-- rows affected = 0 means the row changed since it was read, so reload and retry or return 409

-- 4. Take any free row without waiting on rows other transactions hold
SELECT id FROM seats WHERE show_id = 9 AND status = 'available'
ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;

Retry Loop for Serialization Failures and Deadlocks

Wrap the entire transaction, reads included, because a retry must recompute from fresh data. The sleep ceilings below are 40, 80, 160, and 320 ms for attempts 1 to 4. The two codes are PostgreSQL SQLSTATEs, and MySQL reports a deadlock as error 1213 with SQLSTATE 40001, so the same set works there.

TYPESCRIPT
const RETRYABLE = new Set(["40001", "40P01"]); // serialization failure, deadlock detected

async function withRetry<T>(work: (tx: Transaction) => Promise<T>, maxAttempts = 5): Promise<T> {
  for (let attempt = 1; ; attempt++) {
    try {
      return await db.transaction("SERIALIZABLE", work); // BEGIN ... COMMIT as one retryable unit
    } catch (err) {
      if (!RETRYABLE.has(sqlState(err)) || attempt === maxAttempts) throw err;
      await sleep(Math.random() * 20 * 2 ** attempt);    // full jitter in milliseconds
    }
  }
}

Fixing Write Skew

Write skew has four standard fixes. First, run the transaction at SERIALIZABLE and retry aborts. Second, lock every row the decision read with FOR UPDATE, such as both doctor rows or a parent row like the hotel, which turns the hidden conflict into a visible write conflict. Third, materialize the conflict by creating rows ahead of time, which is why booking designs pre-create room night and seat rows, since there is then something to lock. Fourth, add a constraint the database enforces, such as a UNIQUE key on room and night, or in PostgreSQL an exclusion constraint for overlapping ranges. The constraint is the strongest option because it does not depend on every code path remembering to lock.

Garbage Collection in Practice

Routine VACUUM in PostgreSQL makes dead tuple space reusable inside the table but normally does not shrink the file, while VACUUM FULL rewrites the table and returns space at the cost of heavy locking. Autovacuum runs in the background, and it can only remove versions that no open snapshot could still see. Watch the age of the oldest open transaction and the dead tuple ratio, and treat a stuck old transaction as a production incident. See Relational Database (PostgreSQL) for tuple headers, visibility flags, and transaction ID wraparound.

πŸ’¬Review

Help Us Improve

How helpful was this walkthrough?

Click a star to rate. We actively use this feedback to refine and update our system design content.

Placeholder
Optional but highly appreciated!

Discussion

Share your thoughts, ask questions, or help others.

Loading comments...