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 for | Go to |
|---|---|
| A table you can memorise in one minute | Everything in one minute |
| Why levels exist at all, and the trade-off | Why isolation levels exist |
| ANSI SQL-92, Berenson 1995, serial vs serializable, linearizability | Where the vocabulary comes from |
| One anomaly with a two-session timeline | The anomalies, one by one |
| What a level promises and its surprises (PostgreSQL re-check, InnoDB phantoms) | The levels, one by one |
| Level × anomaly × engine matrices | Per-engine behaviour |
| PostgreSQL, InnoDB, SQL Server, Oracle, SQLite, MongoDB, CockroachDB, Spanner, Redis | What each database really does |
| 2PL, gap locks, snapshots, SSI, bloat, knobs, error codes | Mechanics |
| SQL + Go + Laravel for lost update, write skew, check-then-insert, double booking, reports, job queues | Solving the classic problems |
| Retry wrapper in Go and Laravel | Retries and failure handling |
| Which level for which workload | Choosing a level |
| Replicas, caches, sagas, distributed SQL | In architecture |
| Reproduce everything in two terminals | Lab |
| Wrong beliefs, a cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The anomalies. Every row is unpacked in the anomalies section.
| Anomaly (paper code) | In plain words | Tiny example | What stops it |
|---|---|---|---|
| Dirty write (P0) | You overwrite someone's uncommitted write | T1 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 write | Balance shows a deposit that is then rolled back | Read Committed and above |
| Non-repeatable read / fuzzy read (P2) | Same row, read twice, two values | Price 10, then 12, in one checkout | Repeatable Read, Snapshot Isolation |
| Phantom read (P3) | Same WHERE, run twice, new rows appear | COUNT(*) of bookings changes mid-transaction | Snapshot (for plain reads), InnoDB next-key locks, Serializable |
| Lost update (P4) | Two read-modify-writes, one silently vanishes | Two orders both see stock 1, both write 0 | Atomic update, FOR UPDATE, version column, PostgreSQL Repeatable Read |
| Cursor lost update (P4C) | Lost update through a cursor's current row | Fetch row, other session updates it, you update it | Cursor Stability |
| Read skew (A5A) | You read two related things from two different moments | Transfer between accounts seen half-done | Snapshot Isolation, Repeatable Read |
| Write skew (A5B) | Two transactions check the same rule, write different rows, rule breaks | Two doctors both go off call | Serializable, or lock/materialise the rule |
| Read-only transaction anomaly | A pure reader sees a state no serial order could produce | Report shows a closed batch, then a receipt lands in it | PostgreSQL Serializable (SSI), DEFERRABLE |
The levels.
| Level | Promise | Tiny example of what is still allowed | Typical engines and defaults |
|---|---|---|---|
| Read Uncommitted | No dirty writes | Dirty reads | InnoDB (real), PostgreSQL (silently Read Committed) |
| Read Committed | Only committed data, per statement | Non-repeatable read, phantom, lost update, write skew | Default in PostgreSQL, SQL Server, Oracle; CockroachDB option |
| Repeatable Read | Rows you read do not change | Depends on engine: write skew (PostgreSQL), lost update (InnoDB) | Default in MySQL InnoDB |
| Snapshot Isolation | Whole transaction reads one snapshot; first-committer-wins on writes | Write skew | SQL Server SNAPSHOT; PostgreSQL Repeatable Read; SQLite WAL readers |
| Serializable | Result equals some serial order | Nothing (but you get aborts or waits) | PostgreSQL SSI, InnoDB 2PL, CockroachDB default, Oracle "serializable" is really SI |
| Strict Serializable | Serializable + respects real time | Nothing, including stale reads across clients | Spanner (external consistency), single-node serializable engines |
The three things to do.
| Situation | Do this |
|---|---|
| Changing one counter or balance | One UPDATE ... SET x = x - 1 WHERE ... AND x >= 1 (atomic update) at Read Committed |
| Enforcing a rule across rows | Lock what the rule reads (FOR UPDATE), materialise it into a row or constraint, or run Serializable with retry |
| Any level above Read Committed | Retry 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 aborts | Serialization failures you must retry |
| You reason about every interleaving yourself | You reason about each transaction alone |
| Bugs show up as wrong data, silently | Bugs show up as errors, loudly |
| Cheap long reads | Long 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
- “I am in a transaction, so nobody can change what I read.” A plain
SELECTtakes 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. - “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
SERIALIZABLEpermits write skew. Always name the product with the level. - “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 DEFERRABLEtransaction 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.
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-definedReal 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.
| Engine | Dirty write possible? |
|---|---|
| PostgreSQL, MySQL InnoDB, SQL Server, Oracle, SQLite, CockroachDB | No, at every level: second writer waits (or is aborted) |
| MongoDB multi-document transaction | No: 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."
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 againReal 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 level | Dirty read? |
|---|---|
| PostgreSQL, any level (Read Uncommitted is mapped to Read Committed) | Never |
MySQL InnoDB READ UNCOMMITTED | Yes, real dirty reads |
SQL Server READ UNCOMMITTED or WITH (NOLOCK) | Yes |
| Oracle, CockroachDB, Spanner | No such level; never |
SQLite with shared cache and PRAGMA read_uncommitted | Yes, 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."
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 level | Non-repeatable read? |
|---|---|
PostgreSQL Read Committed, InnoDB READ COMMITTED, SQL Server RC/RCSI, Oracle Read Committed, CockroachDB Read Committed | Yes |
PostgreSQL Repeatable Read, InnoDB REPEATABLE READ (plain reads), SQL Server REPEATABLE READ/SNAPSHOT, Oracle SERIALIZABLE | No |
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.
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 <- phantomReal 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 level | Phantom on re-read? |
|---|---|
| PostgreSQL Read Committed | Yes |
| PostgreSQL Repeatable Read | No (snapshot); the manual marks it "Allowed, but not in PG" |
InnoDB REPEATABLE READ, plain SELECT | No (snapshot of the first read) |
InnoDB REPEATABLE READ, locking reads / UPDATE / DELETE | Prevented by next-key locks, but DML sees the latest committed rows (see InnoDB's phantom exception) |
InnoDB READ COMMITTED | Yes: gap locking is off |
SQL Server REPEATABLE READ | Yes (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.
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 existedThe 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 level | Lost update? |
|---|---|
| PostgreSQL Read Committed | Yes |
| PostgreSQL Repeatable Read / Serializable | No: 40001 for the second writer |
InnoDB READ COMMITTED and REPEATABLE READ | Yes (no write-conflict check) |
InnoDB SERIALIZABLE | No: the plain SELECT becomes FOR SHARE, both hold S locks, upgrade deadlocks, one gets 1213 |
SQL Server READ COMMITTED / RCSI | Yes |
SQL Server REPEATABLE READ | No: S locks held, second writer deadlocks |
SQL Server SNAPSHOT | No: Msg 3960 update conflict |
Oracle Read Committed / SERIALIZABLE | Yes / 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.
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 1000Real 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 level | Read 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 ONLY | No: 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.
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 callAt 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 level | Write skew? |
|---|---|
| PostgreSQL Read Committed / Repeatable Read | Yes |
| PostgreSQL Serializable (SSI) | No: 40001 |
InnoDB READ COMMITTED / REPEATABLE READ (plain reads) | Yes |
InnoDB SERIALIZABLE | No: S locks + next-key locks; one transaction deadlocks (1213) |
SQL Server SNAPSHOT / RCSI | Yes |
SQL Server SERIALIZABLE | No (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.
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 wrongReal scenarios: end-of-day reports, ledger closes, invoices generated for a period that a late write still lands in.
| Engine and level | Possible? |
|---|---|
Snapshot Isolation anywhere (PostgreSQL Repeatable Read, SQL Server SNAPSHOT, Oracle SERIALIZABLE) | Yes |
| PostgreSQL Serializable | No: SSI aborts one of the writers, or the report |
PostgreSQL SERIALIZABLE READ ONLY DEFERRABLE | No, 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.
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 40001Real 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:
| Engine | Mechanism |
|---|---|
| PostgreSQL | New snapshot per statement; writers re-check rows changed by concurrent commits (see below) |
| Oracle | Statement-level read consistency rebuilt from undo data |
InnoDB READ COMMITTED | Fresh 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 COMMITTED | Per-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.
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:
| Engine | What REPEATABLE READ really is |
|---|---|
| PostgreSQL | Snapshot 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 Server | Lock-based: shared locks on read rows held to commit. Prevents lost update (by deadlock) and fuzzy reads; phantoms allowed. |
| CockroachDB | Not offered (Serializable and Read Committed only) |
| Oracle | Not 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:
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 snapshotAnd 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:
| Implementation | Products | How conflicts show up |
|---|---|---|
| Strict two-phase locking (2PL) with predicate/range locks | InnoDB (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 execution | SQLite (one writer at a time), Redis (MULTI/EXEC) | Waiting for the single writer (SQLITE_BUSY) |
Snapshot Isolation labelled SERIALIZABLE | Oracle | ORA-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.
| Level | P1 Dirty read | P2 Fuzzy read | P3 Phantom |
|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible |
| READ COMMITTED | Not possible | Possible | Possible |
| REPEATABLE READ | Not possible | Not possible | Possible |
| SERIALIZABLE | Not possible | Not possible | Not possible |
Matrix 2: the Critique paper (Berenson et al. 1995, Table 4)
| Level | P0 Dirty write | P1 Dirty read | P4C Cursor lost update | P4 Lost update | P2 Fuzzy read | P3 Phantom | A5A Read skew | A5B Write skew |
|---|---|---|---|---|---|---|---|---|
| READ UNCOMMITTED (Degree 1) | Not possible | Possible | Possible | Possible | Possible | Possible | Possible | Possible |
| READ COMMITTED (Degree 2) | Not possible | Not possible | Possible | Possible | Possible | Possible | Possible | Possible |
| Cursor Stability | Not possible | Not possible | Not possible | Sometimes possible | Sometimes possible | Possible | Possible | Sometimes possible |
| REPEATABLE READ (locking) | Not possible | Not possible | Not possible | Not possible | Not possible | Possible | Not possible | Not possible |
| Snapshot | Not possible | Not possible | Not possible | Not possible | Not possible | Sometimes possible | Not possible | Possible |
| ANSI SERIALIZABLE (Degree 3) | Not possible | Not possible | Not possible | Not possible | Not possible | Not possible | Not possible | Not 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 / level | Dirty read | Non-repeatable | Phantom (re-read) | Lost update | Read skew | Write 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 |
What each database really does
| Product | Levels offered | Default | Implementation | Conflict signal | Watch out for |
|---|---|---|---|---|---|
| PostgreSQL | RU (= RC), RC, RR, Serializable | Read Committed | MVCC snapshots; RR = Snapshot Isolation; Serializable = SSI with SIReadLock predicate locks | 40001 serialization_failure, 40P01 deadlock_detected, 55P03 lock_not_available (NOWAIT) | RC re-check surprise; long transactions keep dead tuples alive and cause bloat |
| MySQL InnoDB | RU, RC, RR, Serializable | Repeatable Read | MVCC for plain reads (undo log); record, gap, next-key and insert intention locks for locking reads and DML; Serializable = plain SELECT becomes FOR SHARE | 1213 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 Server | RU, RC, RR, SNAPSHOT, Serializable; RC can be RCSI | Read 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 SNAPSHOT | Msg 3960 snapshot update conflict; deadlock victim | NOLOCK hints; ALLOW_SNAPSHOT_ISOLATION must be ON to use SNAPSHOT; version store growth |
| Oracle | Read Committed, Serializable, Read-Only | Read Committed | Multiversion read consistency from undo data; Serializable = Snapshot Isolation | ORA-08177 cannot serialize access | Write skew at SERIALIZABLE; snapshot too old on long reports when undo is overwritten |
| SQLite | Serializable (RU only with shared cache + PRAGMA read_uncommitted) | Serializable | Single writer at a time; in WAL mode readers see a snapshot | SQLITE_BUSY, SQLITE_BUSY_SNAPSHOT when a stale reader tries to write | Writers queue; upgrade from read to write fails in WAL mode |
| MongoDB | Read/write concerns per operation; multi-document transactions read with snapshot read concern | No SQL level; single-document writes are atomic | Snapshots of majority-committed data; write-write conflict detection | WriteConflict; 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) |
| CockroachDB | Serializable, Read Committed | Serializable | Distributed MVCC; a transaction that cannot be placed in a serializable order is restarted | 40001 with restart transaction | Clients must retry at Serializable; Read Committed is gated by sql.txn.read_committed_isolation.enabled |
| Spanner | Serializable (default), Repeatable Read | Serializable = external consistency | MVCC + TrueTime timestamps; snapshot and stale reads never block writes | Aborted read-write transactions must be retried | Strong reads cost more than stale reads; Repeatable Read gives up serializability |
| Redis | MULTI/EXEC (serial), WATCH (optimistic), Lua scripts / functions | n/a | Single-threaded command execution: a transaction runs as one step | EXEC returns null if a WATCHed key changed | No 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.
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
| Lock | Covers | Taken by | Blocks |
|---|---|---|---|
| Record lock | One index record | Locking reads, UPDATE, DELETE on a unique index hit | Other locks on that record |
| Gap lock | The open interval between two index records | Range scans at RR/Serializable | Inserts into the gap only; gap locks are "purely inhibitive" and do not conflict with each other |
| Next-key lock | Record + the gap before it | Default for index scans at RR/Serializable | Inserts into the gap and locks on the record |
| Insert intention lock | A point inside a gap, set by INSERT before the row is inserted | Every INSERT | Waits on gap/next-key locks; two inserts of different keys in the same gap do not block each other |
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 waitsAt 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:
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)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.
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 threeProperties 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:
| Engine | What piles up | Symptom | Knob / metric |
|---|---|---|---|
| PostgreSQL | Dead tuples that VACUUM cannot remove | Table and index bloat, slower scans, xid age growth | idle_in_transaction_session_timeout, transaction_timeout (SQLSTATE 25P03/25P04), pg_stat_activity.backend_xmin |
| MySQL InnoDB | Undo log records not purged | History list length grows; reads walk long version chains | SHOW ENGINE INNODB STATUS "History list length", innodb_purge_* |
| SQL Server | Row versions in the version store (tempdb, or the user database with ADR) | tempdb fills; with tempdb full, reads may fail for missing versions | Version store size DMVs |
| Oracle | Undo needed for consistent reads gets overwritten | snapshot too old error on long queries | Undo retention period |
| MongoDB | Snapshot history in the WiredTiger cache | Cache pressure; long transactions aborted | transactionLifetimeLimitSeconds |
Setting the level: every knob Must-know
-- 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
| Product | Code / message | Meaning | Retry the whole transaction? |
|---|---|---|---|
| PostgreSQL | 40001 serialization_failure: "could not serialize access due to concurrent update" | RR/Serializable write-write conflict | Yes |
| PostgreSQL | 40001: "could not serialize access due to read/write dependencies among transactions" | SSI found a dangerous structure | Yes |
| PostgreSQL | 40P01 deadlock_detected | Lock cycle; one transaction aborted | Yes |
| PostgreSQL | 55P03 lock_not_available | NOWAIT could not lock, or lock_timeout | Maybe (it is a policy decision) |
| PostgreSQL | 23505 unique_violation, 23P01 exclusion_violation | Constraint caught the race | No: report a business conflict (or upsert) |
| PostgreSQL | 25006 read_only_sql_transaction | Write inside READ ONLY | No: bug |
| MySQL | 1213 ER_LOCK_DEADLOCK, SQLSTATE 40001 | Deadlock; InnoDB rolled back the entire transaction | Yes |
| MySQL | 1205 ER_LOCK_WAIT_TIMEOUT, SQLSTATE HY000 | innodb_lock_wait_timeout exceeded; only the statement was rolled back | Yes, after rolling back the rest |
| MySQL | 1062 ER_DUP_ENTRY, SQLSTATE 23000 | Unique key caught the race | No: business conflict |
| MySQL | 1568 (25001) | SET TRANSACTION inside a transaction | No: bug |
| SQL Server | Msg 3960 | SNAPSHOT update conflict | Yes |
| Oracle | ORA-08177 | Cannot serialize access (SI conflict) | Yes |
| CockroachDB | 40001 "restart transaction" | Could not place the transaction in a serializable order | Yes |
| SQLite | SQLITE_BUSY, SQLITE_BUSY_SNAPSHOT | Another writer holds the lock / stale snapshot tried to write | Yes, from BEGIN |
| MongoDB | WriteConflict, label TransientTransactionError | Concurrent write to the same document | Yes (the callback API does it) |
| Redis | EXEC returns null | A WATCHed key changed | Yes: 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
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Atomic update | Compute in SQL: SET stock = stock - 1 WHERE stock >= 1 | No extra round trip, correct at Read Committed in every engine | Logic must fit in one statement; check affected rows |
| Pessimistic lock | SELECT ... FOR UPDATE, then update | Arbitrary application logic between read and write | Holds 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 requests | Caller must handle 0 rows updated (conflict) |
| Higher level | PostgreSQL Repeatable Read/Serializable, SQL Server SNAPSHOT, Oracle SERIALIZABLE | No code change to the logic | Must retry on 40001; InnoDB RR does not help |
-- 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// 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
}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.
// 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)
}// 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
// 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
// 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
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Serializable + retry | PostgreSQL SSI, CockroachDB default, InnoDB/SQL Server SERIALIZABLE | Fixes every write skew, including ones you did not foresee | Retries; on InnoDB/SQL Server more blocking and deadlocks |
| Lock what the rule reads | SELECT ... FOR UPDATE on all rows the check reads (or on a parent row) | Works at Read Committed | Must cover every row the rule depends on; cannot lock rows that do not exist yet |
| Materializing the conflict | Add a row that every participant must update (e.g. shifts(day) row, customers.credit_used) | Turns write skew into an ordinary write-write conflict | Schema change; a hot row under heavy concurrency |
| Advisory lock | pg_advisory_xact_lock(hashtext('oncall:' || team)) in PostgreSQL, GET_LOCK() in MySQL | No schema change | Every writer must remember to take it |
| Constraint | CHECK, unique, exclusion constraint, or a trigger | Enforced by the engine for every writer | Only for rules a constraint can express |
-- 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;// 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
})
}// 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.
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Unique constraint | UNIQUE (email), UNIQUE (order_id, coupon_id) | Correct at any level, in every engine | Catch 23505 / 1062 and turn it into a business answer |
| Insert-or-skip | PostgreSQL INSERT ... ON CONFLICT DO NOTHING, MySQL INSERT IGNORE | No exception path; RETURNING/affected rows tells you who won | MySQL INSERT IGNORE ignores every "ignorable" error, not only duplicates |
| Upsert | PostgreSQL ON CONFLICT DO UPDATE, MySQL ON DUPLICATE KEY UPDATE | One atomic statement | Only for “create or update” semantics |
| InnoDB next-key check | SELECT ... FOR SHARE then INSERT at RR | Works for non-unique predicates | Deadlock-prone when both insert; InnoDB only |
| Serializable | PostgreSQL SSI | Works for counts (at most 3 keys) | Retries; the manual notes you may still see a 23505 |
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// 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
}// 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.
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.
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
}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
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| One statement | Totals and details in one query (SUM ... GROUP BY, CTE) | Statement snapshot at any level | Not always possible |
| Snapshot, read-only | PostgreSQL REPEATABLE READ READ ONLY; MySQL START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY | Every query sees one moment; read-only transactions never get serialization errors in PostgreSQL RR | Long snapshot = bloat / history list length; can still show the read-only anomaly |
| Safe snapshot | PostgreSQL SERIALIZABLE READ ONLY DEFERRABLE | Consistent with every serial order and cannot be aborted | May wait at start until no conflicting writers are active |
| Dump tools | pg_dump (snapshot; --serializable-deferrable for the safe version), mysqldump --single-transaction | Consistent backup without blocking writers | mysqldump --single-transaction is consistent for InnoDB only, and must not overlap DDL |
| Read replica | Run the report on a replica | Takes load off the primary | Replica lag; on PostgreSQL long queries conflict with replay |
-- 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;pg_dump --serializable-deferrable -Fc app > app.dump
mysqldump --single-transaction --routines --triggers app > app.sqldatabase/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:
// 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
}// 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.
-- 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 skippingfunc 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
}// 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."
| Error | Engine | Retry? | Note |
|---|---|---|---|
| SQLSTATE 40001 | PostgreSQL, CockroachDB, MySQL (as SQLSTATE of 1213) | Yes | Retry the whole transaction, from BEGIN |
| 40P01 | PostgreSQL | Yes | Also fix lock ordering (Deadlocks) |
| 1213 | MySQL | Yes | Transaction already rolled back by InnoDB |
| 1205 | MySQL | Yes, carefully | Only the statement was rolled back: roll back the transaction yourself before retrying |
Msg 3960, ORA-08177 | SQL Server, Oracle | Yes | Snapshot write conflict |
| 23505, 1062, 23P01 | PostgreSQL, MySQL | No | The constraint did its job: answer the user |
TransientTransactionError | MongoDB | Yes | The driver's callback API retries for you |
Rules.
- Retry the whole transaction, never a single statement: after
40001the transaction is dead in PostgreSQL (every later statement fails with25P02in_failed_sql_transaction), and its reads are stale anyway. - 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). - 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.
- Classify the
COMMITerror too: SSI can fail at commit. - Retry only at the outermost transaction boundary; an inner retry inside an outer transaction re-runs on a doomed transaction.
- Measure: export the retry count and the
40001rate. 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.
// 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:
- No delay between attempts. The loop
continues straight into the nextbeginTransaction(), so colliding requests retry in lockstep. There is no backoff or jitter. - No retry inside a nested transaction. If the closure runs while another transaction is open (
transactions > 1), Laravel rolls back to the savepoint and throwsDeadlockExceptioninstead of retrying, because the outer transaction is already lost. Retries only happen at the outermostDB::transaction. - No isolation level, and side effects re-run. There is no
isolation:parameter: on PostgreSQL you must issueSET TRANSACTIONas the first statement inside the closure, while on MySQL that statement fails inside a transaction (ERROR 1568) and must run beforebeginTransaction(). And everything in the closure runs again on retry; dispatch jobs with->afterCommit()(orafter_commit => trueon the queue connection) and useDB::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
// 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);
}
}// 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.
| Workload | Recommended level | Extra technique | Reason |
|---|---|---|---|
| CRUD web app, single-row edits | Default (RC in PostgreSQL, RR in InnoDB) | Version column for edit forms | Conflicts are rare and row-local |
| Counters, stock, balances on one row | Read Committed | Atomic update with a guard (AND stock >= 1) | One statement is always isolated with itself |
| Financial ledger, payments, wallets | Read Committed + FOR UPDATE on the account, or Serializable + retry | Append-only ledger, CHECK (balance >= 0), idempotency key | One 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 row | Write skew is invisible at every snapshot level |
| Bookings, reservations, schedules | Read Committed | EXCLUDE USING gist (PostgreSQL) or slot table with unique key (MySQL) | The constraint enforces it for every writer |
| Uniqueness (emails, coupons, idempotency) | Read Committed | Unique constraint + ON CONFLICT DO NOTHING / INSERT IGNORE | Check-then-insert is racy at every level except Serializable |
| Job queues | Read Committed | FOR UPDATE SKIP LOCKED | Workers must not wait behind each other |
| Reports, exports, backups | Repeatable Read READ ONLY (PostgreSQL), consistent snapshot (InnoDB) | SERIALIZABLE READ ONLY DEFERRABLE for period closes; pg_dump, mysqldump --single-transaction | One moment in time, no blocking |
| Analytics on a replica | Repeatable Read on the replica | Accept replica lag | Keeps load off the primary |
| SQL Server with readers blocking writers | RCSI | SNAPSHOT for multi-statement reads | Removes reader/writer blocking without NOLOCK |
| Porting an app between PostgreSQL and MySQL | Do not rely on RR semantics | Explicit locks, atomic updates, constraints | RR 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).
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 refundedCountermeasures (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:
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 TTLMitigations: 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×
| Load | What changes | Isolation consequence |
|---|---|---|
| 1× (one primary, modest traffic) | Default level, constraints, a few FOR UPDATEs, Serializable for multi-row rules | Retries are rare; correctness is cheap |
| 10× (hot rows, read replicas, connection pool) | Hot counters become contention points; reports move to replicas; pools reuse connections | Replace 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 everywhere | Invariants 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.
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-- 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).
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 updateExperiment 2: write skew at Repeatable Read, prevented at Serializable (PostgreSQL).
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).
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).
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).
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).
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
| Belief | Reality |
|---|---|
| “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
| Topic | What to remember |
|---|---|
| Defaults | PostgreSQL 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 read | P0 never allowed; P1 only at InnoDB/SQL Server Read Uncommitted or NOLOCK |
| Lost update | Atomic update > FOR UPDATE > version column > PostgreSQL RR/Serializable + retry; InnoDB RR does not help |
| Write skew | Only Serializable (PostgreSQL SSI, CockroachDB, InnoDB/SQL Server 2PL) stops it; or lock the rule's rows, or materialise the conflict |
| Phantoms | Snapshot for re-reads; next-key locks in InnoDB; constraints for check-then-insert |
| PostgreSQL RC | New snapshot per statement; writers re-check the new row version (website/hits surprise) |
| InnoDB RR | Plain reads = snapshot of first read; locking reads and DML = latest committed + next-key locks |
| Errors to retry | 40001, 40P01, 1213, 1205 (after rollback), Msg 3960, ORA-08177, TransientTransactionError |
| Errors not to retry | 23505, 23P01, 1062: the constraint answered |
| Retry wrapper | Whole transaction, bounded, retry with jitter, side effects after commit, classify COMMIT too, outermost only |
| Reports | REPEATABLE READ READ ONLY; period closes with SERIALIZABLE READ ONLY DEFERRABLE; pg_dump, mysqldump --single-transaction |
| Job queues | FOR UPDATE SKIP LOCKED; NOWAIT to fail fast |
| Bookings | EXCLUDE USING gist (room_id WITH =, during WITH &&) with btree_gist |
| Long transactions | Bloat and dead tuples (PostgreSQL), history list length (InnoDB), version store (SQL Server), snapshot too old (Oracle); set idle_in_transaction_session_timeout |
| Setting the level | PostgreSQL: first statement or BEGIN ISOLATION LEVEL; MySQL: before START TRANSACTION (ERROR 1568 inside) |
| Outside one database | Replicas, caches, sagas: no isolation; use read-your-writes, versioned cache writes, semantic locks, idempotency keys |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Non-repeatable read (fuzzy read) | The ANSI name and the Critique's name for P2, used interchangeably |
| First-updater-wins / first-committer-wins | The two SI write-conflict rules: detect at the second write (engines) or at commit (the Critique) |
| Version store/tempdb | Where SQL Server keeps row versions: tempdb by default, the user database with ADR |
| Saga semantic lock | A status flag such as PENDING that tells other operations a saga is still in flight |
| DB::transaction attempts | Laravel's retry count argument; retries immediately and only at the outermost level |
| MySQL 1213 | ER_LOCK_DEADLOCK, SQLSTATE 40001; the whole transaction was rolled back |
| MongoDB snapshot read concern / WriteConflict | MongoDB transactions read a majority-committed snapshot and abort with WriteConflict on concurrent writes |
| CockroachDB Serializable default | CockroachDB runs Serializable unless Read Committed is enabled and requested |
| Spanner external consistency | Spanner's default: serializable and consistent with real-time order (TrueTime) |
| Redis MULTI/EXEC/WATCH | Redis queues commands with MULTI, runs them atomically with EXEC, and aborts EXEC if a WATCHed key changed |
| ANSI SQL-92 | The 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 level | The contract about which anomalies concurrent transactions may observe |
| Anomaly / phenomenon | An interleaving whose result differs from every serial order |
| P0 | Dirty write: overwriting another transaction's uncommitted write |
| Dirty write | See P0; prevented by every engine at every level |
| Dirty read (P1) | Reading another transaction's uncommitted write |
| Non-repeatable read | P2: re-reading a row returns a different committed value |
| Fuzzy read | Another 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 Stability | Read 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 anomaly | Any committed result inconsistent with every serial order |
| Read-only transaction anomaly | Under SI, a read-only transaction observes a state no serial order produces (Fekete et al.) |
| Fekete | Co-author of the read-only anomaly result and of the SSI design |
| Serial vs serializable | Serial = literally one at a time; serializable = equivalent to some serial order |
| Read Uncommitted | Level allowing dirty reads (real in InnoDB/SQL Server, mapped to RC in PostgreSQL) |
| Read Committed | Each statement sees data committed before it began |
| Repeatable Read | Rows read stay stable; meaning varies by engine (SI in PostgreSQL, snapshot + locks in InnoDB, locks in SQL Server) |
| Snapshot Isolation | Transaction reads one snapshot; write-write conflicts abort one writer; permits write skew |
| Serializable | Result equals some serial order (2PL, SSI or actual serial execution) |
| Strict Serializable | Serializable and consistent with real-time order |
| Linearizability vs isolation | Linearizability: single-object recency in real time; isolation: multi-object transaction interleaving |
| External consistency | Spanner's name for strict serializability |
| TrueTime | Spanner's clock API with bounded uncertainty used to order commits |
| First-updater-wins | The second writer of a row waits, then aborts if the first committed (PostgreSQL RR, Oracle, SQL Server SNAPSHOT) |
| First-committer-wins | The Critique's SI rule: of two concurrent writers of an item, only the first to commit succeeds |
| could not serialize access | PostgreSQL's message text for SQLSTATE 40001 |
| SQLSTATE 40001 | serialization_failure: retry the transaction (also MySQL 1213's SQLSTATE) |
| serialization_failure | PostgreSQL condition name for 40001 |
| 40P01 | PostgreSQL deadlock_detected |
| deadlock_detected | PostgreSQL condition name for 40P01 |
| 1213 | MySQL ER_LOCK_DEADLOCK; transaction rolled back |
| 1205 | MySQL ER_LOCK_WAIT_TIMEOUT; statement rolled back |
| 1062 | MySQL ER_DUP_ENTRY; unique key violation |
| 23505 | PostgreSQL unique_violation |
| 23P01 | PostgreSQL exclusion_violation |
| 55P03 | PostgreSQL lock_not_available (e.g. NOWAIT) |
| ERROR 1568 | MySQL: transaction characteristics cannot change inside a transaction |
| Msg 3960 | SQL Server snapshot isolation update conflict |
| ORA-08177 | Oracle: cannot serialize access for this transaction |
| SSI | Serializable Snapshot Isolation: SI plus detection of dangerous rw-dependency structures (PostgreSQL, CockroachDB-style) |
| SIReadLock | PostgreSQL's non-blocking predicate lock recording what a serializable transaction read |
| rw-dependency | T1 read a version T2's write replaced; T1 must precede T2 |
| Dangerous structure | Two adjacent rw-dependencies T1 → T2 → T3; SSI aborts one transaction when it appears |
| Pivot | The middle transaction of a dangerous structure |
| Predicate lock | A lock on all rows matching a condition, including future ones |
| max_pred_locks_per_transaction | PostgreSQL memory knob for predicate locks; too low causes escalation and more 40001 |
| pg_locks | PostgreSQL view of current locks, including SIReadLock |
| 2PL | Two-phase locking: acquire, then release, never acquire after releasing |
| Strict 2PL | 2PL that holds write locks until commit/abort |
| Record lock | InnoDB lock on one index record |
| Gap lock | InnoDB lock on the gap between index records; only blocks inserts |
| Next-key lock | InnoDB record lock + gap lock before it; prevents phantoms |
| Insert intention lock | InnoDB gap-level lock taken by INSERT before inserting a row |
| Semi-consistent read | InnoDB RC: an UPDATE reads the latest committed version of a locked row to test its WHERE |
| Consistent nonlocking read | InnoDB plain SELECT from a snapshot |
| Locking read | SELECT ... FOR UPDATE / FOR SHARE: reads latest committed rows and locks them |
| FOR UPDATE | Exclusive row lock on selected rows |
| FOR NO KEY UPDATE | PostgreSQL's weaker update lock that does not block foreign-key FOR KEY SHARE |
| FOR SHARE | Shared row lock: others may read and share-lock, not modify |
| NOWAIT | Fail immediately instead of waiting for a row lock |
| SKIP LOCKED | Skip rows that are locked; for queues |
| READ ONLY | Transaction access mode forbidding writes (PostgreSQL 25006 if violated) |
| DEFERRABLE | PostgreSQL: a SERIALIZABLE READ ONLY transaction waits for a safe snapshot and cannot fail |
| START TRANSACTION WITH CONSISTENT SNAPSHOT | MySQL: take the InnoDB RR snapshot immediately |
| default_transaction_isolation | PostgreSQL / CockroachDB setting for new transactions' level |
| transaction_isolation | PostgreSQL parameter showing the current level; MySQL system variable for the level |
| idle_in_transaction_session_timeout | PostgreSQL: kill sessions idle inside an open transaction |
| transaction_timeout | PostgreSQL: limit total transaction duration |
| innodb_lock_wait_timeout | MySQL seconds to wait for a row lock before error 1205 |
| RCSI | SQL Server Read Committed Snapshot Isolation (READ_COMMITTED_SNAPSHOT ON) |
| READ_COMMITTED_SNAPSHOT | SQL Server database option that turns RC into statement-level row versioning |
| ALLOW_SNAPSHOT_ISOLATION | SQL Server database option required before using SNAPSHOT |
| READCOMMITTEDLOCK | SQL Server table hint forcing locking RC under RCSI |
| NOLOCK | SQL Server table hint equal to Read Uncommitted |
| Version store | SQL Server storage of row versions for RCSI/SNAPSHOT |
| tempdb | SQL Server system database that hosts the version store unless ADR is on |
| Undo log | InnoDB/Oracle record of previous row versions used for rollback and consistent reads |
| History list length | InnoDB count of undo log pages not yet purged; grows with long transactions |
| Snapshot too old | Oracle error when undo needed for a consistent read was overwritten |
| Dead tuples | PostgreSQL row versions no longer visible to anyone, waiting for VACUUM |
| VACUUM | PostgreSQL process that reclaims dead tuples |
| Bloat | Space wasted by dead tuples or versions that cannot be reclaimed yet |
| SQLite WAL mode | Journal mode where readers see a snapshot while one writer appends |
| SQLITE_BUSY_SNAPSHOT | SQLite error when a reader with a stale snapshot tries to write |
| Snapshot read concern | MongoDB read concern giving a transaction a majority-committed point-in-time snapshot |
| WriteConflict | MongoDB error when a transaction writes a document modified concurrently |
| TransientTransactionError | MongoDB error label meaning the whole transaction may be retried |
| transactionLifetimeLimitSeconds | MongoDB limit on a transaction's runtime |
| CockroachDB | Distributed SQL database, Serializable by default, retry on 40001 |
| Spanner | Google's distributed database with external consistency |
| MULTI/EXEC/WATCH | Redis transaction commands: queue, execute atomically, abort if a watched key changed |
| Compare-and-set | Write only if the value is still what you read (Redis WATCH, version columns) |
| Atomic update | A 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 |
| Optimistic | Detect conflicts at write time instead of locking |
| Unique constraint | Index-enforced uniqueness; the reliable fix for check-then-insert |
| ON CONFLICT DO NOTHING | PostgreSQL insert that skips rows violating a unique/exclusion constraint |
| INSERT IGNORE | MySQL insert that ignores ignorable errors such as duplicate keys |
| EXCLUDE USING gist | PostgreSQL exclusion constraint, e.g. no overlapping ranges per room |
| btree_gist | PostgreSQL extension that lets GiST exclusion constraints use scalar = |
| Materializing the conflict | Turning a multi-row rule into a row (or constraint) every writer must update |
| pg_advisory_xact_lock | PostgreSQL application-defined lock held until transaction end |
| pg_dump | PostgreSQL logical backup; runs in one snapshot, --serializable-deferrable for a safe one |
| mysqldump --single-transaction | Consistent InnoDB dump using one RR snapshot |
| Replica lag | Delay between a commit on the primary and its replay on a replica |
| Read-your-writes | Guarantee that a client sees its own writes in later reads |
| Cache lost update | A stale value written to a cache after a newer value invalidated it |
| Saga | A sequence of local transactions with compensations; no isolation between steps |
| Semantic lock | An application-level flag (e.g. PENDING) that other operations respect during a saga |
| Outbox | A table written in the same transaction as the change, relayed to a broker later |
| Idempotency key | A unique key that makes a repeated request or message apply once |
| ORM hidden transaction boundary | Where an ORM silently opens/commits transactions (autocommit save(), lazy loads) |
| DB::transaction | Laravel's closure-based transaction with optional attempts |
| attempts | DB::transaction argument: total tries on deadlock/serialization errors |
| afterCommit | Laravel DB::afterCommit() / job ->afterCommit(): run after the outer transaction commits |
| lockForUpdate | Laravel query builder FOR UPDATE |
| lockForNoKeyUpdate | Laravel query builder FOR NO KEY UPDATE (PostgreSQL) |
| sharedLock | Laravel query builder FOR SHARE / LOCK IN SHARE MODE |
| sql.TxOptions | Go database/sql struct with Isolation and ReadOnly for BeginTx |
| Retry with jitter | Exponential backoff with randomised delay to avoid synchronized retries |
References
- Berenson, Bernstein, Gray, Melton, O'Neil, O'Neil, "A Critique of ANSI SQL Isolation Levels", SIGMOD 1995 / MSR-TR-95-51. Microsoft Research PDF, archived copy
- Ports & Grittner, "Serializable Snapshot Isolation in PostgreSQL", VLDB 2012. PDF
- PostgreSQL documentation: 13.2 Transaction Isolation, SET TRANSACTION, SELECT locking clause, Explicit Locking, Range types and exclusion constraints, Constraints, Client connection defaults, Error codes, pg_dump
- MySQL 8.4 Reference Manual (read via web.archive.org): Transaction Isolation Levels, InnoDB Locking, Phantom Rows, Consistent Nonlocking Reads, Locking Reads, SET TRANSACTION, START TRANSACTION, InnoDB Error Handling, Purge Configuration, mysqldump, INSERT, Server Error Reference
- Microsoft: SET TRANSACTION ISOLATION LEVEL (Transact-SQL), Transaction locking and row versioning guide
- Oracle Database 19c Concepts: Data Concurrency and Consistency
- SQLite: Isolation In SQLite
- MongoDB: Read Concern "snapshot", Production Considerations, Transactions in Applications
- CockroachDB: Transactions, Read Committed Transactions
- Google Cloud: Spanner: TrueTime and external consistency
- Redis: Transactions
- Jepsen: Strong Serializability
- Laravel 13: Database: Transactions, Query Builder: Pessimistic Locking, Queues; framework source: ManagesTransactions.php, ConcurrencyErrorDetector.php, DatabaseQueue.php
- Go:
database/sql, pgx v5, go-sql-driver/mysql