Skip to content

Isolation Levels: Definitions, Anomalies & Real-World Use Cases ​

"This paper shows that these phenomena and the ANSI SQL definitions fail to characterize several popular isolation levels, including the standard locking implementations of the levels." — Berenson, Bernstein, Gray, Melton, O'Neil & O'Neil, A Critique of ANSI SQL Isolation Levels, SIGMOD 1995

Summary: Isolation levels are the dial between correctness and throughput: each level forbids a set of anomalies, and each engine implements the names differently. Focus: The anomalies (dirty read to write skew), the levels, what PostgreSQL, InnoDB, SQL Server and Oracle really do, and the code that fixes the classic bugs. Learning goal: Pick a level per operation, predict which anomaly can still happen, and handle the retry the database may demand.

This page is the complete reference for transaction isolation: every anomaly a practitioner meets (dirty write, dirty read, non-repeatable read, phantom read, lost update, cursor lost update, read skew, write skew, the read-only transaction anomaly), every level (Read Uncommitted, Read Committed, Repeatable Read, Snapshot Isolation, Serializable, Strict Serializable), what PostgreSQL, MySQL InnoDB, SQL Server, Oracle, SQLite, MongoDB, CockroachDB, Spanner and Redis really do under each name, the error codes you will catch, and the code that fixes each classic bug. It deliberately does not re-teach three neighbours: how row versions, xmin/xmax and VACUUM work is in MVCC, VACUUM & Bloat; lock modes and lock queues are in Locks & Concurrency; and the four ACID properties with BEGIN/COMMIT/ROLLBACK are in ACID & Transactions. Deadlock handling has its own page, Deadlocks, and version columns are covered in depth in Optimistic vs Pessimistic Locking.

Page map ​

If you are looking forGo to
A table you can memorise in one minuteEverything in one minute
Why levels exist at all, and the trade-offWhy isolation levels exist
ANSI SQL-92, Berenson 1995, serial vs serializable, linearizabilityWhere the vocabulary comes from
One anomaly with a two-session timelineThe anomalies, one by one
What a level promises and its surprises (PostgreSQL re-check, InnoDB phantoms)The levels, one by one
Level × anomaly × engine matricesPer-engine behaviour
PostgreSQL, InnoDB, SQL Server, Oracle, SQLite, MongoDB, CockroachDB, Spanner, RedisWhat each database really does
2PL, gap locks, snapshots, SSI, bloat, knobs, error codesMechanics
SQL + Go + Laravel for lost update, write skew, check-then-insert, double booking, reports, job queuesSolving the classic problems
Retry wrapper in Go and LaravelRetries and failure handling
Which level for which workloadChoosing a level
Replicas, caches, sagas, distributed SQLIn architecture
Reproduce everything in two terminalsLab
Wrong beliefs, a cheat sheet, every term definedMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The anomalies. Every row is unpacked in the anomalies section.

Anomaly (paper code)In plain wordsTiny exampleWhat stops it
Dirty write (P0)You overwrite someone's uncommitted writeT1 sets x=1, T2 sets x=2, T1 rolls back: what is x?Every real engine, at every level (long write locks)
Dirty read (P1)You read someone's uncommitted writeBalance shows a deposit that is then rolled backRead Committed and above
Non-repeatable read / fuzzy read (P2)Same row, read twice, two valuesPrice 10, then 12, in one checkoutRepeatable Read, Snapshot Isolation
Phantom read (P3)Same WHERE, run twice, new rows appearCOUNT(*) of bookings changes mid-transactionSnapshot (for plain reads), InnoDB next-key locks, Serializable
Lost update (P4)Two read-modify-writes, one silently vanishesTwo orders both see stock 1, both write 0Atomic update, FOR UPDATE, version column, PostgreSQL Repeatable Read
Cursor lost update (P4C)Lost update through a cursor's current rowFetch row, other session updates it, you update itCursor Stability
Read skew (A5A)You read two related things from two different momentsTransfer between accounts seen half-doneSnapshot Isolation, Repeatable Read
Write skew (A5B)Two transactions check the same rule, write different rows, rule breaksTwo doctors both go off callSerializable, or lock/materialise the rule
Read-only transaction anomalyA pure reader sees a state no serial order could produceReport shows a closed batch, then a receipt lands in itPostgreSQL Serializable (SSI), DEFERRABLE

The levels.

LevelPromiseTiny example of what is still allowedTypical engines and defaults
Read UncommittedNo dirty writesDirty readsInnoDB (real), PostgreSQL (silently Read Committed)
Read CommittedOnly committed data, per statementNon-repeatable read, phantom, lost update, write skewDefault in PostgreSQL, SQL Server, Oracle; CockroachDB option
Repeatable ReadRows you read do not changeDepends on engine: write skew (PostgreSQL), lost update (InnoDB)Default in MySQL InnoDB
Snapshot IsolationWhole transaction reads one snapshot; first-committer-wins on writesWrite skewSQL Server SNAPSHOT; PostgreSQL Repeatable Read; SQLite WAL readers
SerializableResult equals some serial orderNothing (but you get aborts or waits)PostgreSQL SSI, InnoDB 2PL, CockroachDB default, Oracle "serializable" is really SI
Strict SerializableSerializable + respects real timeNothing, including stale reads across clientsSpanner (external consistency), single-node serializable engines

The three things to do.

SituationDo this
Changing one counter or balanceOne UPDATE ... SET x = x - 1 WHERE ... AND x >= 1 (atomic update) at Read Committed
Enforcing a rule across rowsLock what the rule reads (FOR UPDATE), materialise it into a row or constraint, or run Serializable with retry
Any level above Read CommittedRetry the whole transaction on 40001/40P01 (PostgreSQL) or 1213/1205 (MySQL), with backoff and jitter

Why isolation levels exist ​

A database runs many transactions at once because running them one after another wastes the machine: while one waits for disk or the network, others could work. Isolation is the “I” in ACID: the promise that concurrent transactions do not see each other's half-done work. Perfect isolation (every outcome equals some one-at-a-time order) costs waiting or aborts. So the SQL standard defined weaker levels that let you trade correctness for throughput, and every engine picked a default somewhere in the middle. The Critique paper puts the trade in one line: isolation levels let "application designers to trade throughput for correctness".

Weaker level (Read Committed)Stronger level (Serializable)
Readers never wait for writers (MVCC engines)Readers may wait (2PL) or be aborted later (SSI)
Almost no abortsSerialization failures you must retry
You reason about every interleaving yourselfYou reason about each transaction alone
Bugs show up as wrong data, silentlyBugs show up as errors, loudly
Cheap long readsLong transactions raise abort rate or block others

The analogy we reuse on this page: a shared office calendar. Assistants read the calendar, decide, and write entries. Read Committed is reading the calendar on the wall: you see whatever is pinned right now, and it can change between two glances. Snapshot Isolation is each assistant getting a photocopy at 9:00: what you read is stable, but two people working from photocopies can both book the director into overlapping meetings in different rooms. Serializable is a rule that only one assistant may hold the calendar at a time (2PL) or a supervisor who checks every evening that the day's changes could have been made one person at a time, and tears up one booking if not (SSI).

Three common misunderstandings, up front ​

  1. “I am in a transaction, so nobody can change what I read.” A plain SELECT takes no lock in PostgreSQL, InnoDB, Oracle or SQL Server with RCSI. Atomicity says your writes commit together; it says nothing about others' writes between your statements.
  2. “Same level name, same behaviour.” PostgreSQL Repeatable Read is Snapshot Isolation and aborts lost updates; InnoDB Repeatable Read lets lost updates through and uses gap locks for writes; Oracle's SERIALIZABLE permits write skew. Always name the product with the level.
  3. “Serializable means slow and blocking.” In PostgreSQL it is SSI: it adds no blocking on top of Repeatable Read, except that a SERIALIZABLE READ ONLY DEFERRABLE transaction may wait at its start. The cost is aborts, which a retry wrapper absorbs.

Where the vocabulary comes from ​

ANSI SQL-92 named four levels and defined three of them by what must not happen. The Critique describes the approach: "These levels are defined with the classical serializability definition, plus three prohibited action subsequences, called phenomena: Dirty Read, Non-repeatable Read, and Phantom." In 1995 Berenson, Bernstein, Gray, Melton and the two O'Neils showed that the English wording is ambiguous, that it does not even forbid dirty writes, and that it cannot describe multi-version engines. They introduced the codes this page uses: P0 dirty write, P1 dirty read, P2 fuzzy read, P3 phantom, P4 lost update, P4C cursor lost update, A5A read skew, A5B write skew, and named Snapshot Isolation and Cursor Stability as levels the standard had no words for. Their key result: Snapshot Isolation "avoids the ANSI SQL phenomena, but is not serializable."

Two later pieces of research matter in practice. Fekete et al. showed that even a read-only transaction can take part in a Snapshot Isolation anomaly (the Ports & Grittner paper calls it "a surprising result discovered by Fekete et al."), and Cahill, Röhm and Fekete designed Serializable Snapshot Isolation, which Ports and Grittner built into PostgreSQL 9.1. The PostgreSQL manual points to [berenson95] for the Repeatable Read / Snapshot Isolation distinction and to [ports12] for SSI.

Serial vs serializable Important ​

A serial execution runs transactions literally one after another. A serializable execution runs them concurrently but guarantees the committed result equals some serial order; the database picks the order, not the clock. PostgreSQL's manual states it as emulating "serial transaction execution for all committed transactions; as if transactions had been executed one after another". SQLite and Redis are the rare systems that are serializable by being (mostly) serial: SQLite "implements serializable transactions by actually serializing the writes", Redis executes a MULTI/EXEC block as one step on its single command thread.

Strict serializable, and linearizability vs isolation Good to know ​

Serializable allows the chosen order to disagree with real time: transaction B may start after A committed and still be ordered before A, so B does not see A's write. On one node this rarely happens because the snapshot is taken at start. Across replicas or regions it is the norm. Strict Serializable adds the real-time rule. Jepsen's definition:

"Strict serializability implies serializability and linearizability." — Jepsen, Strong Serializability consistency model

Linearizability vs isolation: linearizability is a property of single operations on single objects (a register, a key) and is about recency: once a write is acknowledged, every later read sees it. Isolation is about multi-object transactions and interleaving. A system can be linearizable per key but have no transactions (etcd key reads, a Redis primary), or serializable but not linearizable (a read replica serving an old but consistent snapshot). Spanner offers both and calls the combination external consistency; CockroachDB is Serializable by default and documents its real-time guarantees separately.

The anomalies, one by one ​

Each block follows the same order: plain words, the usual wrong belief, the precise definition (with the Critique's history notation where it exists: r1[x] is a read of x by T1, w2[y] a write by T2, c1/a1 commit/abort), a two-session timeline, real scenarios, which engine and level stops it, and a one-line fix that links to the full code in Solving the classic problems.

Dirty write (P0) Good to know ​

In plain words: you overwrite a value that another transaction wrote but has not committed yet. If either of you rolls back, nobody can say what the value should be.

Common misunderstanding: “Read Uncommitted allows everything, including dirty writes.” No: no SQL engine allows dirty writes at any level, because rollback would be impossible to implement. The ANSI text forgot to forbid it; the Critique added P0 to fix that.

Definition: P0: w1[x]...w2[x]...((c1 or a1) and (c2 or a2) in any order). Every engine holds write locks (or the equivalent row-version lock) until commit, so T2's write waits.

text
     T1                                   T2
1    BEGIN;                               BEGIN;
2    UPDATE accounts SET owner='Ann'
       WHERE id=1;   -- row now locked
3                                         UPDATE accounts SET owner='Bob'
                                            WHERE id=1;   -- WAITS for T1
4    ROLLBACK;                            -- T2 now proceeds on the committed row
5                                         COMMIT;  -- owner='Bob', well-defined

Real scenario: this is why a long-running UPDATE in a migration makes every request that touches the same rows hang: the engine is preventing dirty writes by making them wait. It is also why “kill the stuck transaction” unblocks a whole queue.

EngineDirty write possible?
PostgreSQL, MySQL InnoDB, SQL Server, Oracle, SQLite, CockroachDBNo, at every level: second writer waits (or is aborted)
MongoDB multi-document transactionNo: the second writer gets a WriteConflict

Fix: nothing to fix; know that the waiting you see is this protection, and keep write transactions short.

Dirty read (P1) Important ​

In plain words: you read data that another transaction wrote but has not committed, and it may never exist.

Common misunderstanding: “NOLOCK / Read Uncommitted is a harmless speed-up for reports.” On SQL Server NOLOCK has the same effect as Read Uncommitted: reports can show rows that were later rolled back. MVCC engines give you non-blocking reads without dirty reads, so the trade is never worth it there.

Definition (P1): "Transaction T1 modifies a data item. Another transaction T2 then reads that data item before T1 performs a COMMIT or ROLLBACK. If T1 then performs a ROLLBACK, T2 has read a data item that was never committed and so never really existed."

text
     T1 (payment)                         T2 (dashboard, READ UNCOMMITTED)
1    BEGIN;
2    UPDATE wallets SET balance = balance + 500 WHERE id = 7;   -- 100 -> 600
3                                         SELECT balance FROM wallets WHERE id = 7;  -- 600 (dirty)
4                                         -- sends "you can now withdraw 600" push notification
5    ROLLBACK;                            -- card authorisation failed; balance is 100 again

Real scenarios: a dashboard counts orders that were rolled back; a fraud check approves a withdrawal against a deposit that never committed; an ETL job copies uncommitted rows into the warehouse.

Engine and levelDirty read?
PostgreSQL, any level (Read Uncommitted is mapped to Read Committed)Never
MySQL InnoDB READ UNCOMMITTEDYes, real dirty reads
SQL Server READ UNCOMMITTED or WITH (NOLOCK)Yes
Oracle, CockroachDB, SpannerNo such level; never
SQLite with shared cache and PRAGMA read_uncommittedYes, only in that configuration

Fix: use Read Committed or higher; on SQL Server prefer RCSI to NOLOCK for non-blocking reads.

Non-repeatable read (fuzzy read, P2) Must-know ​

In plain words: you read the same row twice inside one transaction and get two different committed values.

Common misunderstanding: “Read Committed means my transaction sees one consistent state.” It means each statement sees only committed data; consecutive statements can see different commits.

Definition (P2): "Transaction T1 reads a data item. Another transaction T2 then modifies or deletes that data item and commits. If T1 then attempts to reread the data item, it receives a modified value or discovers that the data item has been deleted."

text
     T1 (checkout, READ COMMITTED)        T2 (admin)
1    BEGIN;
2    SELECT price FROM products WHERE id=42;   -- 10.00, shown on the page
3                                         UPDATE products SET price = 12.00 WHERE id=42;
4                                         COMMIT;
5    SELECT price FROM products WHERE id=42;   -- 12.00, used for the charge
6    INSERT INTO order_lines ... price 12.00;  -- customer saw 10.00
7    COMMIT;

Real scenarios: price or tax changes between display and charge; a permission is revoked between the check and the action; an invoice header and its lines computed from different moments.

Engine and levelNon-repeatable read?
PostgreSQL Read Committed, InnoDB READ COMMITTED, SQL Server RC/RCSI, Oracle Read Committed, CockroachDB Read CommittedYes
PostgreSQL Repeatable Read, InnoDB REPEATABLE READ (plain reads), SQL Server REPEATABLE READ/SNAPSHOT, Oracle SERIALIZABLENo

Fix: read the value once and carry it (or a version) through; use Repeatable Read for multi-statement reads; or lock the row with FOR SHARE/FOR UPDATE if you will act on it.

Phantom read (P3) Must-know ​

In plain words: you run the same WHERE query twice and rows have appeared (or disappeared) because someone inserted or deleted rows that match it.

Common misunderstanding: “Locking the rows I read protects my query.” Row locks cover rows that exist. A phantom is a row that did not exist when you looked; only a predicate lock, a gap/next-key lock, or a snapshot stops it.

Definition (P3): T1 reads the set of rows satisfying a search condition; T2 inserts rows that satisfy that condition and commits; T1 repeats the read and gets a different set. The Critique's broad form P3: r1[P]...w2[y in P]...(c1 or a1) forbids even the first interleaving, not just the re-read.

text
     T1 (booking check, READ COMMITTED)   T2 (another booking)
1    BEGIN;
2    SELECT count(*) FROM bookings
      WHERE room=5 AND day='2026-12-01';  -- 0
3                                         INSERT INTO bookings(room, day) VALUES (5, '2026-12-01');
4                                         COMMIT;
5    SELECT count(*) FROM bookings
      WHERE room=5 AND day='2026-12-01';  -- 1   <- phantom

Real scenarios: a report's total and its detail list disagree; a capacity check (seats, slots, quota) counts rows, then inserts; a pagination query sees a row twice.

Engine and levelPhantom on re-read?
PostgreSQL Read CommittedYes
PostgreSQL Repeatable ReadNo (snapshot); the manual marks it "Allowed, but not in PG"
InnoDB REPEATABLE READ, plain SELECTNo (snapshot of the first read)
InnoDB REPEATABLE READ, locking reads / UPDATE / DELETEPrevented by next-key locks, but DML sees the latest committed rows (see InnoDB's phantom exception)
InnoDB READ COMMITTEDYes: gap locking is off
SQL Server REPEATABLE READYes (only read rows are locked); SERIALIZABLE uses key-range locks

Fix: a snapshot level for consistent re-reads; for check-then-insert, a unique or exclusion constraint, or Serializable. See check-then-insert.

Lost update (P4) and cursor lost update (P4C) Must-know ​

In plain words: two people read the same number, each does their own calculation and writes the result; the second write lands on top of the first and the first person's work is as if it never happened. No error is raised.

Common misunderstanding: “I am inside a transaction, so nobody can change the row between my SELECT and my UPDATE.” They can; a plain SELECT takes no lock, and the transaction only makes your writes atomic.

Definition (P4): "The lost update anomaly occurs when transaction T1 reads a data item and then T2 updates the data item (possibly based on a previous read), then T1 (based on its earlier read value) updates the data item and commits." History: r1[x]...w2[x]...w1[x]...c1. Cursor lost update (P4C) is the same through a cursor: rc1[x]...w2[x]...w1[x]...c1, where rc is a read via FETCH. Cursor Stability prevents P4C by holding a lock on the cursor's current row, but not P4 in general.

text
     T1 (order #1)                               T2 (order #2)   -- PostgreSQL READ COMMITTED, or InnoDB REPEATABLE READ
1    BEGIN;                                      BEGIN;
2    SELECT stock FROM products WHERE id = 42;   -- 1
3                                                SELECT stock FROM products WHERE id = 42;  -- 1
4    UPDATE products SET stock = 0 WHERE id = 42;
5    COMMIT;
6                                                UPDATE products SET stock = 0 WHERE id = 42;  -- waits for T1, then overwrites
7                                                COMMIT;
     -- two orders shipped, one item existed

The same timeline under PostgreSQL Repeatable Read stops at step 6 with ERROR: could not serialize access due to concurrent update (SQLSTATE 40001): first-updater-wins. Under InnoDB REPEATABLE READ step 6 succeeds, because InnoDB DML reads the latest committed row, not the snapshot.

Real scenarios: overselling in a flash sale; a like counter that shows fewer likes than happened; a wallet where two concurrent withdrawals of 100 reduce the balance once; two admins editing the same CMS page; a JSON settings column where two requests each add a key and one key disappears.

Engine and levelLost update?
PostgreSQL Read CommittedYes
PostgreSQL Repeatable Read / SerializableNo: 40001 for the second writer
InnoDB READ COMMITTED and REPEATABLE READYes (no write-conflict check)
InnoDB SERIALIZABLENo: the plain SELECT becomes FOR SHARE, both hold S locks, upgrade deadlocks, one gets 1213
SQL Server READ COMMITTED / RCSIYes
SQL Server REPEATABLE READNo: S locks held, second writer deadlocks
SQL Server SNAPSHOTNo: Msg 3960 update conflict
Oracle Read Committed / SERIALIZABLEYes / No (ORA-08177)

Fix: in order of preference: an atomic update, SELECT ... FOR UPDATE, a version column (optimistic), or a higher level plus retry. Code in lost update solutions.

Read skew (A5A) Important ​

In plain words: you read two related things, but from two different moments, so together they describe a state that never existed.

Common misunderstanding: “Each value I read was committed, so what I see is correct.” Each is correct; the combination is not.

Definition: "Suppose transaction T1 reads x, and then a second transaction T2 updates x and y to new values and commits. If now T1 reads y, it may see an inconsistent state". History A5A: r1[x]...w2[x]...w2[y]...c2...r1[y]...(c1 or a1). A fuzzy read is the special case x = y.

text
     T1 (customer total, READ COMMITTED)   T2 (transfer 100 from A to B)
1    BEGIN;
2    SELECT balance FROM accounts WHERE id='A';   -- 500
3                                          BEGIN;
4                                          UPDATE accounts SET balance = balance - 100 WHERE id='A';
5                                          UPDATE accounts SET balance = balance + 100 WHERE id='B';
6                                          COMMIT;
7    SELECT balance FROM accounts WHERE id='B';   -- 600
8    -- reports 1100; the real total was always 1000

Real scenarios: backups made with many statements (a pg_dump without a snapshot would be this); a foreign-key-like check that reads the parent, then the child, across a concurrent move; a dashboard whose total does not match its breakdown.

Engine and levelRead skew?
Any Read Committed (PostgreSQL, InnoDB, SQL Server, Oracle, CockroachDB)Yes
PostgreSQL Repeatable Read, InnoDB REPEATABLE READ plain reads, SQL Server SNAPSHOT, Oracle SERIALIZABLE/READ ONLYNo: one snapshot

Fix: read in one statement (a join or SUM) or use a snapshot level, ideally READ ONLY. See consistent reports.

Write skew (A5B) Must-know ​

In plain words: two transactions check the same rule, both see it is fine, and each writes a different row; together they break the rule. Neither overwrote the other, so write-conflict detection sees nothing.

Common misunderstanding: “Snapshot Isolation / PostgreSQL Repeatable Read is basically serializable.” It prevents every ANSI phenomenon and still allows write skew; that is the Critique's central example.

Definition: A5B: r1[x]...r2[y]...w1[y]...w2[x]...(c1 and c2 occur). The Critique's example is a bank constraint where balances may go negative "as long as the sum of commonly held balances remains non-negative". The Ports & Grittner example is two doctors on call.

text
     T1 (Alice goes off call)                  T2 (Bob goes off call)   -- PostgreSQL REPEATABLE READ
1    BEGIN ISOLATION LEVEL REPEATABLE READ;    BEGIN ISOLATION LEVEL REPEATABLE READ;
2    SELECT count(*) FROM doctors
      WHERE on_call;                           -- 2
3                                              SELECT count(*) FROM doctors WHERE on_call;   -- 2
4    UPDATE doctors SET on_call = false
      WHERE name = 'Alice';
5                                              UPDATE doctors SET on_call = false WHERE name = 'Bob';
6    COMMIT;                                   COMMIT;   -- both succeed: nobody is on call

At SERIALIZABLE in PostgreSQL one of the commits (or a later statement) fails with ERROR: could not serialize access due to read/write dependencies among transactions.

Real scenarios: on-call or minimum-staffing rules; two meeting bookings in different rows that overlap the same slot; a username claimed in two tables; a customer's combined credit limit across several accounts; “at most 3 active API keys” enforced by COUNT(*); a phantom-based variant where both transactions insert (the Critique's job-tasks example where the hours "cannot have a sum of hours greater than 8").

Engine and levelWrite skew?
PostgreSQL Read Committed / Repeatable ReadYes
PostgreSQL Serializable (SSI)No: 40001
InnoDB READ COMMITTED / REPEATABLE READ (plain reads)Yes
InnoDB SERIALIZABLENo: S locks + next-key locks; one transaction deadlocks (1213)
SQL Server SNAPSHOT / RCSIYes
SQL Server SERIALIZABLENo (key-range locks)
Oracle SERIALIZABLE (Snapshot Isolation)Yes
CockroachDB SERIALIZABLE (default)No

Fix: Serializable + retry; or lock the rows the rule reads (FOR UPDATE); or materialise the conflict into one row or a constraint. See write skew solutions.

Read-only transaction anomaly Good to know ​

In plain words: under Snapshot Isolation even a transaction that only reads can see a state that no serial order would produce, because it looks at the data between two other transactions that are themselves fine.

Common misunderstanding: “Read-only transactions are always safe at Repeatable Read.” PostgreSQL itself says Repeatable Read read-only transactions never get serialization errors, but its manual also shows how one can see a batch marked complete without all of its details.

Definition: Fekete et al.'s result, restated by Ports & Grittner as the batch-processing example: NEW-RECEIPT reads the current batch and inserts a receipt; CLOSE-BATCH increments the batch number; REPORT reads the batch number and sums the previous batch. Under SI the report can show a total for batch x that a later commit still changes.

text
     T2 (NEW-RECEIPT)          T3 (CLOSE-BATCH)           T1 (REPORT, read-only)
1    BEGIN; x := current batch (=7)
2                              BEGIN; batch := 8; COMMIT;
3                                                         BEGIN; x := current batch (=8)
4                                                         SUM(amount) WHERE batch = 7; COMMIT;   -- total printed
5    INSERT receipt (batch 7); COMMIT;                    -- the printed total for batch 7 is now wrong

Real scenarios: end-of-day reports, ledger closes, invoices generated for a period that a late write still lands in.

Engine and levelPossible?
Snapshot Isolation anywhere (PostgreSQL Repeatable Read, SQL Server SNAPSHOT, Oracle SERIALIZABLE)Yes
PostgreSQL SerializableNo: SSI aborts one of the writers, or the report
PostgreSQL SERIALIZABLE READ ONLY DEFERRABLENo, and the report itself can never be aborted: it waits for a safe snapshot

Fix: run period-closing reports as SERIALIZABLE READ ONLY DEFERRABLE in PostgreSQL, or make "closed" a row the writers must lock. See consistent reports.

Serialization anomaly Important ​

In plain words: the umbrella term: any committed outcome that does not equal some one-at-a-time order. Write skew and the read-only anomaly are the two famous kinds.

Common misunderstanding: “If none of the named phenomena happens, the history is serializable.” The Critique's whole point is that the named list is incomplete; PostgreSQL's table therefore lists "serialization anomaly" as a fourth column.

Definition: PostgreSQL's wording: "The result of successfully committing a group of transactions is inconsistent with all possible orderings of running those transactions one at a time." The manual's own example: two Serializable transactions each SUM one class of mytab and insert the result into the other class; at Repeatable Read both commit, at Serializable one fails.

text
     T1                                        T2
1    SELECT SUM(value) FROM mytab WHERE class=1;   -- 30
2                                              SELECT SUM(value) FROM mytab WHERE class=2;   -- 300
3    INSERT INTO mytab VALUES (2, 30);
4                                              INSERT INTO mytab VALUES (1, 300);
5    COMMIT;                                   COMMIT;   -- SERIALIZABLE: one fails with 40001

Real scenario: any derived value (totals, counters, quotas) written back based on reads of other rows.

Fix: Serializable + retry, or restructure so the conflict is a write to the same row.

The levels, one by one ​

Read Uncommitted Good to know ​

In plain words: no protection for readers at all: you may see other transactions' uncommitted writes. Writers are still protected from each other.

Common misunderstanding: “Asking for it in PostgreSQL gives me dirty reads (or speed).” PostgreSQL accepts the name and runs Read Committed: "PostgreSQL's Read Uncommitted mode behaves like Read Committed."

Definition: ANSI permits P1, P2, P3. In InnoDB "SELECT statements are performed in a nonlocking fashion, but a possible earlier version of a row might be used"; the manual adds: "This is also called a dirty read." SQL Server's READ UNCOMMITTED and the NOLOCK table hint read without shared locks.

Real scenario: the only defensible use is a rough progress check on a huge batch load in SQL Server or MySQL (SELECT COUNT(*) while the load runs), where a wrong number is acceptable. In MVCC engines a snapshot read is already non-blocking, so even that use disappears.

Read Committed Must-know ​

In plain words: every statement sees only data that was committed before that statement started. The next statement may see newer commits.

Common misunderstanding: “Read Committed is safe for read-modify-write as long as I'm in a transaction.” It allows lost updates, write skew, read skew and phantoms. It is safe for single-statement changes (SET x = x - 1) and for code that locks what it reads.

Definition: PostgreSQL: "a SELECT query (without a FOR UPDATE/SHARE clause) sees only data committed before the query began". Oracle: "every query executed by a transaction sees only data committed before the query—not the transaction—began". The default in PostgreSQL, Oracle and SQL Server; an option in CockroachDB (enabled by sql.txn.read_committed_isolation.enabled, default true) and InnoDB.

How the engines implement it:

EngineMechanism
PostgreSQLNew snapshot per statement; writers re-check rows changed by concurrent commits (see below)
OracleStatement-level read consistency rebuilt from undo data
InnoDB READ COMMITTEDFresh consistent read per statement; gap locking off; semi-consistent read for UPDATE
SQL Server, READ_COMMITTED_SNAPSHOT OFF (on-premises default)Shared locks for the duration of each read: readers block behind writers
SQL Server, RCSI (READ_COMMITTED_SNAPSHOT ON; default on Azure SQL Database)Row versions from the version store: statement-level snapshot, no reader blocking
CockroachDB READ COMMITTEDPer-statement snapshot; client-side retries not required

The PostgreSQL Read Committed re-check surprise Must-know ​

When an UPDATE, DELETE or SELECT ... FOR UPDATE finds a row that a concurrent transaction is changing, PostgreSQL waits; if that transaction commits, it re-evaluates its WHERE clause against the new version of that one row and either proceeds with the new version or skips the row. Rows it did not find in its own snapshot are never considered. The manual's example: website has two rows with hits 9 and 10.

text
     T1                                         T2
1    BEGIN;
2    UPDATE website SET hits = hits + 1;        -- 9 -> 10, 10 -> 11 (rows locked)
3                                               DELETE FROM website WHERE hits = 10;
                                                -- its snapshot sees only the old row with hits=10; it waits for T1
4    COMMIT;
5                                               -- re-checks that row: now hits=11, no match, skipped.
                                                -- The row that now has hits=10 was 9 in T2's snapshot: never examined.
                                                DELETE 0

"The DELETE will have no effect even though there is a website.hits = 10 row before and after the UPDATE." — PostgreSQL documentation, 13.2.1 Read Committed Isolation Level

The rule that falls out: in PostgreSQL Read Committed, a single-row update with a fixed key (WHERE id = 7) is safe and even convenient (the transfer example in the manual), but a statement whose WHERE depends on values other sessions are changing can skip or double-apply work. Use Repeatable Read (which errors with 40001 instead) or lock first. InnoDB READ COMMITTED has a cousin: the semi-consistent read, where an UPDATE that hits a locked row reads the latest committed version "so that MySQL can determine whether the row matches the WHERE condition".

Real scenario: the default level for OLTP web applications; correct when every business rule is either one atomic statement, a constraint, or protected by FOR UPDATE.

Repeatable Read Must-know ​

In plain words: rows you have read will not change under you for the rest of the transaction. What that means beyond rows you read depends entirely on the engine.

Common misunderstanding: “Repeatable Read is one well-defined thing.” It is three different things in PostgreSQL, InnoDB and SQL Server, and that is the most common source of porting bugs.

Definition: ANSI: P1 and P2 forbidden, P3 allowed. Then the engines diverge:

EngineWhat REPEATABLE READ really is
PostgreSQLSnapshot Isolation. One snapshot from the first statement; no phantoms; lost update aborted with 40001 (first-updater-wins); write skew allowed. "Applications using this level must be prepared to retry transactions due to serialization failures."
MySQL InnoDB (default)Plain SELECT: snapshot taken at the first read. Locking reads, UPDATE, DELETE: read the latest committed rows and take next-key locks. No write-conflict error, so lost update is allowed.
SQL ServerLock-based: shared locks on read rows held to commit. Prevents lost update (by deadlock) and fuzzy reads; phantoms allowed.
CockroachDBNot offered (Serializable and Read Committed only)
OracleNot offered (use SERIALIZABLE, which is Snapshot Isolation)

InnoDB's phantom exception at Repeatable Read Must-know ​

InnoDB claims to prevent phantoms at REPEATABLE READ, and it does, in two different ways that do not compose. Plain reads use the snapshot. Locking reads and DML use next-key locks:

"To prevent phantoms, InnoDB uses an algorithm called next-key locking that combines index-row locking with gap locking." — MySQL 8.4 Reference Manual, 17.7.4 Phantom Rows

But the snapshot applies only to SELECT: "The snapshot of the database state applies to SELECT statements within a transaction, not necessarily to DML statements." So a DML statement can act on rows that the transaction's own SELECT cannot see, and after it does, those rows become visible:

text
     T1 (REPEATABLE READ)                           T2
1    START TRANSACTION;
2    SELECT COUNT(*) FROM t1 WHERE c2 = 'abc';      -- 0 (snapshot)
3                                                   INSERT 10 rows with c2 = 'abc'; COMMIT;
4    SELECT COUNT(*) FROM t1 WHERE c2 = 'abc';      -- still 0 (snapshot)
5    UPDATE t1 SET c2 = 'cba' WHERE c2 = 'abc';     -- "Affects 10 rows"
6    SELECT COUNT(*) FROM t1 WHERE c2 = 'cba';      -- 10: the phantom is now in your snapshot

And mixing the two read kinds in one transaction gives two answers to one question: SELECT ... WHERE id > 100 (snapshot) and SELECT ... WHERE id > 100 FOR UPDATE (latest committed + next-key locks) can return different rows at the same instant. Rule: in InnoDB, if you will act on what you read, read it with FOR UPDATE/FOR SHARE.

Real scenario: InnoDB REPEATABLE READ with plain reads is good for consistent multi-statement reports (mysqldump --single-transaction uses exactly that); for read-modify-write it behaves like Read Committed plus gap locks, so use atomic updates or FOR UPDATE.

Snapshot Isolation Must-know ​

In plain words: your whole transaction reads from a photocopy taken when it started; when you write, you lose if someone else already committed a write to the same row after your photocopy.

Common misunderstanding: “Snapshot means serializable because I see a consistent state.” Consistent reads, yes; consistent decisions, no: write skew and the read-only anomaly remain.

Definition: the Critique: a transaction "reads data from a snapshot of the (committed) data as of the time the transaction started", and commits only if no concurrent committed transaction wrote the same data (first-committer-wins). Real engines implement first-updater-wins: the conflict is detected when the second writer touches the row (it waits for the first, then errors if the first committed), not at commit. Products: PostgreSQL Repeatable Read, SQL Server SNAPSHOT (requires ALLOW_SNAPSHOT_ISOLATION ON; conflict is Msg 3960), Oracle SERIALIZABLE (ORA-08177), SQLite in WAL mode (the SQLite docs: in WAL mode SQLite exhibits snapshot isolation for readers), MongoDB transactions with snapshot read concern.

Real scenario: long reports and exports that must be internally consistent without blocking writers; optimistic concurrency for single-row edits where 40001 is an acceptable signal.

Serializable Must-know ​

In plain words: every committed outcome is the same as if transactions had run one at a time in some order. If you can show one transaction is correct alone, it is correct in any mix.

Common misunderstanding: “Serializable is the same everywhere.” Three very different implementations share the name, and one product (Oracle) uses the name for Snapshot Isolation.

Definition and implementations:

ImplementationProductsHow conflicts show up
Strict two-phase locking (2PL) with predicate/range locksInnoDB (SELECT becomes FOR SHARE when autocommit is off, plus next-key locks), SQL Server (key-range locks)Waiting, deadlocks (1213), lock wait timeouts (1205)
Serializable Snapshot Isolation (SSI)PostgreSQL since 9.1, CockroachDB (default level)No extra blocking; 40001 at a statement or at COMMIT
Actual serial executionSQLite (one writer at a time), Redis (MULTI/EXEC)Waiting for the single writer (SQLITE_BUSY)
Snapshot Isolation labelled SERIALIZABLEOracleORA-08177 on write-write conflict; write skew still possible

PostgreSQL adds a guarantee that simplifies application code: "any set of successfully committed concurrent Serializable transactions will have the same effect as if they were run one at a time". The price, from the same page: data read by a serializable transaction must not be "considered valid until the transaction which read it has successfully committed", except in a DEFERRABLE read-only transaction.

Real scenario: money movement with multi-row rules, inventory reservations, quota and limit enforcement, scheduling. The rule-of-thumb from PostgreSQL's performance notes: declare READ ONLY when possible, keep transactions short, avoid sequential scans (they take a relation-level predicate lock), and size max_pred_locks_per_transaction.

Strict Serializable and external consistency Good to know ​

In plain words: Serializable plus “if A finished before B started, A comes first”. Clients on different machines never see time go backwards.

Common misunderstanding: “My single PostgreSQL primary is not strict serializable.” For transactions on one primary it effectively is; the gap opens when you read from replicas or across regions.

Definition: Spanner: "When the isolation level is unspecified, or when you set the isolation level as serializable isolation, Spanner provides clients with the strictest concurrency-control guarantees for transactions, which is called external consistency." It uses TrueTime, which lets it assign commit timestamps "guaranteed to be greater than any timestamp T', if T' finished being generated before T started being generated".

Real scenario: a user changes a password in one region and the old password must stop working everywhere immediately; a ledger replicated across regions.

Per-engine behaviour ​

Matrix 1: the ANSI SQL-92 standard ​

The standard's table, as reproduced in the Critique (Table 1). "Possible" means the level may allow it; an engine is free to be stronger.

LevelP1 Dirty readP2 Fuzzy readP3 Phantom
READ UNCOMMITTEDPossiblePossiblePossible
READ COMMITTEDNot possiblePossiblePossible
REPEATABLE READNot possibleNot possiblePossible
SERIALIZABLENot possibleNot possibleNot possible

Matrix 2: the Critique paper (Berenson et al. 1995, Table 4) ​

LevelP0 Dirty writeP1 Dirty readP4C Cursor lost updateP4 Lost updateP2 Fuzzy readP3 PhantomA5A Read skewA5B Write skew
READ UNCOMMITTED (Degree 1)Not possiblePossiblePossiblePossiblePossiblePossiblePossiblePossible
READ COMMITTED (Degree 2)Not possibleNot possiblePossiblePossiblePossiblePossiblePossiblePossible
Cursor StabilityNot possibleNot possibleNot possibleSometimes possibleSometimes possiblePossiblePossibleSometimes possible
REPEATABLE READ (locking)Not possibleNot possibleNot possibleNot possibleNot possiblePossibleNot possibleNot possible
SnapshotNot possibleNot possibleNot possibleNot possibleNot possibleSometimes possibleNot possiblePossible
ANSI SERIALIZABLE (Degree 3)Not possibleNot possibleNot possibleNot possibleNot possibleNot possibleNot possibleNot possible

Note the two incomparable levels: locking Repeatable Read allows phantoms but not write skew; Snapshot allows write skew but (mostly) not phantoms. That is the paper's "REPEATABLE READ »« Snapshot Isolation".

Matrix 3: what you actually get in production ​

✅ = prevented, ❌ = can happen. “Error” means prevented by aborting one transaction; “lock” means prevented by blocking (and possibly a deadlock).

Engine / levelDirty readNon-repeatablePhantom (re-read)Lost updateRead skewWrite skew
PostgreSQL Read Committed (default)✅❌❌❌❌❌
PostgreSQL Repeatable Read (SI)✅✅✅✅ error 40001✅❌
PostgreSQL Serializable (SSI)✅✅✅✅ error 40001✅✅ error 40001
InnoDB READ COMMITTED✅❌❌❌❌❌
InnoDB REPEATABLE READ (default)✅✅ plain reads✅ plain reads; DML sees new rows❌✅ plain reads❌
InnoDB SERIALIZABLE✅✅ lock✅ next-key lock✅ deadlock 1213✅✅ lock / 1213
SQL Server READ COMMITTED (locking, default)✅❌❌❌❌❌
SQL Server RCSI✅❌❌❌❌❌
SQL Server REPEATABLE READ✅✅ lock❌✅ deadlock✅ lock✅ for rows read; ❌ via inserts
SQL Server SNAPSHOT✅✅✅✅ error 3960✅❌
SQL Server SERIALIZABLE✅✅ lock✅ key-range lock✅ deadlock✅✅ lock
Oracle Read Committed (default)✅❌❌❌❌❌
Oracle SERIALIZABLE (SI)✅✅✅✅ ORA-08177✅❌
CockroachDB SERIALIZABLE (default)✅✅✅✅ error 40001✅✅ error 40001
Dirty readNon-repeatablePhantomLost updateRead skewWrite skewPostgreSQL Read CommittedPostgreSQL Repeatable ReadPostgreSQL SerializableInnoDB Repeatable Readpreventedcan happencan happencan happencan happencan happenpreventedpreventedpreventedpreventedpreventedcan happenpreventedpreventedpreventedpreventedpreventedpreventedpreventedpreventedpartialcan happenpartialcan happenpreventedcan happenpartialPrevented may mean an abort (40001) in PostgreSQL.

What each database really does ​

ProductLevels offeredDefaultImplementationConflict signalWatch out for
PostgreSQLRU (= RC), RC, RR, SerializableRead CommittedMVCC snapshots; RR = Snapshot Isolation; Serializable = SSI with SIReadLock predicate locks40001 serialization_failure, 40P01 deadlock_detected, 55P03 lock_not_available (NOWAIT)RC re-check surprise; long transactions keep dead tuples alive and cause bloat
MySQL InnoDBRU, RC, RR, SerializableRepeatable ReadMVCC for plain reads (undo log); record, gap, next-key and insert intention locks for locking reads and DML; Serializable = plain SELECT becomes FOR SHARE1213 ER_LOCK_DEADLOCK (SQLSTATE 40001, whole transaction rolled back), 1205 ER_LOCK_WAIT_TIMEOUT (only the statement rolled back)Lost update at RR; DML sees rows the snapshot hides; history list length grows under long transactions
SQL ServerRU, RC, RR, SNAPSHOT, Serializable; RC can be RCSIRead Committed with locking (RCSI on Azure SQL Database)Locking by default; row versions in the version store (tempdb, or the user database with ADR) for RCSI and SNAPSHOTMsg 3960 snapshot update conflict; deadlock victimNOLOCK hints; ALLOW_SNAPSHOT_ISOLATION must be ON to use SNAPSHOT; version store growth
OracleRead Committed, Serializable, Read-OnlyRead CommittedMultiversion read consistency from undo data; Serializable = Snapshot IsolationORA-08177 cannot serialize accessWrite skew at SERIALIZABLE; snapshot too old on long reports when undo is overwritten
SQLiteSerializable (RU only with shared cache + PRAGMA read_uncommitted)SerializableSingle writer at a time; in WAL mode readers see a snapshotSQLITE_BUSY, SQLITE_BUSY_SNAPSHOT when a stale reader tries to writeWriters queue; upgrade from read to write fails in WAL mode
MongoDBRead/write concerns per operation; multi-document transactions read with snapshot read concernNo SQL level; single-document writes are atomicSnapshots of majority-committed data; write-write conflict detectionWriteConflict; error labels TransientTransactionError and UnknownTransactionCommitResult; runtime limit transactionLifetimeLimitSeconds (by default under one minute)Snapshot guarantee only if the transaction commits with write concern majority; write skew possible (it is snapshot-based)
CockroachDBSerializable, Read CommittedSerializableDistributed MVCC; a transaction that cannot be placed in a serializable order is restarted40001 with restart transactionClients must retry at Serializable; Read Committed is gated by sql.txn.read_committed_isolation.enabled
SpannerSerializable (default), Repeatable ReadSerializable = external consistencyMVCC + TrueTime timestamps; snapshot and stale reads never block writesAborted read-write transactions must be retriedStrong reads cost more than stale reads; Repeatable Read gives up serializability
RedisMULTI/EXEC (serial), WATCH (optimistic), Lua scripts / functionsn/aSingle-threaded command execution: a transaction runs as one stepEXEC returns null if a WATCHed key changedNo rollback: a failing command inside EXEC does not undo the others

Mechanics ​

There are only two ways to isolate: make conflicting transactions wait (locks) or let them run and abort one when a conflict is detected (versions + validation). Every level in every product is a mix of the two. The lock modes themselves are taught in Locks & Concurrency; here is what each level does with them.

Locking: 2PL, strict 2PL and predicate locks Important ​

Two-phase locking (2PL) says a transaction acquires locks (growing phase) and, once it releases any, acquires no more (shrinking phase). Strict 2PL holds all write locks until commit or abort; rigorous 2PL holds read locks too. Locking Read Committed holds read locks only for the duration of the read (the Critique's "Short duration Read locks"), which is why it permits fuzzy reads. Locking Serializable needs predicate locks: locks on “every row that matches WHERE room = 5”, including rows that do not exist yet. Real engines approximate predicates with index ranges: SQL Server key-range locks, InnoDB next-key locks.

text
time ─▶
T1  S(row 7)  S(row 9)  X(row 9) ........................ commit -> release all
T2            X(row 7)? -- waits until T1 commits (strict 2PL)

InnoDB: record, gap, next-key and insert intention locks Important ​

LockCoversTaken byBlocks
Record lockOne index recordLocking reads, UPDATE, DELETE on a unique index hitOther locks on that record
Gap lockThe open interval between two index recordsRange scans at RR/SerializableInserts into the gap only; gap locks are "purely inhibitive" and do not conflict with each other
Next-key lockRecord + the gap before itDefault for index scans at RR/SerializableInserts into the gap and locks on the record
Insert intention lockA point inside a gap, set by INSERT before the row is insertedEvery INSERTWaits on gap/next-key locks; two inserts of different keys in the same gap do not block each other
text
index on id:   ... 90 ][ gap ][ 102 ][ gap ][ supremum
SELECT * FROM child WHERE id > 100 FOR UPDATE;
                     └──next-key on 102──┘└─ gap after 102 ─┘
session B: INSERT INTO child (id) VALUES (101);   -- insert intention lock waits

At READ COMMITTED InnoDB disables gap locking for searches and index scans (it keeps it for foreign-key and duplicate-key checks), so phantoms come back and deadlocks become rarer. A side effect worth knowing: because next-key locking lets you lock the nonexistence of a row, SELECT ... FOR SHARE followed by INSERT is a valid uniqueness check in InnoDB at RR, while the same code in PostgreSQL locks nothing for a missing row.

MVCC snapshots: first-updater-wins and first-committer-wins Must-know ​

In PostgreSQL, InnoDB (plain reads), Oracle, SQL Server RCSI/SNAPSHOT, CockroachDB and MongoDB, a write creates a new row version and readers pick the version their snapshot can see; readers never block writers. What differs is when the snapshot is taken (per statement at RC, at the first statement at RR/SI; at the first read in InnoDB, or at START TRANSACTION WITH CONSISTENT SNAPSHOT) and what happens on a write-write conflict:

text
first-updater-wins (PostgreSQL RR, Oracle SERIALIZABLE, SQL Server SNAPSHOT)
T1: snapshot@100 ... UPDATE row r (locks r) ................ COMMIT@120
T2: snapshot@105 ........... UPDATE row r -> waits for T1 -> T1 committed -> ERROR 40001 / ORA-08177 / Msg 3960
                                                    (if T1 had rolled back, T2 proceeds)

InnoDB REPEATABLE READ (no conflict check)
T2: ... UPDATE row r -> waits for T1 -> T1 committed -> applies to T1's version (lost update if T2 computed from its snapshot)
Read Committed: one snapshot per statementRepeatable Read / Snapshot Isolation: one snapshot per transactiontimetimeT1: SELECT price snapshot AT1: SELECT price snapshot BT2: UPDATE price=20; COMMITsees 10sees 20 (non-repeatable read)T1: SELECT price snapshot AT1: SELECT price still AT2: UPDATE price=20; COMMITsees 10sees 10 (repeatable)one snapshot

The MVCC storage details (tuple headers, visibility rules, undo chains) are in MVCC, VACUUM & Bloat.

SSI: SIReadLock, rw-dependencies and the pivot Important ​

PostgreSQL's Serializable runs Snapshot Isolation and additionally records what each transaction read as SIReadLock entries (visible in pg_locks). An rw-dependency (rw-antidependency) T1 → T2 means T1 read a version that T2's write replaced, so T1 must come before T2 in any serial order. A cycle in the dependency graph means no serial order exists. Instead of searching for cycles, SSI looks for a "dangerous structure": two adjacent rw-dependencies T1 → T2 → T3, where T2 is the pivot (it has both an incoming and an outgoing rw edge). When it sees one (and the commit order makes an anomaly possible), it aborts one transaction with 40001, chosen by the paper's "safe retry" rule: retrying the aborted transaction immediately will not fail the same way.

text
write skew as a graph (doctors example):
  T1 --rw--> T2   (T1 read Bob's row, T2 wrote it)
  T2 --rw--> T1   (T2 read Alice's row, T1 wrote it)
  cycle -> one of them gets: ERROR: could not serialize access due to read/write dependencies among transactions

read-only anomaly (batch example):
  T1 REPORT --rw--> T2 NEW-RECEIPT --rw--> T3 CLOSE-BATCH, and T3 --wr--> T1
  T2 is the pivot; SSI aborts one of the three
T1reads xT2 (pivot)writes x, reads y1 edge in, 1 edge outT3writes yrwrwdangerous structure foundone transaction aborts: 40001rw-dependency: reader saw a version that the writer replaced

Properties you rely on in production: SIReadLocks never block, so they cannot cause deadlocks; they are kept past commit until overlapping transactions finish; they escalate from tuple to page to relation when memory is short (tune max_pred_locks_per_transaction, max_pred_locks_per_relation, max_pred_locks_per_page); a sequential scan always takes a relation-level predicate lock, which raises false positives. Read-only transactions often take no predicate locks at all, and SERIALIZABLE READ ONLY DEFERRABLE waits until it can get a safe snapshot and then runs with zero SSI overhead and zero risk of abort.

The cost of long snapshots: bloat, undo, version store Must-know ​

Every snapshot level keeps old row versions alive until the oldest transaction that might need them ends. One forgotten BEGIN in a connection pool can hurt the whole database:

EngineWhat piles upSymptomKnob / metric
PostgreSQLDead tuples that VACUUM cannot removeTable and index bloat, slower scans, xid age growthidle_in_transaction_session_timeout, transaction_timeout (SQLSTATE 25P03/25P04), pg_stat_activity.backend_xmin
MySQL InnoDBUndo log records not purgedHistory list length grows; reads walk long version chainsSHOW ENGINE INNODB STATUS "History list length", innodb_purge_*
SQL ServerRow versions in the version store (tempdb, or the user database with ADR)tempdb fills; with tempdb full, reads may fail for missing versionsVersion store size DMVs
OracleUndo needed for consistent reads gets overwrittensnapshot too old error on long queriesUndo retention period
MongoDBSnapshot history in the WiredTiger cacheCache pressure; long transactions abortedtransactionLifetimeLimitSeconds

Setting the level: every knob Must-know ​

sql
-- PostgreSQL
SHOW default_transaction_isolation;                        -- 'read committed'
ALTER DATABASE app SET default_transaction_isolation = 'repeatable read';
BEGIN ISOLATION LEVEL SERIALIZABLE;                        -- per transaction
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE, READ ONLY, DEFERRABLE;  -- first statement after BEGIN
SHOW transaction_isolation;                                -- level of the current transaction
SET idle_in_transaction_session_timeout = '30s';

-- MySQL InnoDB
SELECT @@transaction_isolation;                            -- 'REPEATABLE-READ'
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;    -- this session
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;              -- next transaction only; ERROR 1568 inside one
START TRANSACTION WITH CONSISTENT SNAPSHOT;                -- take the RR snapshot now, not at first read
START TRANSACTION READ ONLY;
SET SESSION innodb_lock_wait_timeout = 5;                  -- seconds; error 1205 when exceeded

-- SQL Server
ALTER DATABASE app SET READ_COMMITTED_SNAPSHOT ON;         -- RCSI for READ COMMITTED
ALTER DATABASE app SET ALLOW_SNAPSHOT_ISOLATION ON;        -- permit SNAPSHOT
SET TRANSACTION ISOLATION LEVEL SNAPSHOT;
SELECT * FROM orders WITH (READCOMMITTEDLOCK);             -- force locking RC under RCSI
SELECT * FROM orders WITH (NOLOCK);                        -- = READ UNCOMMITTED: avoid

-- Oracle
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SET TRANSACTION READ ONLY;

-- CockroachDB
SET default_transaction_isolation = 'read committed';      -- requires sql.txn.read_committed_isolation.enabled
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;

Two portability traps: PostgreSQL rejects a level change after the first query ("cannot be changed after the first query or data-modification statement"), and MySQL rejects SET TRANSACTION inside an open transaction with ERROR 1568 (25001): Transaction characteristics can't be changed while a transaction is in progress. ORMs that issue a query on BEGIN (or reuse a pooled connection mid-transaction) trip both.

Error codes you will catch Must-know ​

ProductCode / messageMeaningRetry the whole transaction?
PostgreSQL40001 serialization_failure: "could not serialize access due to concurrent update"RR/Serializable write-write conflictYes
PostgreSQL40001: "could not serialize access due to read/write dependencies among transactions"SSI found a dangerous structureYes
PostgreSQL40P01 deadlock_detectedLock cycle; one transaction abortedYes
PostgreSQL55P03 lock_not_availableNOWAIT could not lock, or lock_timeoutMaybe (it is a policy decision)
PostgreSQL23505 unique_violation, 23P01 exclusion_violationConstraint caught the raceNo: report a business conflict (or upsert)
PostgreSQL25006 read_only_sql_transactionWrite inside READ ONLYNo: bug
MySQL1213 ER_LOCK_DEADLOCK, SQLSTATE 40001Deadlock; InnoDB rolled back the entire transactionYes
MySQL1205 ER_LOCK_WAIT_TIMEOUT, SQLSTATE HY000innodb_lock_wait_timeout exceeded; only the statement was rolled backYes, after rolling back the rest
MySQL1062 ER_DUP_ENTRY, SQLSTATE 23000Unique key caught the raceNo: business conflict
MySQL1568 (25001)SET TRANSACTION inside a transactionNo: bug
SQL ServerMsg 3960SNAPSHOT update conflictYes
OracleORA-08177Cannot serialize access (SI conflict)Yes
CockroachDB40001 "restart transaction"Could not place the transaction in a serializable orderYes
SQLiteSQLITE_BUSY, SQLITE_BUSY_SNAPSHOTAnother writer holds the lock / stale snapshot tried to writeYes, from BEGIN
MongoDBWriteConflict, label TransientTransactionErrorConcurrent write to the same documentYes (the callback API does it)
RedisEXEC returns nullA WATCHed key changedYes: re-read and retry

Solving the classic problems ​

The Go fragments below use WithTx and DefaultPolicy from the retry section and database/sql with PostgreSQL placeholders ($1); for MySQL swap to ?. The Laravel fragments use the query builder and Eloquent from Laravel 13.

Lost update ​

SolutionHowAdvantageCost / limitation
Atomic updateCompute in SQL: SET stock = stock - 1 WHERE stock >= 1No extra round trip, correct at Read Committed in every engineLogic must fit in one statement; check affected rows
Pessimistic lockSELECT ... FOR UPDATE, then updateArbitrary application logic between read and writeHolds a row lock across a round trip; deadlock risk if order varies
Version column (optimistic)UPDATE ... SET version = version + 1 WHERE id = ? AND version = ?No locks held while the user thinks; works across HTTP requestsCaller must handle 0 rows updated (conflict)
Higher levelPostgreSQL Repeatable Read/Serializable, SQL Server SNAPSHOT, Oracle SERIALIZABLENo code change to the logicMust retry on 40001; InnoDB RR does not help
sql
-- 1. Atomic update (any engine, Read Committed is enough)
UPDATE products SET stock = stock - 1 WHERE id = 42 AND stock >= 1;   -- 0 rows -> out of stock

-- 2. Pessimistic: lock the row you will write
BEGIN;
SELECT stock FROM products WHERE id = 42 FOR UPDATE;    -- PostgreSQL: FOR NO KEY UPDATE is enough and lighter
UPDATE products SET stock = 0 WHERE id = 42;
COMMIT;

-- 3. Optimistic: version column
UPDATE pages SET body = 'new text', version = version + 1
 WHERE id = 7 AND version = 12;                          -- 0 rows -> someone else saved first
go
// Atomic update: correct at READ COMMITTED; no transaction needed.
func reserveStock(ctx context.Context, db *sql.DB, productID, qty int64) error {
	res, err := db.ExecContext(ctx,
		`UPDATE products SET stock = stock - $1 WHERE id = $2 AND stock >= $1`, qty, productID)
	if err != nil {
		return err
	}
	if n, _ := res.RowsAffected(); n == 0 {
		return errors.New("out of stock")
	}
	return nil
}

// Optimistic: the version travels with the edit form.
func savePage(ctx context.Context, db *sql.DB, id, version int64, body string) error {
	res, err := db.ExecContext(ctx,
		`UPDATE pages SET body = $1, version = version + 1 WHERE id = $2 AND version = $3`,
		body, id, version)
	if err != nil {
		return err
	}
	if n, _ := res.RowsAffected(); n == 0 {
		return errors.New("page was changed by someone else; reload")
	}
	return nil
}
php
use Illuminate\Support\Facades\DB;

// Atomic update: decrement() returns the number of affected rows.
$ok = DB::table('products')
    ->where('id', $productId)
    ->where('stock', '>=', $qty)
    ->decrement('stock', $qty) === 1;

// Pessimistic: lockForUpdate() inside DB::transaction (lockForNoKeyUpdate() on PostgreSQL).
DB::transaction(function () use ($productId, $qty) {
    $product = Product::whereKey($productId)->lockForUpdate()->firstOrFail();
    if ($product->stock < $qty) {
        throw new OutOfStock($productId);
    }
    $product->decrement('stock', $qty);
});

// Optimistic: version column.
$updated = Page::whereKey($id)->where('version', $version)
    ->update(['body' => $body, 'version' => $version + 1]);
if ($updated === 0) {
    throw new StaleEdit($id);
}

Runnable demo. The Go pair below reproduces the bug and the Serializable fix against PostgreSQL: two goroutines read stock 10 and write stock-1; under Read Committed the result is 9, under Serializable with retry it is 8.

go
// Lost update demonstration: two goroutines run a read-then-write stock
// decrement under READ COMMITTED. Both read the same value, so one decrement
// vanishes. Needs a PostgreSQL DSN in DATABASE_URL and a table:
//
//	CREATE TABLE products (id int PRIMARY KEY, stock int NOT NULL);
//	INSERT INTO products VALUES (1, 10);
package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"
	"sync"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib"
)

// decrement reads the stock, pauses, then writes back stock-1.
// The write is based on a value that may already be stale.
func decrement(ctx context.Context, db *sql.DB, id int) error {
	tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
	if err != nil {
		return err
	}
	defer tx.Rollback()

	var stock int
	if err := tx.QueryRowContext(ctx, `SELECT stock FROM products WHERE id = $1`, id).Scan(&stock); err != nil {
		return err
	}

	time.Sleep(100 * time.Millisecond) // widen the race window

	if _, err := tx.ExecContext(ctx, `UPDATE products SET stock = $1 WHERE id = $2`, stock-1, id); err != nil {
		return err
	}
	return tx.Commit()
}

func main() {
	ctx := context.Background()
	db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	var wg sync.WaitGroup
	for range 2 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if err := decrement(ctx, db, 1); err != nil {
				log.Println("decrement:", err)
			}
		}()
	}
	wg.Wait()

	var stock int
	if err := db.QueryRowContext(ctx, `SELECT stock FROM products WHERE id = 1`).Scan(&stock); err != nil {
		log.Fatal(err)
	}
	// Two decrements from 10 should leave 8. Under READ COMMITTED it leaves 9.
	fmt.Println("stock:", stock)
}
go
// Same demonstration at SERIALIZABLE. PostgreSQL aborts one transaction with
// SQLSTATE 40001 (serialization_failure) and the caller retries the whole
// transaction, which then sees the committed value.
package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"log"
	"os"
	"sync"
	"time"

	"github.com/jackc/pgx/v5/pgconn"
	_ "github.com/jackc/pgx/v5/stdlib"
)

const maxAttempts = 5

func isSerializationFailure(err error) bool {
	var pgErr *pgconn.PgError
	return errors.As(err, &pgErr) && pgErr.Code == "40001"
}

func decrementOnce(ctx context.Context, db *sql.DB, id int) error {
	tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
	if err != nil {
		return err
	}
	defer tx.Rollback()

	var stock int
	if err := tx.QueryRowContext(ctx, `SELECT stock FROM products WHERE id = $1`, id).Scan(&stock); err != nil {
		return err
	}

	time.Sleep(100 * time.Millisecond) // widen the race window

	if _, err := tx.ExecContext(ctx, `UPDATE products SET stock = $1 WHERE id = $2`, stock-1, id); err != nil {
		return err
	}
	return tx.Commit()
}

// decrement retries the WHOLE transaction on 40001, never a single statement.
func decrement(ctx context.Context, db *sql.DB, id int) error {
	var err error
	for attempt := 1; attempt <= maxAttempts; attempt++ {
		if err = decrementOnce(ctx, db, id); !isSerializationFailure(err) {
			return err
		}
		time.Sleep(time.Duration(attempt) * 20 * time.Millisecond) // simple backoff
	}
	return fmt.Errorf("gave up after %d attempts: %w", maxAttempts, err)
}

func main() {
	ctx := context.Background()
	db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	var wg sync.WaitGroup
	for range 2 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if err := decrement(ctx, db, 1); err != nil {
				log.Println("decrement:", err)
			}
		}()
	}
	wg.Wait()

	var stock int
	if err := db.QueryRowContext(ctx, `SELECT stock FROM products WHERE id = 1`).Scan(&stock); err != nil {
		log.Fatal(err)
	}
	fmt.Println("stock:", stock) // 8: both decrements survive
}

The Laravel pair shows the same: the read-modify-write in DB::transaction that loses updates, and the PostgreSQL Serializable version with attempts:.

php
<?php

// app/Services/StockService.php — read-modify-write at the connection's
// default isolation level (READ COMMITTED on PostgreSQL, REPEATABLE READ on
// MySQL/InnoDB). The transaction does not make the arithmetic safe.
namespace App\Services;

use App\Models\Product;
use Illuminate\Support\Facades\DB;

final class StockService
{
    public function decrement(int $productId, int $qty): void
    {
        DB::transaction(function () use ($productId, $qty) {
            $product = Product::findOrFail($productId);

            // A concurrent request may have committed a decrement between the
            // read above and the write below. On PostgreSQL READ COMMITTED
            // this silently overwrites it: a lost update.
            $product->stock = $product->stock - $qty;
            $product->save();
        });
    }
}
php
<?php

// app/Services/StockService.php — PostgreSQL: run the transaction at
// SERIALIZABLE and let Laravel retry it when PostgreSQL reports a
// serialization failure (SQLSTATE 40001).
namespace App\Services;

use App\Models\Product;
use Illuminate\Support\Facades\DB;

final class StockService
{
    public function decrement(int $productId, int $qty): void
    {
        DB::transaction(function () use ($productId, $qty) {
            // Must be the first statement after BEGIN, before any query.
            // On MySQL this statement is rejected inside a transaction; set
            // the level on the connection config or before DB::beginTransaction().
            DB::statement('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');

            $product = Product::findOrFail($productId);
            $product->stock = $product->stock - $qty;
            $product->save();
        }, attempts: 5);
        // Failures arrive as Illuminate\Database\QueryException wrapping a
        // PDOException with SQLSTATE 40001. DB::transaction re-runs the whole
        // closure for concurrency errors and rethrows once attempts run out.
        // Keep side effects (emails, queue dispatches) out of the closure:
        // it may execute more than once.
    }
}

Write skew ​

SolutionHowAdvantageCost / limitation
Serializable + retryPostgreSQL SSI, CockroachDB default, InnoDB/SQL Server SERIALIZABLEFixes every write skew, including ones you did not foreseeRetries; on InnoDB/SQL Server more blocking and deadlocks
Lock what the rule readsSELECT ... FOR UPDATE on all rows the check reads (or on a parent row)Works at Read CommittedMust cover every row the rule depends on; cannot lock rows that do not exist yet
Materializing the conflictAdd a row that every participant must update (e.g. shifts(day) row, customers.credit_used)Turns write skew into an ordinary write-write conflictSchema change; a hot row under heavy concurrency
Advisory lockpg_advisory_xact_lock(hashtext('oncall:' || team)) in PostgreSQL, GET_LOCK() in MySQLNo schema changeEvery writer must remember to take it
ConstraintCHECK, unique, exclusion constraint, or a triggerEnforced by the engine for every writerOnly for rules a constraint can express
sql
-- Lock the rule's inputs: every on-call doctor row of the team (PostgreSQL / InnoDB)
BEGIN;
SELECT id FROM doctors WHERE team_id = 3 AND on_call FOR UPDATE;   -- both transactions now queue here
-- re-count under the lock, then:
UPDATE doctors SET on_call = false WHERE id = 17;
COMMIT;

-- Materialise the conflict: one row per team that every change must touch
UPDATE teams SET on_call_count = on_call_count - 1
 WHERE id = 3 AND on_call_count >= 2;                              -- 0 rows -> refuse
UPDATE doctors SET on_call = false WHERE id = 17;
go
// Write skew handled by Serializable + retry (PostgreSQL SSI / CockroachDB).
func goOffCall(ctx context.Context, db *sql.DB, teamID, doctorID int64) error {
	opts := &sql.TxOptions{Isolation: sql.LevelSerializable}
	return WithTx(ctx, db, opts, DefaultPolicy, func(tx *sql.Tx) error {
		var onCall int
		if err := tx.QueryRowContext(ctx,
			`SELECT count(*) FROM doctors WHERE team_id = $1 AND on_call`, teamID).Scan(&onCall); err != nil {
			return err
		}
		if onCall < 2 {
			return errors.New("at least one doctor must stay on call")
		}
		_, err := tx.ExecContext(ctx, `UPDATE doctors SET on_call = false WHERE id = $1`, doctorID)
		return err
	})
}
php
// Laravel, Read Committed: lock every row the rule reads, then decide.
DB::transaction(function () use ($teamId, $doctorId) {
    $onCall = Doctor::where('team_id', $teamId)->where('on_call', true)
        ->lockForUpdate()->get();
    if ($onCall->count() < 2) {
        throw new MinimumStaffing($teamId);
    }
    Doctor::whereKey($doctorId)->update(['on_call' => false]);
}, attempts: 3);

Check-then-insert (uniqueness and quotas) ​

SELECT to see if a username, coupon redemption or idempotency key exists, then INSERT: at Read Committed and at every snapshot level two requests both see "nothing" and both insert. A row lock cannot help because the row does not exist yet.

SolutionHowAdvantageCost / limitation
Unique constraintUNIQUE (email), UNIQUE (order_id, coupon_id)Correct at any level, in every engineCatch 23505 / 1062 and turn it into a business answer
Insert-or-skipPostgreSQL INSERT ... ON CONFLICT DO NOTHING, MySQL INSERT IGNORENo exception path; RETURNING/affected rows tells you who wonMySQL INSERT IGNORE ignores every "ignorable" error, not only duplicates
UpsertPostgreSQL ON CONFLICT DO UPDATE, MySQL ON DUPLICATE KEY UPDATEOne atomic statementOnly for “create or update” semantics
InnoDB next-key checkSELECT ... FOR SHARE then INSERT at RRWorks for non-unique predicatesDeadlock-prone when both insert; InnoDB only
SerializablePostgreSQL SSIWorks for counts (at most 3 keys)Retries; the manual notes you may still see a 23505
sql
CREATE TABLE redemptions (
  order_id  bigint NOT NULL,
  coupon_id bigint NOT NULL,
  PRIMARY KEY (order_id, coupon_id)
);
-- PostgreSQL
INSERT INTO redemptions VALUES (10, 3) ON CONFLICT DO NOTHING RETURNING order_id;   -- no row -> already redeemed
-- MySQL
INSERT IGNORE INTO redemptions VALUES (10, 3);                                     -- 0 rows affected -> already redeemed
go
// Idempotency key: the unique constraint is the arbiter, not a prior SELECT.
func claimIdempotencyKey(ctx context.Context, db *sql.DB, key string) (bool, error) {
	res, err := db.ExecContext(ctx,
		`INSERT INTO idempotency_keys (key) VALUES ($1) ON CONFLICT DO NOTHING`, key)
	if err != nil {
		return false, err
	}
	n, err := res.RowsAffected()
	return n == 1, err
}
php
// insertOrIgnore() compiles to INSERT IGNORE (MySQL) / ON CONFLICT DO NOTHING (PostgreSQL).
$first = DB::table('redemptions')->insertOrIgnore([
    'order_id' => $orderId,
    'coupon_id' => $couponId,
]) === 1;

Double booking (exclusion constraint) ​

Two bookings for the same room that overlap in time are not equal keys, so a unique index cannot catch them. PostgreSQL's EXCLUDE USING gist can: "Exclusion constraints ensure that if any two rows are compared on the specified columns or expressions using the specified operators, at least one of these operator comparisons will return false or null." The btree_gist extension is needed to mix the scalar room_id WITH = into a GiST constraint.

sql
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE bookings (
  id      bigserial PRIMARY KEY,
  room_id bigint    NOT NULL,
  during  tstzrange NOT NULL,
  EXCLUDE USING gist (room_id WITH =, during WITH &&)
);
INSERT INTO bookings (room_id, during) VALUES (5, '[2026-12-01 10:00, 2026-12-01 11:00)');
INSERT INTO bookings (room_id, during) VALUES (5, '[2026-12-01 10:30, 2026-12-01 11:30)');
-- ERROR:  conflicting key value violates exclusion constraint "bookings_room_id_during_excl"   (SQLSTATE 23P01)

The constraint works at Read Committed and holds even when the two inserts are concurrent: the second waits for the first and then fails. MySQL has no exclusion constraints; there, use a slot table with a unique key (UNIQUE (room_id, slot_start) with one row per 15-minute slot, materializing the conflict), lock the room row with FOR UPDATE before checking overlaps, or run SERIALIZABLE.

go
var errSlotTaken = errors.New("room already booked for that time")

func book(ctx context.Context, db *sql.DB, roomID int64, from, to time.Time) error {
	_, err := db.ExecContext(ctx,
		`INSERT INTO bookings (room_id, during) VALUES ($1, tstzrange($2, $3, '[)'))`, roomID, from, to)
	var pgErr *pgconn.PgError
	if errors.As(err, &pgErr) && pgErr.Code == "23P01" { // exclusion_violation
		return errSlotTaken
	}
	return err
}
php
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

// Migration: Laravel has no fluent API for exclusion constraints; use raw SQL.
DB::statement('CREATE EXTENSION IF NOT EXISTS btree_gist');
DB::statement('ALTER TABLE bookings ADD CONSTRAINT bookings_no_overlap
    EXCLUDE USING gist (room_id WITH =, during WITH &&)');

// Application code: translate 23P01 into a domain error.
try {
    DB::insert("INSERT INTO bookings (room_id, during) VALUES (?, tstzrange(?, ?, '[)'))", [$roomId, $from, $to]);
} catch (QueryException $e) {
    if ($e->getCode() === '23P01') {
        throw new SlotTaken($roomId);
    }
    throw $e;
}

Consistent reports and exports ​

SolutionHowAdvantageCost / limitation
One statementTotals and details in one query (SUM ... GROUP BY, CTE)Statement snapshot at any levelNot always possible
Snapshot, read-onlyPostgreSQL REPEATABLE READ READ ONLY; MySQL START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLYEvery query sees one moment; read-only transactions never get serialization errors in PostgreSQL RRLong snapshot = bloat / history list length; can still show the read-only anomaly
Safe snapshotPostgreSQL SERIALIZABLE READ ONLY DEFERRABLEConsistent with every serial order and cannot be abortedMay wait at start until no conflicting writers are active
Dump toolspg_dump (snapshot; --serializable-deferrable for the safe version), mysqldump --single-transactionConsistent backup without blocking writersmysqldump --single-transaction is consistent for InnoDB only, and must not overlap DDL
Read replicaRun the report on a replicaTakes load off the primaryReplica lag; on PostgreSQL long queries conflict with replay
sql
-- PostgreSQL: end-of-day ledger report that can never show an impossible state
BEGIN ISOLATION LEVEL SERIALIZABLE, READ ONLY, DEFERRABLE;
SELECT batch, sum(amount) FROM receipts WHERE batch = 7 GROUP BY batch;
SELECT count(*) FROM receipts WHERE batch = 7;
COMMIT;

-- MySQL InnoDB: multi-query export from one snapshot taken right now
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY;
SELECT ...; SELECT ...;
COMMIT;
bash
pg_dump --serializable-deferrable -Fc app > app.dump
mysqldump --single-transaction --routines --triggers app > app.sql

database/sql has no DEFERRABLE flag in sql.TxOptions, so in Go either issue SET TRANSACTION as the first statement or use pgx's native options:

go
// pgx native: Serializable, read-only, deferrable (PostgreSQL only).
func endOfDayTotal(ctx context.Context, pool *pgxpool.Pool, batch int) (int64, error) {
	var total int64
	err := pgx.BeginTxFunc(ctx, pool, pgx.TxOptions{
		IsoLevel:       pgx.Serializable,
		AccessMode:     pgx.ReadOnly,
		DeferrableMode: pgx.Deferrable,
	}, func(tx pgx.Tx) error {
		return tx.QueryRow(ctx, `SELECT coalesce(sum(amount), 0) FROM receipts WHERE batch = $1`, batch).Scan(&total)
	})
	return total, err
}
php
// Laravel on PostgreSQL: the SET must be the first statement in the transaction.
$rows = DB::transaction(function () {
    DB::statement('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE, READ ONLY, DEFERRABLE');

    return DB::table('receipts')->where('batch', 7)
        ->selectRaw('count(*) AS n, sum(amount) AS total')->first();
});

Job queue without double processing (SKIP LOCKED) ​

Workers that SELECT the oldest pending job and then UPDATE it race each other (two workers take the same job: a lost update), and with plain FOR UPDATE they queue behind each other. FOR UPDATE SKIP LOCKED (PostgreSQL and MySQL 8.4) gives each worker a different row without waiting: "With SKIP LOCKED, any selected rows that cannot be immediately locked are skipped." MySQL's manual adds the caveat: "Queries that skip locked rows return an inconsistent view of the data", so use it for queues, not for reports.

sql
-- PostgreSQL and MySQL 8.4: identical syntax
BEGIN;
SELECT id, payload FROM jobs
 WHERE status = 'pending' AND run_at <= now()
 ORDER BY run_at
 LIMIT 10
 FOR UPDATE SKIP LOCKED;
-- the application sends back the ids it received:
UPDATE jobs SET status = 'running', locked_at = now() WHERE id IN (101, 102, 103);
COMMIT;
-- NOWAIT instead of SKIP LOCKED: fail at once (PostgreSQL 55P03, MySQL 3572 ER_LOCK_NOWAIT) instead of skipping
go
func claimJobs(ctx context.Context, db *sql.DB, limit int) ([]int64, error) {
	var ids []int64
	err := WithTx(ctx, db, &sql.TxOptions{Isolation: sql.LevelReadCommitted}, DefaultPolicy, func(tx *sql.Tx) error {
		ids = ids[:0]
		rows, err := tx.QueryContext(ctx, `
			SELECT id FROM jobs WHERE status = 'pending' AND run_at <= now()
			ORDER BY run_at LIMIT $1 FOR UPDATE SKIP LOCKED`, limit)
		if err != nil {
			return err
		}
		defer rows.Close()
		for rows.Next() {
			var id int64
			if err := rows.Scan(&id); err != nil {
				return err
			}
			ids = append(ids, id)
		}
		if err := rows.Err(); err != nil {
			return err
		}
		for _, id := range ids {
			if _, err := tx.ExecContext(ctx, `UPDATE jobs SET status = 'running', locked_at = now() WHERE id = $1`, id); err != nil {
				return err
			}
		}
		return nil
	})
	return ids, err
}
php
// Laravel: lock() accepts a raw lock clause.
$jobs = DB::transaction(function () {
    $jobs = DB::table('jobs_queue')
        ->where('status', 'pending')
        ->where('run_at', '<=', now())
        ->orderBy('run_at')
        ->limit(10)
        ->lock('for update skip locked')
        ->get();

    DB::table('jobs_queue')->whereIn('id', $jobs->pluck('id'))
        ->update(['status' => 'running', 'locked_at' => now()]);

    return $jobs;
});

Laravel's own database queue driver pops jobs with FOR UPDATE SKIP LOCKED when the server supports it (DatabaseQueue::getLockForPopping()); the details are on Laravel Queue Internals.

Retries and failure handling ​

Any level above Read Committed, and any locking at all, means some transactions will be aborted by the database and must be run again. PostgreSQL: "applications using this level must be prepared to retry transactions due to serialization failures." InnoDB: "Both deadlocks and lock wait timeouts are normal on busy servers and it is necessary for applications to be aware that they may happen and handle them by retrying."

ErrorEngineRetry?Note
SQLSTATE 40001PostgreSQL, CockroachDB, MySQL (as SQLSTATE of 1213)YesRetry the whole transaction, from BEGIN
40P01PostgreSQLYesAlso fix lock ordering (Deadlocks)
1213MySQLYesTransaction already rolled back by InnoDB
1205MySQLYes, carefullyOnly the statement was rolled back: roll back the transaction yourself before retrying
Msg 3960, ORA-08177SQL Server, OracleYesSnapshot write conflict
23505, 1062, 23P01PostgreSQL, MySQLNoThe constraint did its job: answer the user
TransientTransactionErrorMongoDBYesThe driver's callback API retries for you

Rules.

  1. Retry the whole transaction, never a single statement: after 40001 the transaction is dead in PostgreSQL (every later statement fails with 25P02 in_failed_sql_transaction), and its reads are stale anyway.
  2. The function you retry must be side-effect free outside the database: no emails, HTTP calls or queue publishes inside it. Do them after commit (DB::afterCommit, an outbox row).
  3. Bound the attempts (3–10) and use retry with jitter (exponential backoff with a random delay) so that the transactions that just collided do not collide again in lockstep.
  4. Classify the COMMIT error too: SSI can fail at commit.
  5. Retry only at the outermost transaction boundary; an inner retry inside an outer transaction re-runs on a doomed transaction.
  6. Measure: export the retry count and the 40001 rate. A rising rate means a hot row, a missing index (sequential scans take relation-level SIRead locks), or transactions that are too long.

Go: a WithTx wrapper for pgx and go-sql-driver ​

database/sql gives you sql.TxOptions{Isolation, ReadOnly} and nothing else: no retry, no typed serialization error. The wrapper below classifies pgx's *pgconn.PgError (40001, 40P01) and go-sql-driver's *mysql.MySQLError (1213, 1205), uses full jitter, respects context cancellation, and classifies the commit error.

go
// WithTx: run a function inside a transaction at a chosen isolation level and
// retry the WHOLE function on serialization failures, deadlocks and lock wait
// timeouts. Works with PostgreSQL (pgx stdlib) and MySQL (go-sql-driver).
//
//	DB_DRIVER=pgx   DATABASE_URL=postgres://app:app@localhost:5432/app
//	DB_DRIVER=mysql DATABASE_URL='app:app@tcp(localhost:3306)/app'
package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"log"
	"math/rand/v2"
	"os"
	"time"

	"github.com/go-sql-driver/mysql"
	"github.com/jackc/pgx/v5/pgconn"
	_ "github.com/jackc/pgx/v5/stdlib"
)

// Retryable reports whether err means "the database aborted this transaction
// because of a concurrent one; running it again may succeed".
func Retryable(err error) bool {
	var pgErr *pgconn.PgError
	if errors.As(err, &pgErr) {
		switch pgErr.Code {
		case "40001", // serialization_failure (RR/Serializable, SSI)
			"40P01": // deadlock_detected
			return true
		}
		return false
	}
	var myErr *mysql.MySQLError
	if errors.As(err, &myErr) {
		switch myErr.Number {
		case 1213, // ER_LOCK_DEADLOCK, SQLSTATE 40001: whole transaction rolled back
			1205: // ER_LOCK_WAIT_TIMEOUT: only the statement rolled back, we roll back the rest
			return true
		}
	}
	return false
}

// Policy bounds the retry loop.
type Policy struct {
	MaxAttempts int
	BaseDelay   time.Duration
	MaxDelay    time.Duration
}

var DefaultPolicy = Policy{MaxAttempts: 5, BaseDelay: 10 * time.Millisecond, MaxDelay: 500 * time.Millisecond}

// backoff returns a "full jitter" delay: random in [0, min(MaxDelay, Base*2^attempt)).
func (p Policy) backoff(attempt int) time.Duration {
	ceiling := p.BaseDelay << attempt
	if ceiling <= 0 || ceiling > p.MaxDelay {
		ceiling = p.MaxDelay
	}
	return time.Duration(rand.Int64N(int64(ceiling)))
}

// WithTx runs fn in a fresh transaction per attempt. fn must touch only the
// database through tx: no HTTP calls, no queue publishes, no emails, because
// it may run several times. The commit error is classified too, because
// PostgreSQL SSI can report 40001 at COMMIT.
func WithTx(ctx context.Context, db *sql.DB, opts *sql.TxOptions, p Policy, fn func(*sql.Tx) error) error {
	var err error
	for attempt := 0; attempt < p.MaxAttempts; attempt++ {
		if err = runOnce(ctx, db, opts, fn); err == nil || !Retryable(err) {
			return err
		}
		select {
		case <-time.After(p.backoff(attempt)):
		case <-ctx.Done():
			return errors.Join(ctx.Err(), err)
		}
	}
	return fmt.Errorf("transaction gave up after %d attempts: %w", p.MaxAttempts, err)
}

func runOnce(ctx context.Context, db *sql.DB, opts *sql.TxOptions, fn func(*sql.Tx) error) error {
	tx, err := db.BeginTx(ctx, opts)
	if err != nil {
		return err
	}
	if err := fn(tx); err != nil {
		_ = tx.Rollback()
		return err
	}
	return tx.Commit()
}

// transfer moves money between two accounts with a "total balance of the
// customer must stay >= 0" rule: a write-skew-prone invariant, so it runs at
// SERIALIZABLE and relies on WithTx for the retry.
func transfer(ctx context.Context, db *sql.DB, from, to, cents int64) error {
	opts := &sql.TxOptions{Isolation: sql.LevelSerializable}
	return WithTx(ctx, db, opts, DefaultPolicy, func(tx *sql.Tx) error {
		var total int64
		q := `SELECT COALESCE(SUM(balance), 0) FROM accounts
		      WHERE customer_id = (SELECT customer_id FROM accounts WHERE id = ?)`
		if os.Getenv("DB_DRIVER") == "pgx" {
			q = `SELECT COALESCE(SUM(balance), 0) FROM accounts
			     WHERE customer_id = (SELECT customer_id FROM accounts WHERE id = $1)`
		}
		if err := tx.QueryRowContext(ctx, q, from).Scan(&total); err != nil {
			return err
		}
		if total < cents {
			return errors.New("insufficient funds")
		}
		upd := `UPDATE accounts SET balance = balance + ? WHERE id = ?`
		if os.Getenv("DB_DRIVER") == "pgx" {
			upd = `UPDATE accounts SET balance = balance + $1 WHERE id = $2`
		}
		if _, err := tx.ExecContext(ctx, upd, -cents, from); err != nil {
			return err
		}
		_, err := tx.ExecContext(ctx, upd, cents, to)
		return err
	})
}

func main() {
	driver, dsn := os.Getenv("DB_DRIVER"), os.Getenv("DATABASE_URL")
	if driver == "" || dsn == "" {
		log.Println("set DB_DRIVER (pgx|mysql) and DATABASE_URL to run the demo")
		return
	}
	db, err := sql.Open(driver, dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := transfer(ctx, db, 1, 2, 100_00); err != nil {
		log.Fatal(err)
	}
	fmt.Println("transfer committed")
}

Laravel: DB::transaction attempts, and its three limitations ​

DB::transaction($callback, attempts: 5) re-runs the closure when Laravel's ConcurrencyErrorDetector recognises the exception: SQLSTATE 40001 (PostgreSQL serialization failures and MySQL 1213, whose SQLSTATE is 40001) or a message such as "deadlock detected" (PostgreSQL 40P01), "Deadlock found when trying to get lock" or "Lock wait timeout exceeded; try restarting transaction" (MySQL 1205). The docs describe the argument as "the number of times a transaction should be retried when a deadlock occurs". Read Illuminate\Database\Concerns\ManagesTransactions and you find three limitations:

  1. No delay between attempts. The loop continues straight into the next beginTransaction(), so colliding requests retry in lockstep. There is no backoff or jitter.
  2. No retry inside a nested transaction. If the closure runs while another transaction is open (transactions > 1), Laravel rolls back to the savepoint and throws DeadlockException instead of retrying, because the outer transaction is already lost. Retries only happen at the outermost DB::transaction.
  3. No isolation level, and side effects re-run. There is no isolation: parameter: on PostgreSQL you must issue SET TRANSACTION as the first statement inside the closure, while on MySQL that statement fails inside a transaction (ERROR 1568) and must run before beginTransaction(). And everything in the closure runs again on retry; dispatch jobs with ->afterCommit() (or after_commit => true on the queue connection) and use DB::afterCommit(fn () => ...) for other side effects.

The runner below fixes all three: backoff with jitter, refuses to run nested, sets the level the right way per driver, and also retries a failing COMMIT (which throws a raw PDOException).

php
<?php

// app/Support/TransactionRunner.php: run a closure in a transaction at a chosen
// isolation level, retrying the whole closure with exponential backoff and
// jitter on serialization failures, deadlocks and lock wait timeouts.
// DB::transaction($cb, attempts: n) already retries, but immediately, only at
// the outermost level, and without a way to set the isolation level per attempt.
namespace App\Support;

use Closure;
use Illuminate\Database\Connection;
use Illuminate\Support\Facades\DB;
use LogicException;
use PDOException;
use Throwable;

final class TransactionRunner
{
    public function __construct(
        private readonly int $maxAttempts = 5,
        private readonly int $baseDelayMs = 10,
        private readonly int $maxDelayMs = 500,
    ) {}

    /**
     * @template T
     *
     * @param  Closure(Connection): T  $work  Database work only. No mail, HTTP or
     *                                         job dispatch: it may run more than once.
     *                                         Use DB::afterCommit() for side effects.
     * @return T
     */
    public function run(Closure $work, string $level = 'SERIALIZABLE', ?string $connection = null): mixed
    {
        $level = strtoupper($level);
        if (! in_array($level, ['READ COMMITTED', 'REPEATABLE READ', 'SERIALIZABLE'], true)) {
            throw new LogicException("Unsupported isolation level: {$level}");
        }

        /** @var Connection $db */
        $db = DB::connection($connection);

        if ($db->transactionLevel() > 0) {
            // A retry inside an outer transaction cannot work: the outer one is
            // already doomed (PostgreSQL) or already rolled back (MySQL deadlock).
            throw new LogicException('TransactionRunner must own the outermost transaction.');
        }

        for ($attempt = 1; ; $attempt++) {
            try {
                return $this->once($db, $work, $level);
            } catch (PDOException $e) {
                // Statement errors arrive as QueryException (a PDOException
                // subclass); a failing COMMIT throws the raw PDOException.
                if ($attempt >= $this->maxAttempts || ! $this->retryable($e)) {
                    throw $e;
                }
                $ceiling = min($this->maxDelayMs, $this->baseDelayMs * (2 ** $attempt));
                usleep(random_int(0, $ceiling) * 1000); // full jitter
            }
        }
    }

    private function once(Connection $db, Closure $work, string $level): mixed
    {
        $driver = $db->getDriverName();

        if ($driver === 'mysql' || $driver === 'mariadb') {
            // MySQL: SET TRANSACTION (no GLOBAL/SESSION) applies to the next
            // transaction only and is rejected inside one (ERROR 1568).
            $db->statement("SET TRANSACTION ISOLATION LEVEL {$level}");
        }

        $db->beginTransaction();

        try {
            if ($driver === 'pgsql') {
                // PostgreSQL: must run before the first query of the transaction.
                $db->statement("SET TRANSACTION ISOLATION LEVEL {$level}");
            }
            $result = $work($db);
            $db->commit(); // SSI may fail here with 40001: still retryable
        } catch (Throwable $e) {
            $db->rollBack();
            throw $e;
        }

        return $result;
    }

    private function retryable(PDOException $e): bool
    {
        $sqlState = (string) $e->getCode();          // e.g. 40001, 40P01, HY000
        $driverCode = (int) ($e->errorInfo[1] ?? 0); // MySQL: 1213, 1205

        return in_array($sqlState, ['40001', '40P01'], true)
            || in_array($driverCode, [1213, 1205], true);
    }
}
php
// Usage
$runner = new TransactionRunner(maxAttempts: 5);
$runner->run(function ($db) use ($from, $to, $cents) {
    $db->update('UPDATE accounts SET balance = balance - ? WHERE id = ?', [$cents, $from]);
    $db->update('UPDATE accounts SET balance = balance + ? WHERE id = ?', [$cents, $to]);
    DB::afterCommit(fn () => TransferCompleted::dispatch($from, $to, $cents));
}, level: 'SERIALIZABLE');

Choosing a level ​

Pick per operation, not per application. Most code stays at the engine default (Read Committed in PostgreSQL, Repeatable Read in InnoDB) and opts up where an invariant spans rows.

WorkloadRecommended levelExtra techniqueReason
CRUD web app, single-row editsDefault (RC in PostgreSQL, RR in InnoDB)Version column for edit formsConflicts are rare and row-local
Counters, stock, balances on one rowRead CommittedAtomic update with a guard (AND stock >= 1)One statement is always isolated with itself
Financial ledger, payments, walletsRead Committed + FOR UPDATE on the account, or Serializable + retryAppend-only ledger, CHECK (balance >= 0), idempotency keyOne anomaly costs far more than locks or retries
Multi-row rules (on-call, quotas, credit limits)Serializable + retry (PostgreSQL, CockroachDB)Or materialise the rule into one rowWrite skew is invisible at every snapshot level
Bookings, reservations, schedulesRead CommittedEXCLUDE USING gist (PostgreSQL) or slot table with unique key (MySQL)The constraint enforces it for every writer
Uniqueness (emails, coupons, idempotency)Read CommittedUnique constraint + ON CONFLICT DO NOTHING / INSERT IGNORECheck-then-insert is racy at every level except Serializable
Job queuesRead CommittedFOR UPDATE SKIP LOCKEDWorkers must not wait behind each other
Reports, exports, backupsRepeatable Read READ ONLY (PostgreSQL), consistent snapshot (InnoDB)SERIALIZABLE READ ONLY DEFERRABLE for period closes; pg_dump, mysqldump --single-transactionOne moment in time, no blocking
Analytics on a replicaRepeatable Read on the replicaAccept replica lagKeeps load off the primary
SQL Server with readers blocking writersRCSISNAPSHOT for multi-statement readsRemoves reader/writer blocking without NOLOCK
Porting an app between PostgreSQL and MySQLDo not rely on RR semanticsExplicit locks, atomic updates, constraintsRR means different things in the two engines

In architecture: from a single process to a distributed system ​

An isolation level is a promise about transactions inside one database (really one primary). As soon as data or decisions leave that transaction (to a cache, a replica, another service, a user's browser), no level protects you any more. The design question becomes: where are my transaction boundaries, and what do I use where there are none?

Monolith: one process, one database ​

How it shows up: every request is a transaction; the ORM opens it. The isolation bugs are the ones on this page: lost updates in $model->save(), check-then-insert on signup, write skew in scheduling.

Simplest correct usage: stay at the default level, push invariants into the database (atomic updates, unique and exclusion constraints, CHECK), use FOR UPDATE where logic must run between read and write, and wrap the few multi-row rules in Serializable + retry.

Example (simple): a shop's POST /orders does UPDATE products SET stock = stock - :qty WHERE id = :id AND stock >= :qty and an INSERT INTO orders in one transaction. No level change needed.

Example (complex): a clinic scheduler where “a doctor may not have overlapping appointments” and “at least two doctors per shift” both hold. The first is an exclusion constraint; the second is write skew, so the “leave shift” endpoint runs at Serializable through WithTx and the UI shows "try again" only if retries are exhausted.

The ORM hidden transaction boundary. ORMs blur where transactions start and end. Eloquent's save() outside DB::transaction is its own autocommit transaction, so find() then save() is two transactions with a gap between them: a lost update even at Serializable. Lazy loading inside a template runs queries after the transaction committed. Laravel's DB::transaction re-runs the closure on deadlock, so any Mail::send inside it is sent twice. Rule: make the transaction explicit around every read-decide-write, and move side effects to afterCommit.

Modular monolith and multiple databases ​

How it shows up: modules own their tables, possibly in separate schemas or separate databases. While modules share one database, a transaction can still span them, but that couples their schemas and their lock contention.

Example: Billing and Inventory in one PostgreSQL. A checkout that decrements stock and creates an invoice in one transaction is correct and simple. The moment Inventory moves to its own database, that transaction is gone: there is no isolation level that spans two databases without two-phase commit (XA), which most teams avoid.

Rules: keep each invariant inside one module's tables so it can be enforced by one local transaction; communicate across modules with events written in the same transaction as the change (the outbox); never read another module's tables inside your transaction and assume isolation will keep them still.

Microservices: sagas, outbox and no isolation ​

What survives: each service's local transaction, at whatever level that service chooses. What does not: isolation between steps of a business process. A saga is a sequence of local transactions with compensations; between steps, other requests see the intermediate state. In isolation terms, a saga runs at worse than Read Uncommitted: other transactions can read and act on state that will later be compensated (a dirty read), and two sagas can overwrite each other (a lost update).

text
Order service           Payment service           Inventory service
1  BEGIN; INSERT order(PENDING); INSERT outbox(OrderCreated); COMMIT
2                       consume OrderCreated
                        BEGIN; charge card; INSERT outbox(PaymentCaptured); COMMIT
3                                                 consume PaymentCaptured
                                                  BEGIN; UPDATE stock ... WHERE stock >= qty -> 0 rows; COMMIT
                                                  publish StockUnavailable
4                       consume StockUnavailable -> refund (compensation)
5  consume -> UPDATE order SET status = CANCELLED
   -- between 2 and 5 a "customer total spent" query saw a payment that is later refunded

Countermeasures (from the saga literature): a semantic lock (an application-level flag such as status = PENDING that other operations respect: “don't ship, don't count in reports while pending”); commutative updates (balance = balance + x instead of setting values); pessimistic view (order steps so the riskiest, least compensable happens last); re-reading values before acting; versioned entities; and an idempotency key on every consumer so redelivered messages do not apply twice. Each local step still needs the techniques on this page: the inventory step above is an atomic update. See Saga Pattern and Idempotent Consumers & the Inbox Pattern.

Distributed data: replicas, caches and distributed SQL ​

Read replicas and replica lag. A replica replays the primary's committed changes with a delay. A transaction on the replica sees a consistent (snapshot) but old state. Read-after-write breaks: a user saves a profile on the primary and the next page, read from a replica, shows the old one. Read-your-writes fixes: route a user's reads to the primary for a few seconds after they write; or remember the primary's WAL position / GTID of the write and wait until the replica has replayed it. Never do a read-decide-write where the read comes from a replica and the write goes to the primary: that is a lost update or write skew with a replication-lag-sized window. Details: Replication & Failover.

Cache in front of the database (cache lost update). The cache is outside every transaction. Classic race at any isolation level:

text
     Request A (reader)                    Request B (writer)
1    cache miss; SELECT price -> 10
2                                          UPDATE price = 12; COMMIT
3                                          DEL cache:price
4    SET cache:price = 10                  -- stale value written after the invalidation; lives until TTL

Mitigations: delete the key after commit (never inside the transaction), use short TTLs, write versioned cache values and refuse to overwrite a newer version (SET only if the stored version is older, via a Lua script or WATCH/MULTI/EXEC), or invalidate from the change stream (CDC). Redis transactions do not join database transactions; a Redis MULTI/EXEC/WATCH block is its own optimistic check-and-set on Redis keys only.

Distributed SQL. CockroachDB runs Serializable by default across nodes and asks clients to retry 40001; Spanner gives external consistency (strict serializability) using TrueTime; MongoDB multi-document transactions give snapshot reads, with the snapshot guarantee only if committed with write concern majority. Clocks and consensus make the strong levels possible, at a latency cost per transaction; Distributed SQL, Consensus & 2PC covers how.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesIsolation consequence
1× (one primary, modest traffic)Default level, constraints, a few FOR UPDATEs, Serializable for multi-row rulesRetries are rare; correctness is cheap
10× (hot rows, read replicas, connection pool)Hot counters become contention points; reports move to replicas; pools reuse connectionsReplace read-modify-write on hot rows with atomic updates or sharded counters; watch 40001 and deadlock rates; enforce idle_in_transaction_session_timeout; add read-your-writes routing
100× (sharding, multiple regions, services)Data split across databases; sagas between services; caches everywhereInvariants must be shard-local (choose shard keys so a rule's rows live together) or move to a distributed SQL engine; cross-shard rules become sagas with semantic locks and reconciliation jobs

At every step the same rule holds: keep each invariant inside one transaction on one database, and design what happens outside that boundary explicitly.

Lab ​

Two terminals per experiment. Expected output is in comments; error texts are the ones the PostgreSQL and MySQL manuals print.

Setup.

bash
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
docker run -d --name my -e MYSQL_ROOT_PASSWORD=my -e MYSQL_DATABASE=lab -p 3306:3306 mysql:8.4
# terminal A and B (PostgreSQL):  docker exec -it pg psql -U postgres
# terminal A and B (MySQL):       docker exec -it my mysql -uroot -pmy lab
sql
-- PostgreSQL
CREATE TABLE products (id int PRIMARY KEY, stock int NOT NULL);
INSERT INTO products VALUES (42, 1);
CREATE TABLE doctors (name text PRIMARY KEY, on_call bool NOT NULL);
INSERT INTO doctors VALUES ('Alice', true), ('Bob', true);
CREATE TABLE website (id int PRIMARY KEY, hits int NOT NULL);
INSERT INTO website VALUES (1, 9), (2, 10);
CREATE TABLE jobs (id int PRIMARY KEY, status text NOT NULL DEFAULT 'pending');
INSERT INTO jobs SELECT g, 'pending' FROM generate_series(1, 4) g;

-- MySQL
CREATE TABLE child (id int PRIMARY KEY, note varchar(20)) ENGINE=InnoDB;
INSERT INTO child VALUES (90, 'a'), (102, 'b');

Experiment 1: lost update at Read Committed, error at Repeatable Read (PostgreSQL).

text
     A                                                  B
1    BEGIN;                                             BEGIN;
2    SELECT stock FROM products WHERE id=42;  -- 1
3                                                       SELECT stock FROM products WHERE id=42;  -- 1
4    UPDATE products SET stock=0 WHERE id=42;
5                                                       UPDATE products SET stock=0 WHERE id=42;  -- blocks
6    COMMIT;                                            -- UPDATE 1 (lost update: two sales, one item)
7                                                       COMMIT;
-- Reset stock to 1 and repeat with BEGIN ISOLATION LEVEL REPEATABLE READ in both:
-- step 6 now makes B fail: ERROR:  could not serialize access due to concurrent update

Experiment 2: write skew at Repeatable Read, prevented at Serializable (PostgreSQL).

text
     A                                                  B
1    BEGIN ISOLATION LEVEL REPEATABLE READ;             BEGIN ISOLATION LEVEL REPEATABLE READ;
2    SELECT count(*) FROM doctors WHERE on_call;  -- 2  SELECT count(*) FROM doctors WHERE on_call;  -- 2
3    UPDATE doctors SET on_call=false WHERE name='Alice';
4                                                       UPDATE doctors SET on_call=false WHERE name='Bob';
5    COMMIT;                                            COMMIT;   -- both succeed; count is now 0
-- Reset both to true and repeat with SERIALIZABLE in both:
-- the second COMMIT fails:
-- ERROR:  could not serialize access due to read/write dependencies among transactions
-- In a third terminal during step 3, run: SELECT locktype, relation::regclass, mode FROM pg_locks WHERE mode = 'SIReadLock';

Experiment 3: the Read Committed re-check surprise (PostgreSQL).

text
     A                                                  B
1    BEGIN;
2    UPDATE website SET hits = hits + 1;   -- UPDATE 2
3                                                       DELETE FROM website WHERE hits = 10;   -- blocks
4    COMMIT;
5                                                       -- DELETE 0   (although a row with hits = 10 exists now and existed before)

Experiment 4: InnoDB's two kinds of read at REPEATABLE READ (MySQL).

text
     A                                                  B
1    START TRANSACTION;
2    SELECT * FROM child WHERE id > 100;   -- 102
3                                                       INSERT INTO child VALUES (101, 'new');  -- autocommit
4    SELECT * FROM child WHERE id > 100;              -- 102 (snapshot: no phantom)
5    SELECT * FROM child WHERE id > 100 FOR UPDATE;   -- 101, 102 (latest committed: phantom appears)
6    UPDATE child SET note = 'x' WHERE id > 100;      -- Rows matched: 2
7    SELECT * FROM child WHERE id > 100;              -- 101, 102 (the row you updated is now in your snapshot)
8    COMMIT;

Experiment 5: gap locks block inserts at REPEATABLE READ but not at READ COMMITTED (MySQL).

text
     A                                                  B
1    START TRANSACTION;
2    SELECT * FROM child WHERE id > 100 FOR UPDATE;
3                                                       INSERT INTO child VALUES (150, 'gap');
                                                        -- blocks; after innodb_lock_wait_timeout seconds:
                                                        -- ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
4    ROLLBACK;
-- Repeat with SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED in A and id 160 in B: step 3 succeeds immediately.
-- While B waits, SELECT * FROM performance_schema.data_locks shows A's X locks (record and gap) and B's insert intention lock.

Experiment 6: two workers, SKIP LOCKED (PostgreSQL).

text
     A                                                  B
1    BEGIN;                                             BEGIN;
2    SELECT id FROM jobs WHERE status='pending'
      ORDER BY id LIMIT 2 FOR UPDATE SKIP LOCKED;  -- 1, 2
3                                                       SELECT id FROM jobs WHERE status='pending'
                                                         ORDER BY id LIMIT 2 FOR UPDATE SKIP LOCKED;  -- 3, 4 (no wait)
4                                                       -- with NOWAIT instead of SKIP LOCKED: an error with SQLSTATE 55P03 (lock_not_available)
5    COMMIT;                                            COMMIT;

Common misconceptions ​

BeliefReality
“A transaction protects my read-modify-write.”Atomicity is not isolation. At PostgreSQL Read Committed and InnoDB Repeatable Read, SELECT then UPDATE loses updates.
“Repeatable Read means no anomalies.”PostgreSQL RR permits write skew; InnoDB RR permits lost update; SQL Server RR permits phantoms.
“The same level name behaves the same in every database.”Oracle SERIALIZABLE is Snapshot Isolation; PostgreSQL RR is SI; InnoDB RR is snapshot reads + locking writes.
“Read Uncommitted in PostgreSQL gives dirty reads or speed.”It is silently Read Committed.
“Serializable always blocks.”PostgreSQL SSI adds no blocking (except DEFERRABLE read-only at start); it aborts instead.
“Serializable makes my app slow.”Short, indexed transactions at Serializable usually cost a few percent in retries; long scans and hot rows cost more. Measure.
“Snapshot Isolation is serializable.”It prevents every ANSI phenomenon and still permits write skew and the read-only anomaly.
“FOR UPDATE prevents phantoms.”Only in InnoDB (next-key locks) at RR/Serializable. In PostgreSQL it locks existing rows only.
“Retry the failed statement.”After 40001 or 1213 the transaction is gone; retry from BEGIN. MySQL 1205 rolled back only the statement, so roll back yourself first.
“NOLOCK is a free performance hint.”It is Read Uncommitted: you can read rolled-back data. Use RCSI.
“Read-only transactions cannot be wrong.”They can see the read-only transaction anomaly under Snapshot Isolation; use SERIALIZABLE READ ONLY DEFERRABLE.
“Unique checks in code are enough.”Check-then-insert races at every level below Serializable; only a unique or exclusion constraint is airtight.
“My cache is consistent because my database is Serializable.”The cache is outside the transaction; the cache lost update happens at any level.
“Microservices can share isolation through a saga.”Sagas have no isolation between steps; use semantic locks, commutative updates and idempotency keys.
“Higher isolation fixes replica-lag bugs.”Replica lag is outside the transaction; you need read-your-writes routing.

Cheat sheet ​

TopicWhat to remember
DefaultsPostgreSQL RC, InnoDB RR, SQL Server RC (locking; RCSI on Azure SQL Database), Oracle RC, CockroachDB Serializable, SQLite Serializable, Spanner Serializable (external consistency)
Dirty write / dirty readP0 never allowed; P1 only at InnoDB/SQL Server Read Uncommitted or NOLOCK
Lost updateAtomic update > FOR UPDATE > version column > PostgreSQL RR/Serializable + retry; InnoDB RR does not help
Write skewOnly Serializable (PostgreSQL SSI, CockroachDB, InnoDB/SQL Server 2PL) stops it; or lock the rule's rows, or materialise the conflict
PhantomsSnapshot for re-reads; next-key locks in InnoDB; constraints for check-then-insert
PostgreSQL RCNew snapshot per statement; writers re-check the new row version (website/hits surprise)
InnoDB RRPlain reads = snapshot of first read; locking reads and DML = latest committed + next-key locks
Errors to retry40001, 40P01, 1213, 1205 (after rollback), Msg 3960, ORA-08177, TransientTransactionError
Errors not to retry23505, 23P01, 1062: the constraint answered
Retry wrapperWhole transaction, bounded, retry with jitter, side effects after commit, classify COMMIT too, outermost only
ReportsREPEATABLE READ READ ONLY; period closes with SERIALIZABLE READ ONLY DEFERRABLE; pg_dump, mysqldump --single-transaction
Job queuesFOR UPDATE SKIP LOCKED; NOWAIT to fail fast
BookingsEXCLUDE USING gist (room_id WITH =, during WITH &&) with btree_gist
Long transactionsBloat and dead tuples (PostgreSQL), history list length (InnoDB), version store (SQL Server), snapshot too old (Oracle); set idle_in_transaction_session_timeout
Setting the levelPostgreSQL: first statement or BEGIN ISOLATION LEVEL; MySQL: before START TRANSACTION (ERROR 1568 inside)
Outside one databaseReplicas, caches, sagas: no isolation; use read-your-writes, versioned cache writes, semantic locks, idempotency keys

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — At PostgreSQL Read Committed, a transaction runs the same SELECT twice and gets different rows or values. Why, and what is it called? Must-know ​

Answer

Answer: Each statement takes a fresh snapshot, so a commit between the two statements becomes visible. This is a non-repeatable read (P2), or a phantom (P3) when the set of rows changes. See Read Committed and Non-repeatable read.

2 — What does PostgreSQL Repeatable Read really implement, and which anomaly can still happen? Important ​

Answer

Answer: Snapshot Isolation: one snapshot at the first statement. It prevents dirty, non-repeatable and phantom reads, but write skew is still possible. See Repeatable Read and Write skew.

3 — Two sessions run SELECT balance then UPDATE ... SET balance = :new inside transactions at Read Committed. What goes wrong, and name two fixes. Must-know ​

Answer

Answer: A lost update: the second write overwrites the first because a plain SELECT takes no lock. Fix it with an atomic SET balance = balance - x, SELECT ... FOR UPDATE, or a version column. See Lost update and its solutions.

4 — What is a rw-dependency, and what is the pivot in an SSI dangerous structure? Good to know ​

Answer

Answer: T1 -> T2 means T1 read a version that T2's write replaced. In T1 -> T2 -> T3 the middle transaction T2 is the pivot (one edge in, one edge out). SSI aborts one transaction with 40001. See SSI.

5 — When is the snapshot taken in InnoDB Repeatable Read compared with PostgreSQL? Important ​

Answer

Answer: InnoDB takes it at the first consistent read (or at START TRANSACTION WITH CONSISTENT SNAPSHOT); PostgreSQL takes it at the first statement. Read Committed takes one per statement in both. See MVCC snapshots.

6 — Which error code must your retry loop catch in PostgreSQL, and which two in InnoDB? Important ​

Answer

Answer: PostgreSQL: 40001 (serialization failure) and 40P01 (deadlock). InnoDB: 1213 (deadlock) and 1205 (lock wait timeout). See Error codes and Retries.

7 — Why does a row lock on the rows you read not stop a phantom? Important ​

Answer

Answer: Row locks cover rows that already exist; a phantom is a new row. You need a predicate lock, a gap or next-key lock, or a snapshot. See Phantom read and InnoDB locks.

8 — Is Read Uncommitted in PostgreSQL faster because it allows dirty reads? Must-know ​

Answer

Answer: No. PostgreSQL accepts the name and runs Read Committed. No engine allows dirty writes at any level. See Dirty write and Setting the level.

9 — Does Serializable mean transactions ran one after another? Must-know ​

Answer

Answer: No. It means the outcome equals some serial order, and engines get there by locks or by SSI-style aborts. See Serial vs serializable.

10 — Does an isolation level protect a workflow that spans a cache, a replica and another service? Must-know ​

Answer

Answer: No. The level is a promise about transactions inside one database primary; beyond that you need sagas, outbox and idempotency. See In architecture.

Glossary ​

TermMeaning
Non-repeatable read (fuzzy read)The ANSI name and the Critique's name for P2, used interchangeably
First-updater-wins / first-committer-winsThe two SI write-conflict rules: detect at the second write (engines) or at commit (the Critique)
Version store/tempdbWhere SQL Server keeps row versions: tempdb by default, the user database with ADR
Saga semantic lockA status flag such as PENDING that tells other operations a saga is still in flight
DB::transaction attemptsLaravel's retry count argument; retries immediately and only at the outermost level
MySQL 1213ER_LOCK_DEADLOCK, SQLSTATE 40001; the whole transaction was rolled back
MongoDB snapshot read concern / WriteConflictMongoDB transactions read a majority-committed snapshot and abort with WriteConflict on concurrent writes
CockroachDB Serializable defaultCockroachDB runs Serializable unless Read Committed is enabled and requested
Spanner external consistencySpanner's default: serializable and consistent with real-time order (TrueTime)
Redis MULTI/EXEC/WATCHRedis queues commands with MULTI, runs them atomically with EXEC, and aborts EXEC if a WATCHed key changed
ANSI SQL-92The SQL standard that named Read Uncommitted, Read Committed, Repeatable Read and Serializable by forbidden phenomena
Berenson et al. (Critique)The 1995 paper that added P0, P4, P4C, A5A, A5B, Cursor Stability and Snapshot Isolation to the vocabulary
Isolation levelThe contract about which anomalies concurrent transactions may observe
Anomaly / phenomenonAn interleaving whose result differs from every serial order
P0Dirty write: overwriting another transaction's uncommitted write
Dirty writeSee P0; prevented by every engine at every level
Dirty read (P1)Reading another transaction's uncommitted write
Non-repeatable readP2: re-reading a row returns a different committed value
Fuzzy readAnother name for non-repeatable read (P2)
Phantom read (P3)Re-running a predicate query returns a different set of rows
Lost update (P4)A read-modify-write overwrites a concurrent committed update
Cursor lost update (P4C)Lost update through a cursor's current row; prevented by Cursor Stability
Cursor StabilityRead Committed plus a lock on the cursor's current row
Read skew (A5A)Reading related items from different moments
Write skew (A5B)Two transactions read overlapping data, write disjoint rows, and jointly break an invariant
Serialization anomalyAny committed result inconsistent with every serial order
Read-only transaction anomalyUnder SI, a read-only transaction observes a state no serial order produces (Fekete et al.)
FeketeCo-author of the read-only anomaly result and of the SSI design
Serial vs serializableSerial = literally one at a time; serializable = equivalent to some serial order
Read UncommittedLevel allowing dirty reads (real in InnoDB/SQL Server, mapped to RC in PostgreSQL)
Read CommittedEach statement sees data committed before it began
Repeatable ReadRows read stay stable; meaning varies by engine (SI in PostgreSQL, snapshot + locks in InnoDB, locks in SQL Server)
Snapshot IsolationTransaction reads one snapshot; write-write conflicts abort one writer; permits write skew
SerializableResult equals some serial order (2PL, SSI or actual serial execution)
Strict SerializableSerializable and consistent with real-time order
Linearizability vs isolationLinearizability: single-object recency in real time; isolation: multi-object transaction interleaving
External consistencySpanner's name for strict serializability
TrueTimeSpanner's clock API with bounded uncertainty used to order commits
First-updater-winsThe second writer of a row waits, then aborts if the first committed (PostgreSQL RR, Oracle, SQL Server SNAPSHOT)
First-committer-winsThe Critique's SI rule: of two concurrent writers of an item, only the first to commit succeeds
could not serialize accessPostgreSQL's message text for SQLSTATE 40001
SQLSTATE 40001serialization_failure: retry the transaction (also MySQL 1213's SQLSTATE)
serialization_failurePostgreSQL condition name for 40001
40P01PostgreSQL deadlock_detected
deadlock_detectedPostgreSQL condition name for 40P01
1213MySQL ER_LOCK_DEADLOCK; transaction rolled back
1205MySQL ER_LOCK_WAIT_TIMEOUT; statement rolled back
1062MySQL ER_DUP_ENTRY; unique key violation
23505PostgreSQL unique_violation
23P01PostgreSQL exclusion_violation
55P03PostgreSQL lock_not_available (e.g. NOWAIT)
ERROR 1568MySQL: transaction characteristics cannot change inside a transaction
Msg 3960SQL Server snapshot isolation update conflict
ORA-08177Oracle: cannot serialize access for this transaction
SSISerializable Snapshot Isolation: SI plus detection of dangerous rw-dependency structures (PostgreSQL, CockroachDB-style)
SIReadLockPostgreSQL's non-blocking predicate lock recording what a serializable transaction read
rw-dependencyT1 read a version T2's write replaced; T1 must precede T2
Dangerous structureTwo adjacent rw-dependencies T1 → T2 → T3; SSI aborts one transaction when it appears
PivotThe middle transaction of a dangerous structure
Predicate lockA lock on all rows matching a condition, including future ones
max_pred_locks_per_transactionPostgreSQL memory knob for predicate locks; too low causes escalation and more 40001
pg_locksPostgreSQL view of current locks, including SIReadLock
2PLTwo-phase locking: acquire, then release, never acquire after releasing
Strict 2PL2PL that holds write locks until commit/abort
Record lockInnoDB lock on one index record
Gap lockInnoDB lock on the gap between index records; only blocks inserts
Next-key lockInnoDB record lock + gap lock before it; prevents phantoms
Insert intention lockInnoDB gap-level lock taken by INSERT before inserting a row
Semi-consistent readInnoDB RC: an UPDATE reads the latest committed version of a locked row to test its WHERE
Consistent nonlocking readInnoDB plain SELECT from a snapshot
Locking readSELECT ... FOR UPDATE / FOR SHARE: reads latest committed rows and locks them
FOR UPDATEExclusive row lock on selected rows
FOR NO KEY UPDATEPostgreSQL's weaker update lock that does not block foreign-key FOR KEY SHARE
FOR SHAREShared row lock: others may read and share-lock, not modify
NOWAITFail immediately instead of waiting for a row lock
SKIP LOCKEDSkip rows that are locked; for queues
READ ONLYTransaction access mode forbidding writes (PostgreSQL 25006 if violated)
DEFERRABLEPostgreSQL: a SERIALIZABLE READ ONLY transaction waits for a safe snapshot and cannot fail
START TRANSACTION WITH CONSISTENT SNAPSHOTMySQL: take the InnoDB RR snapshot immediately
default_transaction_isolationPostgreSQL / CockroachDB setting for new transactions' level
transaction_isolationPostgreSQL parameter showing the current level; MySQL system variable for the level
idle_in_transaction_session_timeoutPostgreSQL: kill sessions idle inside an open transaction
transaction_timeoutPostgreSQL: limit total transaction duration
innodb_lock_wait_timeoutMySQL seconds to wait for a row lock before error 1205
RCSISQL Server Read Committed Snapshot Isolation (READ_COMMITTED_SNAPSHOT ON)
READ_COMMITTED_SNAPSHOTSQL Server database option that turns RC into statement-level row versioning
ALLOW_SNAPSHOT_ISOLATIONSQL Server database option required before using SNAPSHOT
READCOMMITTEDLOCKSQL Server table hint forcing locking RC under RCSI
NOLOCKSQL Server table hint equal to Read Uncommitted
Version storeSQL Server storage of row versions for RCSI/SNAPSHOT
tempdbSQL Server system database that hosts the version store unless ADR is on
Undo logInnoDB/Oracle record of previous row versions used for rollback and consistent reads
History list lengthInnoDB count of undo log pages not yet purged; grows with long transactions
Snapshot too oldOracle error when undo needed for a consistent read was overwritten
Dead tuplesPostgreSQL row versions no longer visible to anyone, waiting for VACUUM
VACUUMPostgreSQL process that reclaims dead tuples
BloatSpace wasted by dead tuples or versions that cannot be reclaimed yet
SQLite WAL modeJournal mode where readers see a snapshot while one writer appends
SQLITE_BUSY_SNAPSHOTSQLite error when a reader with a stale snapshot tries to write
Snapshot read concernMongoDB read concern giving a transaction a majority-committed point-in-time snapshot
WriteConflictMongoDB error when a transaction writes a document modified concurrently
TransientTransactionErrorMongoDB error label meaning the whole transaction may be retried
transactionLifetimeLimitSecondsMongoDB limit on a transaction's runtime
CockroachDBDistributed SQL database, Serializable by default, retry on 40001
SpannerGoogle's distributed database with external consistency
MULTI/EXEC/WATCHRedis transaction commands: queue, execute atomically, abort if a watched key changed
Compare-and-setWrite only if the value is still what you read (Redis WATCH, version columns)
Atomic updateA single statement that reads and writes (SET x = x - 1 WHERE x >= 1)
Version column (optimistic)A counter checked in WHERE and incremented on every update
OptimisticDetect conflicts at write time instead of locking
Unique constraintIndex-enforced uniqueness; the reliable fix for check-then-insert
ON CONFLICT DO NOTHINGPostgreSQL insert that skips rows violating a unique/exclusion constraint
INSERT IGNOREMySQL insert that ignores ignorable errors such as duplicate keys
EXCLUDE USING gistPostgreSQL exclusion constraint, e.g. no overlapping ranges per room
btree_gistPostgreSQL extension that lets GiST exclusion constraints use scalar =
Materializing the conflictTurning a multi-row rule into a row (or constraint) every writer must update
pg_advisory_xact_lockPostgreSQL application-defined lock held until transaction end
pg_dumpPostgreSQL logical backup; runs in one snapshot, --serializable-deferrable for a safe one
mysqldump --single-transactionConsistent InnoDB dump using one RR snapshot
Replica lagDelay between a commit on the primary and its replay on a replica
Read-your-writesGuarantee that a client sees its own writes in later reads
Cache lost updateA stale value written to a cache after a newer value invalidated it
SagaA sequence of local transactions with compensations; no isolation between steps
Semantic lockAn application-level flag (e.g. PENDING) that other operations respect during a saga
OutboxA table written in the same transaction as the change, relayed to a broker later
Idempotency keyA unique key that makes a repeated request or message apply once
ORM hidden transaction boundaryWhere an ORM silently opens/commits transactions (autocommit save(), lazy loads)
DB::transactionLaravel's closure-based transaction with optional attempts
attemptsDB::transaction argument: total tries on deadlock/serialization errors
afterCommitLaravel DB::afterCommit() / job ->afterCommit(): run after the outer transaction commits
lockForUpdateLaravel query builder FOR UPDATE
lockForNoKeyUpdateLaravel query builder FOR NO KEY UPDATE (PostgreSQL)
sharedLockLaravel query builder FOR SHARE / LOCK IN SHARE MODE
sql.TxOptionsGo database/sql struct with Isolation and ReadOnly for BeginTx
Retry with jitterExponential backoff with randomised delay to avoid synchronized retries

References ​

Built by Morteza Negahi