# Database Transactions: generated Scenario transcripts Each section below is one scenario, replayed against a real database by `bun run gen`. The structured index of the same runs is at https://database-transactions.svyatov.com/ledger.jsonl. ## mysql/01-basics/aborted-transaction.yaml - engine: mysql (MySQL 8.4.11) - claim: The demonstrated duplicate-key INSERT error (1062, without IGNORE) rolls back that statement; the earlier and later INSERTs commit in the same InnoDB transaction. This does not describe deadlock or connection errors. ```transcript A> BEGIN; Query OK A> INSERT INTO items VALUES (2, 'gadget'); Query OK, 1 row affected A> INSERT INTO items VALUES (3, 'widget'); -- ER_DUP_ENTRY ERROR 1062 (23000): Duplicate entry 'widget' for key 'items.name' ``` *This 1062 error leaves the earlier INSERT intact. A chooses to continue and COMMIT.* ```transcript A> INSERT INTO items VALUES (3, 'doohickey'); Query OK, 1 row affected A> COMMIT; Query OK A> SELECT id, name FROM items ORDER BY id; -- survived the error in the middle id | name ----+----------- 1 | widget 2 | gadget 3 | doohickey (3 rows) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/01-basics/aborted-transaction.yaml) ## mysql/01-basics/atomicity.yaml - engine: mysql (MySQL 8.4.11) - claim: On InnoDB, the demonstrated CHECK error leaves bob's earlier credit in A's transaction; explicit ROLLBACK then discards both balances' changes. ```timeline A: credit bob +150 (uncommitted) B: read bob → 50 (credit hidden) A: debit alice −150 ← 3819 Check constraint 'accounts_chk_1' is violated. A: ROLLBACK; bob's credit gone too B: read → alice 100, bob 50 (untouched) ``` *A transfers 150 from alice to bob. Crediting bob works fine…* ```transcript A> BEGIN; Query OK A> UPDATE accounts SET balance = balance + 150 WHERE owner = 'bob'; Query OK, 1 row affected B> SELECT balance FROM accounts WHERE owner = 'bob'; -- B can't see A's uncommitted credit balance --------- 50 (1 row) ``` *…but debiting alice violates the CHECK constraint; she only has 100.* ```transcript A> UPDATE accounts SET balance = balance - 150 WHERE owner = 'alice'; -- ER_CHECK_CONSTRAINT_VIOLATED ERROR 3819 (HY000): Check constraint 'accounts_chk_1' is violated. ``` *A's SELECT still sees bob's successful credit. The explicit ROLLBACK below discards it.* ```transcript A> SELECT owner, balance FROM accounts ORDER BY id; owner | balance -------+--------- alice | 100 bob | 200 (2 rows) A> ROLLBACK; Query OK B> SELECT owner, balance FROM accounts ORDER BY id; owner | balance -------+--------- alice | 100 bob | 50 (2 rows) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/01-basics/atomicity.yaml) ## mysql/01-basics/autocommit-visibility.yaml - engine: mysql (MySQL 8.4.11) - claim: With autocommit=1 on InnoDB, A's successful standalone UPDATE is visible to B's later standalone SELECT. B excludes A's explicit-transaction UPDATE until COMMIT; a pre-existing REPEATABLE READ snapshot need not refresh. ```timeline A: UPDATE balance = 150 (autocommit) B: SELECT balance → 150 (visible at once) A: UPDATE balance = 999 (uncommitted) B: SELECT balance → 150 (A's change hidden) A: COMMIT B: SELECT balance → 999 (now visible) ``` ```transcript A> SELECT @@autocommit AS autocommit, @@transaction_isolation AS isolation, @@default_storage_engine AS engine; autocommit | isolation | engine ------------+-----------------+-------- 1 | REPEATABLE-READ | InnoDB (1 row) B> SELECT @@autocommit AS autocommit; autocommit ------------ 1 (1 row) ``` *No BEGIN; the UPDATE is its own transaction, committed the instant it finishes.* ```transcript A> UPDATE accounts SET balance = 150 WHERE id = 1; Query OK, 1 row affected B> SELECT balance FROM accounts WHERE id = 1; -- B sees it immediately balance --------- 150 (1 row) ``` *Inside an explicit transaction, A's change is invisible to B…* ```transcript A> BEGIN; Query OK A> UPDATE accounts SET balance = 999 WHERE id = 1; Query OK, 1 row affected B> SELECT balance FROM accounts WHERE id = 1; -- still the old value balance --------- 150 (1 row) ``` *B's next standalone SELECT takes a new snapshot after A commits.* ```transcript A> COMMIT; Query OK B> SELECT balance FROM accounts WHERE id = 1; balance --------- 999 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/01-basics/autocommit-visibility.yaml) ## mysql/01-basics/savepoint-nesting.yaml - engine: mysql (MySQL 8.4.11) - claim: Rolling back to an outer savepoint discards inner savepoints along with their work; RELEASE keeps the changes but forfeits the rollback point. ```transcript A> BEGIN; Query OK A> INSERT INTO steps VALUES (1); Query OK, 1 row affected A> SAVEPOINT outer_sp; Query OK A> INSERT INTO steps VALUES (2); Query OK, 1 row affected A> SAVEPOINT inner_sp; Query OK A> INSERT INTO steps VALUES (3); Query OK, 1 row affected ``` *Rolling back to the OUTER savepoint discards rows 2 and 3; and inner_sp itself.* ```transcript A> ROLLBACK TO SAVEPOINT outer_sp; Query OK A> ROLLBACK TO SAVEPOINT inner_sp; -- SAVEPOINT inner_sp does not exist; destroyed by the outer rollback ERROR 1305 (42000): SAVEPOINT inner_sp does not exist ``` *RELEASE keeps the work done after the savepoint, but you can no longer rewind to it.* ```transcript A> INSERT INTO steps VALUES (4); Query OK, 1 row affected A> RELEASE SAVEPOINT outer_sp; Query OK A> ROLLBACK TO SAVEPOINT outer_sp; -- the released savepoint no longer exists ERROR 1305 (42000): SAVEPOINT outer_sp does not exist A> COMMIT; Query OK A> SELECT n FROM steps ORDER BY n; n --- 1 4 (2 rows) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/01-basics/savepoint-nesting.yaml) ## mysql/01-basics/savepoint-recovery.yaml - engine: mysql (MySQL 8.4.11) - claim: In this InnoDB INSERT branch, ROLLBACK TO SAVEPOINT removes the successful branch INSERT after a 1062 error, preserves the earlier INSERT, and allows the replacement branch to commit. ```transcript A> BEGIN; Query OK A> INSERT INTO items VALUES (2, 'gadget'); Query OK, 1 row affected A> SAVEPOINT before_risky; Query OK ``` *The risky branch makes real progress before it fails…* ```transcript A> INSERT INTO items VALUES (3, 'gizmo'); Query OK, 1 row affected A> INSERT INTO items VALUES (4, 'widget'); -- ER_DUP_ENTRY ERROR 1062 (23000): Duplicate entry 'widget' for key 'items.name' ``` *The transaction is still alive; but the branch is half-done. Rewind all of it in one go.* ```transcript A> ROLLBACK TO SAVEPOINT before_risky; Query OK A> SELECT id, name FROM items ORDER BY id; id | name ----+-------- 1 | widget 2 | gadget (2 rows) A> INSERT INTO items VALUES (3, 'doohickey'); Query OK, 1 row affected A> COMMIT; Query OK A> SELECT id, name FROM items ORDER BY id; -- survived; it predates the savepoint; 'gizmo' is gone with the branch id | name ----+----------- 1 | widget 2 | gadget 3 | doohickey (3 rows) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/01-basics/savepoint-recovery.yaml) ## mysql/02-isolation/circular-information-flow.yaml - engine: mysql (MySQL 8.4.11) - claim: At READ UNCOMMITTED two concurrent transactions can each read the other's uncommitted write (Adya's G1c, "circular information flow"); an exchange no serial order can explain. The repeated READ COMMITTED schedule excludes those dirty cross-reads, but its two old reads do not prove serializability. ```timeline A: UPDATE alice = 111 (uncommitted) B: UPDATE bob = 222 (uncommitted) A: read bob → 222 (B's uncommitted) B: read alice → 111 (A's uncommitted) A: COMMIT B: COMMIT ``` *A adjusts alice while B adjusts bob; then each peeks at the other's row. In any serial order, at most one of them can see the other's write.* ```transcript A> SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; Query OK B> SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; Query OK A> BEGIN; Query OK B> BEGIN; Query OK A> UPDATE accounts SET balance = 111 WHERE id = 1; Query OK, 1 row affected B> UPDATE accounts SET balance = 222 WHERE id = 2; Query OK, 1 row affected A> SELECT balance FROM accounts WHERE id = 2; -- A sees B's uncommitted write… balance --------- 222 (1 row) B> SELECT balance FROM accounts WHERE id = 1; -- …and B sees A's. Information flowed in a circle. balance --------- 111 (1 row) ``` *Both dirty cross-reads are asserted, then both writers commit. No serial order of these two transactions gives both new values to the readers. No external application arithmetic is executed.* ```transcript A> COMMIT; Query OK B> COMMIT; Query OK A> SELECT id, balance FROM accounts ORDER BY id; id | balance ----+--------- 1 | 111 2 | 222 (2 rows) A> UPDATE accounts SET balance = 100; Query OK, 2 rows affected ``` *After resetting both balances, READ COMMITTED excludes these dirty cross-reads. The two old reads still do not form a serial execution.* ```transcript A> SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; Query OK B> SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; Query OK A> BEGIN; Query OK B> BEGIN; Query OK A> UPDATE accounts SET balance = 111 WHERE id = 1; Query OK, 1 row affected B> UPDATE accounts SET balance = 222 WHERE id = 2; Query OK, 1 row affected A> SELECT balance FROM accounts WHERE id = 2; balance --------- 100 (1 row) B> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) A> COMMIT; Query OK B> COMMIT; Query OK ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/circular-information-flow.yaml) ## mysql/02-isolation/current-reads.yaml - engine: mysql (MySQL 8.4.11) - claim: In this InnoDB REPEATABLE READ schedule, A's UPDATE computes from B's committed 150, not its snapshot's 100, and A reads its own result 200. In the second attempt A waits for B's commit of 300 and produces 350. ```timeline A: SELECT balance → 100 (snapshot) B: UPDATE balance = 150 (committed) A: SELECT balance → 100 (snapshot holds) A: UPDATE +50 (current read of 150) A: SELECT balance → 200 (150 + 50; the hole) A: COMMIT ``` ```transcript A> SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ; Query OK A> BEGIN; Query OK A> SELECT balance FROM accounts WHERE id = 1; -- snapshot taken balance --------- 100 (1 row) ``` *B commits a change. A keeps READING its stale snapshot…* ```transcript B> UPDATE accounts SET balance = 150 WHERE id = 1; Query OK, 1 row affected A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) ``` *…but A's UPDATE is a current read: it computes from B's committed 150, not from the snapshot's 100.* ```transcript A> UPDATE accounts SET balance = balance + 50 WHERE id = 1; Query OK, 1 row affected A> SELECT balance FROM accounts WHERE id = 1; -- 150 + 50; and now A sees it: the snapshot has a hole balance --------- 200 (1 row) A> COMMIT; Query OK ``` *A's own write is visible to its later consistent SELECT. The PostgreSQL comparison is in its concurrent-update lesson.* *If the competing write is NOT yet committed, A first waits on the row lock…* ```transcript A> BEGIN; Query OK A> SELECT balance FROM accounts WHERE id = 1; -- snapshot taken balance --------- 200 (1 row) B> BEGIN; Query OK B> UPDATE accounts SET balance = 300 WHERE id = 1; Query OK, 1 row affected A> UPDATE accounts SET balance = balance + 50 WHERE id = 1; ⏳ A is waiting for a lock… ``` *…and proceeds from B's value the moment B commits. No error here either.* ```transcript B> COMMIT; Query OK ⏵ A resumes: Query OK, 1 row affected A> SELECT balance FROM accounts WHERE id = 1; -- 300 + 50 balance --------- 350 (1 row) A> COMMIT; Query OK ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/current-reads.yaml) ## mysql/02-isolation/dirty-read.yaml - engine: mysql (MySQL 8.4.11) - claim: At READ UNCOMMITTED, MySQL serves other transactions' uncommitted changes including the asserted 999 that A later rolls back. The value existed uncommitted, but never became part of committed history. ```timeline A: UPDATE balance = 999 (uncommitted) B: SELECT balance → 999 (dirty read) A: ROLLBACK; 999 never committed B: SELECT balance → 100 (the real value) ``` ```transcript A> BEGIN; Query OK A> UPDATE accounts SET balance = 999 WHERE id = 1; Query OK, 1 row affected ``` *B opts into READ UNCOMMITTED; and sees A's uncommitted 999.* ```transcript B> SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; Query OK B> BEGIN; Query OK B> SELECT @@transaction_isolation AS isolation; isolation ------------------ READ-UNCOMMITTED (1 row) B> SELECT balance FROM accounts WHERE id = 1; -- a dirty read; A never committed this balance --------- 999 (1 row) ``` *A rolls back. The 999 B read never became committed.* ```transcript A> ROLLBACK; Query OK B> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) B> COMMIT; Query OK ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/dirty-read.yaml) ## mysql/02-isolation/dirty-write.yaml - engine: mysql (MySQL 8.4.11) - claim: In this InnoDB READ UNCOMMITTED schedule, B's UPDATE of A's uncommitted row waits until A commits. Both of B's later prices are asserted after B commits. All-level dirty-write exclusion needs the row-lock contract. ```timeline A: UPDATE mug = 11 B: UPDATE mug = 12 → ⏳ waits A: UPDATE cap = 21 A: COMMIT B: ⏵ UPDATE mug = 12 → completes B: UPDATE cap = 22 B: COMMIT A: SELECT → 12, 22 (both B) ``` *Two batch jobs reprice the whole catalog concurrently at READ UNCOMMITTED. The dirty-write event would be overwriting A's uncommitted row; a mixed final state is not its definition.* ```transcript A> SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; Query OK B> SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; Query OK A> BEGIN; Query OK B> BEGIN; Query OK A> UPDATE items SET price = 11 WHERE id = 1; Query OK, 1 row affected ``` *B may READ A's uncommitted rows at this level; but it may not overwrite them.* ```transcript B> UPDATE items SET price = 12 WHERE id = 1; ⏳ B is waiting for a lock… A> UPDATE items SET price = 21 WHERE id = 2; Query OK, 1 row affected A> COMMIT; -- releases both row locks Query OK ⏵ B resumes: Query OK, 1 row affected B> UPDATE items SET price = 22 WHERE id = 2; Query OK, 1 row affected B> COMMIT; Query OK A> SELECT id, price FROM items ORDER BY id; -- both of B's prices in this schedule id | price ----+------- 1 | 12 2 | 22 (2 rows) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/dirty-write.yaml) ## mysql/02-isolation/intermediate-read.yaml - engine: mysql (MySQL 8.4.11) - claim: At READ UNCOMMITTED a reader can observe an intermediate value the writer later overwrites before committing (Adya's G1b, "intermediate read"); a number absent from committed history. In the repeated READ COMMITTED schedule, B reads 110 while A's draft 555 is uncommitted. ```timeline A: UPDATE balance = 999 (a draft) B: SELECT balance → 999 (reads the draft) A: UPDATE balance = 110 (final value) A: COMMIT B: SELECT balance → 110 (999 never committed) ``` *A recalculates alice's balance in two steps. B watches at READ UNCOMMITTED.* ```transcript B> SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; Query OK B> BEGIN; Query OK A> BEGIN; Query OK A> UPDATE accounts SET balance = 999 WHERE id = 1; -- a working draft; A isn't done yet Query OK, 1 row affected B> SELECT balance FROM accounts WHERE id = 1; -- B just read a draft balance --------- 999 (1 row) A> UPDATE accounts SET balance = 110 WHERE id = 1; -- A settles on the final value… Query OK, 1 row affected A> COMMIT; Query OK B> SELECT balance FROM accounts WHERE id = 1; balance --------- 110 (1 row) B> COMMIT; Query OK ``` *The committed history is 100 → 110. B read 999 without executing any application action. At READ COMMITTED, B now excludes A's draft 555:* ```transcript B> SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; Query OK B> BEGIN; Query OK A> BEGIN; Query OK A> UPDATE accounts SET balance = 555 WHERE id = 1; Query OK, 1 row affected B> SELECT balance FROM accounts WHERE id = 1; -- no drafts served here balance --------- 110 (1 row) A> ROLLBACK; Query OK B> COMMIT; Query OK ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/intermediate-read.yaml) ## mysql/02-isolation/lost-update-read-committed.yaml - engine: mysql (MySQL 8.4.11) - claim: Two read-modify-write transactions at READ COMMITTED can silently overwrite each other: two deposits of 10 grow the balance by only 10. ```timeline A: SELECT balance → 100 B: SELECT balance → 100 (same stale read) A: UPDATE balance = 100 + 10 A: COMMIT B: UPDATE balance = 100 + 10 (stale math) B: COMMIT A: SELECT balance → 110; one deposit gone ``` *Two app servers process a +10 deposit each: read the balance, add 10 in code, write it back.* ```transcript A> SET TRANSACTION ISOLATION LEVEL READ COMMITTED; Query OK A> BEGIN; Query OK A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) B> SET TRANSACTION ISOLATION LEVEL READ COMMITTED; Query OK B> BEGIN; Query OK B> SELECT balance FROM accounts WHERE id = 1; -- B reads the same 100; A hasn't committed balance --------- 100 (1 row) A> UPDATE accounts SET balance = 100 + 10 WHERE id = 1; Query OK, 1 row affected A> COMMIT; Query OK ``` *B uses its captured 100 plus 10 in this SQL UPDATE. A has committed; this stale replacement succeeds in the displayed schedule.* ```transcript B> UPDATE accounts SET balance = 100 + 10 WHERE id = 1; Query OK, 0 rows affected B> COMMIT; Query OK A> SELECT balance FROM accounts WHERE id = 1; -- two +10 deposits, but only one survived balance --------- 110 (1 row) ``` *A's deposit vanished without any error. Fixes: atomic UPDATE or SELECT FOR UPDATE; see the lesson.* Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/lost-update-read-committed.yaml) ## mysql/02-isolation/lost-update-repeatable-read.yaml - engine: mysql (MySQL 8.4.11) - claim: In this InnoDB REPEATABLE READ schedule, both transactions read 100 and commit writes of that value plus 10 without error; the final balance is 110, not 120. A stale literal write is not rejected merely for staleness. ```timeline A: SELECT balance → 100 B: SELECT balance → 100 (same snapshot) A: UPDATE balance = 100 + 10 A: COMMIT B: UPDATE balance = 100 + 10; no error! B: COMMIT A: SELECT balance → 110; deposit gone, silently ``` *The same two +10 deposits; this time at REPEATABLE READ, MySQL's default.* ```transcript A> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; Query OK B> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; Query OK A> BEGIN; Query OK A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) B> BEGIN; Query OK B> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) A> UPDATE accounts SET balance = 100 + 10 WHERE id = 1; Query OK, 1 row affected A> COMMIT; Query OK ``` *B's snapshot predates A's commit; but MySQL's UPDATE acts on the CURRENT row and raises nothing.* ```transcript B> UPDATE accounts SET balance = 100 + 10 WHERE id = 1; Query OK, 0 rows affected B> COMMIT; Query OK A> SELECT balance FROM accounts WHERE id = 1; -- A's deposit is gone; silently, even at REPEATABLE READ balance --------- 110 (1 row) ``` *PostgreSQL refuses B's write here (SQLSTATE 40001). MySQL does not; don't port that assumption.* Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/lost-update-repeatable-read.yaml) ## mysql/02-isolation/non-repeatable-read.yaml - engine: mysql (MySQL 8.4.11) - claim: At READ COMMITTED, a transaction can read two different values for the same row; other transactions' commits become visible between its statements. ```timeline A: SELECT balance → 100 B: UPDATE balance = 200 (autocommit) A: SELECT balance → 200; same txn, different answer ``` ```transcript A> SET TRANSACTION ISOLATION LEVEL READ COMMITTED; Query OK A> BEGIN; Query OK A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) ``` *While A's transaction is still open, B updates the row and commits.* ```transcript B> UPDATE accounts SET balance = 200 WHERE id = 1; Query OK, 1 row affected A> SELECT balance FROM accounts WHERE id = 1; -- same query, same transaction; different answer balance --------- 200 (1 row) A> COMMIT; Query OK ``` *These nonlocking SELECTs did not wait for row locks. The interleaving with UPDATEs makes B wait for A's row lock.* ```transcript A> BEGIN; Query OK A> UPDATE accounts SET balance = 300 WHERE id = 1; Query OK, 1 row affected B> UPDATE accounts SET balance = 400 WHERE id = 1; ⏳ B is waiting for a lock… A> COMMIT; -- releases the row lock Query OK ⏵ B resumes: Query OK, 1 row affected B> SELECT balance FROM accounts WHERE id = 1; -- B's write landed on top of A's committed 300 balance --------- 400 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/non-repeatable-read.yaml) ## mysql/02-isolation/observed-transaction-vanishes.yaml - engine: mysql (MySQL 8.4.11) - claim: At READ UNCOMMITTED a reader can see a later transaction's uncommitted overwrite of one row while relying on the overwritten transaction's other row (Adya's OTV, "observed transaction vanishes"); the committed transaction is visible only in pieces in this schedule. The repeated READ COMMITTED SELECTs exclude A's draft and see both rows after commit; separate statements do not have one shared snapshot. ```timeline A: id1 = 11 A: id2 = 19 B: UPDATE id1 = 12 → ⏳ waits A: COMMIT (11 and 19) B: ⏵ UPDATE id1 = 12 → completes C: C reads → 12, 19 (A's 11 already gone) ``` *A rewrites both balances and commits. B overwrites one of them. C reads at READ UNCOMMITTED.* ```transcript C> SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; Query OK C> BEGIN; Query OK A> BEGIN; Query OK A> UPDATE accounts SET balance = 11 WHERE id = 1; Query OK, 1 row affected A> UPDATE accounts SET balance = 19 WHERE id = 2; Query OK, 1 row affected B> BEGIN; Query OK B> UPDATE accounts SET balance = 12 WHERE id = 1; ⏳ B is waiting for a lock… A> COMMIT; -- A is committed; its writes are 11 and 19 Query OK ⏵ B resumes: Query OK, 1 row affected C> SELECT id, balance FROM accounts ORDER BY id; -- 12 is B's uncommitted draft, 19 is A's commit; A's 11 already vanished id | balance ----+--------- 1 | 12 2 | 19 (2 rows) ``` *C never saw the committed state {11, 19}. Half of A was overwritten before C observed it. C's returned rows combine B's draft with A's committed second row. B now finishes:* ```transcript B> UPDATE accounts SET balance = 18 WHERE id = 2; Query OK, 1 row affected B> COMMIT; Query OK C> SELECT id, balance FROM accounts ORDER BY id; id | balance ----+--------- 1 | 12 2 | 18 (2 rows) C> COMMIT; Query OK ``` *These READ COMMITTED SELECTs exclude A's uncommitted changes, then include its commit:* ```transcript C> SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; Query OK C> BEGIN; Query OK A> BEGIN; Query OK A> UPDATE accounts SET balance = 51 WHERE id = 1; Query OK, 1 row affected A> UPDATE accounts SET balance = 59 WHERE id = 2; Query OK, 1 row affected C> SELECT id, balance FROM accounts ORDER BY id; -- all of the last committed state; nothing of A's draft id | balance ----+--------- 1 | 12 2 | 18 (2 rows) A> COMMIT; Query OK C> SELECT id, balance FROM accounts ORDER BY id; -- and now all of A, atomically id | balance ----+--------- 1 | 51 2 | 59 (2 rows) C> COMMIT; Query OK ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/observed-transaction-vanishes.yaml) ## mysql/02-isolation/phantom-read.yaml - engine: mysql (MySQL 8.4.11) - claim: At READ COMMITTED, re-running the same range query inside one transaction can return rows that weren't there before; phantoms. ```timeline A: count(amount ≥ 100) → 2 B: INSERT order 3 (autocommit) A: recount → 3, total 1500; a phantom ``` *A runs two SELECTs inside one transaction: a count first, then a count and total.* ```transcript A> SET TRANSACTION ISOLATION LEVEL READ COMMITTED; Query OK A> BEGIN; Query OK A> SELECT count(*) AS n FROM orders WHERE amount >= 100; n --- 2 (1 row) ``` *Between A's two statements, B commits a new order that matches A's WHERE clause.* ```transcript B> INSERT INTO orders VALUES (3, 700); Query OK, 1 row affected A> SELECT count(*) AS n, CAST(sum(amount) AS SIGNED) AS total FROM orders WHERE amount >= 100; -- a third row appeared out of nowhere; a phantom n | total ---+------- 3 | 1500 (1 row) A> COMMIT; Query OK ``` *A's first SELECT returns count 2; the later SELECT returns count 3 and total 1500. No report publication is executed.* Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/phantom-read.yaml) ## mysql/02-isolation/read-skew.yaml - engine: mysql (MySQL 8.4.11) - claim: At READ COMMITTED, a transaction reading two rows around a concurrent transfer observes money that never existed (Adya's G-single, "read skew"); the repeated REPEATABLE READ schedule returns 25 and 75 from one snapshot, with no writes by the reader. ```timeline A: read alice → 50 B: alice −25 B: bob +25 B: COMMIT (transfer done) A: read bob → 75 (50 + 75 = 125!) ``` *The rule: alice + bob = 100 in each committed state. A models an auditor reading the accounts row by row; B transfers 25 between them mid-audit.* ```transcript A> SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; Query OK A> BEGIN; Query OK A> SELECT balance FROM accounts WHERE owner = 'alice'; balance --------- 50 (1 row) B> BEGIN; Query OK B> UPDATE accounts SET balance = balance - 25 WHERE owner = 'alice'; Query OK, 1 row affected B> UPDATE accounts SET balance = balance + 25 WHERE owner = 'bob'; Query OK, 1 row affected B> COMMIT; -- a perfectly correct transfer; atomic, invariant preserved Query OK A> SELECT balance FROM accounts WHERE owner = 'bob'; -- 50 + 75 = 125. The auditor found 25 that never existed. balance --------- 75 (1 row) A> COMMIT; Query OK ``` *Neither row was ever wrong; A read alice BEFORE the transfer and bob AFTER it. The repeated REPEATABLE READ consistent SELECTs use one snapshot; the reader makes no changes of its own:* ```transcript A> SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ; Query OK A> BEGIN; Query OK A> SELECT balance FROM accounts WHERE owner = 'alice'; balance --------- 25 (1 row) B> BEGIN; Query OK B> UPDATE accounts SET balance = balance - 10 WHERE owner = 'alice'; Query OK, 1 row affected B> UPDATE accounts SET balance = balance + 10 WHERE owner = 'bob'; Query OK, 1 row affected B> COMMIT; Query OK A> SELECT balance FROM accounts WHERE owner = 'bob'; -- 25 + 75 = 100; one snapshot, one moment in time balance --------- 75 (1 row) A> COMMIT; Query OK ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/read-skew.yaml) ## mysql/02-isolation/stable-snapshot.yaml - engine: mysql (MySQL 8.4.11) - claim: In this InnoDB REPEATABLE READ schedule, the first consistent SELECT includes a commit after BEGIN. Later consistent SELECTs exclude B's later UPDATE and INSERT, include A's own UPDATE, and refresh after A commits. ```timeline A: SELECT → 120, 50 (snapshot taken) B: UPDATE id1 = 999 (committed) B: INSERT carol (committed) A: SELECT → 120, 50; no 999, no carol A: COMMIT A: SELECT → 999 + carol (new snapshot) ``` ```transcript A> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; Query OK A> BEGIN; Query OK B> UPDATE accounts SET balance = 120 WHERE id = 1; Query OK, 1 row affected ``` *The first consistent table read includes B's commit after BEGIN.* ```transcript A> SELECT id, balance FROM accounts ORDER BY id; id | balance ----+--------- 1 | 120 2 | 50 (2 rows) ``` *B changes an existing row AND inserts a new one; both committed instantly.* ```transcript B> UPDATE accounts SET balance = 999 WHERE id = 1; Query OK, 1 row affected B> INSERT INTO accounts VALUES (3, 'carol', 300); Query OK, 1 row affected A> SELECT id, balance FROM accounts ORDER BY id; -- not 999; no non-repeatable read; and no carol; no phantom id | balance ----+--------- 1 | 120 2 | 50 (2 rows) A> UPDATE accounts SET balance = balance + 10 WHERE id = 2; Query OK, 1 row affected A> SELECT id, balance FROM accounts ORDER BY id; -- own write is visible alongside the snapshot's old row 1 id | balance ----+--------- 1 | 120 2 | 60 (2 rows) A> COMMIT; Query OK ``` *After COMMIT, this standalone SELECT takes a fresh snapshot.* ```transcript A> SELECT id, balance FROM accounts ORDER BY id; id | balance ----+--------- 1 | 999 2 | 60 3 | 300 (3 rows) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/stable-snapshot.yaml) ## mysql/02-isolation/update-recheck.yaml - engine: mysql (MySQL 8.4.11) - claim: An UPDATE at READ COMMITTED that waited for a lock re-evaluates its WHERE clause against the new row version; rows that no longer match are silently skipped. ```timeline A: UPDATE row1 → 20 (uncommitted) B: UPDATE WHERE value = 10 → ⏳ waits A: COMMIT; row1 is now 20 B: ⏵ UPDATE WHERE value = 10 → completes ``` ```transcript A> BEGIN; Query OK A> UPDATE items SET value = value * 2 WHERE id = 1; -- row 1: 10 → 20, uncommitted Query OK, 1 row affected ``` *B targets WHERE value = 10. The latest committed version of row 1 still qualifies; but it's locked by A, so B waits.* ```transcript B> SET TRANSACTION ISOLATION LEVEL READ COMMITTED; Query OK B> BEGIN; Query OK B> UPDATE items SET value = 99 WHERE value = 10; ⏳ B is waiting for a lock… ``` *A commits. B wakes up and re-checks the row it waited for against the NEW version, where value is 20.* ```transcript A> COMMIT; Query OK ⏵ B resumes: Query OK, 0 rows affected ``` *0 rows affected; the row slipped away.* ```transcript B> COMMIT; Query OK B> SELECT id, value FROM items ORDER BY id; id | value ----+------- 1 | 20 2 | 30 (2 rows) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/update-recheck.yaml) ## mysql/02-isolation/visibility-operations.yaml - engine: mysql (MySQL 8.4.11) - claim: In this InnoDB REPEATABLE READ schedule, A's consistent SELECT retains 100 after B commits 150. SELECT FOR UPDATE returns 150 without refreshing the consistent-read view. A's UPDATE adds 50 to 150, and A reads its own 200 while B still reads 150; after A commits, B reads 200. ```timeline A: Plain SELECT B: UPDATE; autocommit A: Plain SELECT A: Locking SELECT A: Plain SELECT after locking read A: Plain SELECT after own UPDATE ``` ```transcript A> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; Query OK A> BEGIN; Query OK A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) B> UPDATE accounts SET balance = 150 WHERE id = 1; Query OK, 1 row affected A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) A> SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; balance --------- 150 (1 row) A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) A> UPDATE accounts SET balance = balance + 50 WHERE id = 1; Query OK, 1 row affected A> SELECT balance FROM accounts WHERE id = 1; balance --------- 200 (1 row) B> SELECT balance FROM accounts WHERE id = 1; balance --------- 150 (1 row) A> COMMIT; Query OK B> SELECT balance FROM accounts WHERE id = 1; balance --------- 200 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/visibility-operations.yaml) ## mysql/02-isolation/write-predicate-skew.yaml - engine: mysql (MySQL 8.4.11) - claim: In this InnoDB REPEATABLE READ schedule, A's DELETE of balance=20 finds no current matching row after B commits 15/25, while A's consistent SELECT still returns snapshot balance 20. The DELETE affects zero rows. ```timeline A: SELECT → 10, 20 (snapshot) B: +5 to every balance B: COMMIT (now 15, 25) A: DELETE balance = 20 → 0 rows A: SELECT balance = 20 → still sees bob ``` ```transcript A> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; Query OK ``` *A opens a snapshot. B then reshuffles every balance and commits.* ```transcript A> BEGIN; Query OK A> SELECT id, balance FROM accounts ORDER BY id; -- snapshot taken id | balance ----+--------- 1 | 10 2 | 20 (2 rows) B> BEGIN; Query OK B> UPDATE accounts SET balance = balance + 5; Query OK, 2 rows affected B> COMMIT; -- current data is now 15 and 25 Query OK ``` *A closes every account with balance 20; its snapshot says that's bob. But the DELETE is a current read: it scans the committed 15 and 25, finds nothing, and deletes nothing.* ```transcript A> DELETE FROM accounts WHERE balance = 20; Query OK, 0 rows affected A> SELECT id, balance FROM accounts WHERE balance = 20 ORDER BY id; -- …yet A still SEES a row with balance 20. Deleted: no such rows. Visible: one. id | balance ----+--------- 2 | 20 (1 row) A> COMMIT; Query OK ``` *A's DELETE used current rows while its consistent SELECT retained an older snapshot. A locking read must precede the decision and all relevant writers must coordinate; changing a later read alone is not a general repair. See the locking and SERIALIZABLE lessons.* Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/write-predicate-skew.yaml) ## mysql/02-isolation/write-skew-rr.yaml - engine: mysql (MySQL 8.4.11) - claim: Two REPEATABLE READ transactions can each validate an invariant against their snapshots, write to different rows, and both commit; leaving the invariant broken. This is write skew. ```timeline A: on-call count → 2 B: on-call count → 2 A: alice off call B: bob off call A: COMMIT B: COMMIT (both succeed) A: on-call count → 0; invariant broken ``` ```transcript A> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; Query OK B> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; Query OK ``` *Hospital rule: at least one doctor must stay on call. Alice and Bob both want the night off.* ```transcript A> BEGIN; Query OK B> BEGIN; Query OK A> SELECT count(*) AS on_call FROM doctors WHERE on_call; -- "two of us; safe for me to leave" on_call --------- 2 (1 row) B> SELECT count(*) AS on_call FROM doctors WHERE on_call; -- "two of us; safe for me to leave" on_call --------- 2 (1 row) ``` *Each updates a DIFFERENT row, so there is no write-write conflict to detect.* ```transcript A> UPDATE doctors SET on_call = false WHERE name = 'alice'; Query OK, 1 row affected B> UPDATE doctors SET on_call = false WHERE name = 'bob'; Query OK, 1 row affected A> COMMIT; Query OK B> COMMIT; -- both succeed! Query OK A> SELECT count(*) AS on_call FROM doctors WHERE on_call; -- nobody is on call; the invariant is broken on_call --------- 0 (1 row) ``` *Each transaction was internally consistent; together they broke the rule. SERIALIZABLE or suitable coordination by all relevant writers can protect it; the next Scenario executes the SERIALIZABLE schedule.* Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/write-skew-rr.yaml) ## mysql/02-isolation/write-skew-serializable.yaml - engine: mysql (MySQL 8.4.11) - claim: In these explicit InnoDB SERIALIZABLE transactions with deadlock detection enabled, the count SELECTs take shared locks. This schedule rejects B's UPDATE with 1213, A commits, and a fresh B attempt sees one doctor and declines to leave. Other schedules need not select B as victim. ```timeline A: on-call count → 2 (takes shared locks) B: on-call count → 2 (takes shared locks) A: alice off call → ⏳ waits B: bob off call ← 1213 Deadlock found when trying to get lock A: ⏵ alice off call → completes A: COMMIT A: on-call count → 1; invariant survived ``` ```transcript A> SELECT @@innodb_deadlock_detect AS deadlock_detect; deadlock_detect ----------------- 1 (1 row) ``` *Same story, same statements, same order; only the isolation level differs.* ```transcript A> SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; Query OK B> SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; Query OK A> BEGIN; Query OK B> BEGIN; Query OK A> SELECT count(*) AS on_call FROM doctors WHERE on_call; on_call --------- 2 (1 row) B> SELECT count(*) AS on_call FROM doctors WHERE on_call; on_call --------- 2 (1 row) ``` *Those SELECTs took shared locks on the rows they read. A's write now waits for B…* ```transcript A> UPDATE doctors SET on_call = false WHERE name = 'alice'; ⏳ A is waiting for a lock… ``` *…and B's write closes the cycle. InnoDB detects the deadlock and rolls B back entirely.* ```transcript B> UPDATE doctors SET on_call = false WHERE name = 'bob'; -- ER_LOCK_DEADLOCK ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction ``` *B's rollback freed the locks; A's update proceeds.* ```transcript ⏵ A resumes: Query OK, 1 row affected A> COMMIT; Query OK A> SELECT count(*) AS on_call FROM doctors WHERE on_call; -- the invariant survived on_call --------- 1 (1 row) ``` *B starts a fresh SERIALIZABLE transaction and repeats the count. With only one doctor remaining, the application declines the update.* ```transcript B> SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; Query OK B> BEGIN; Query OK B> SELECT count(*) AS on_call FROM doctors WHERE on_call; on_call --------- 1 (1 row) B> COMMIT; Query OK A> SELECT name, on_call FROM doctors ORDER BY name; name | on_call -------+--------- alice | 0 bob | 1 (2 rows) ``` *A standalone SERIALIZABLE SELECT with autocommit=1 is a nonlocking consistent read here.* ```transcript A> SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE; Query OK A> SELECT @@autocommit AS autocommit; autocommit ------------ 1 (1 row) B> BEGIN; Query OK B> UPDATE doctors SET on_call = false WHERE name = 'bob'; Query OK, 1 row affected A> SELECT count(*) AS on_call FROM doctors WHERE on_call; on_call --------- 1 (1 row) ``` *With autocommit=0, A's SERIALIZABLE SELECT instead waits for B's row lock.* ```transcript A> SET autocommit = 0; Query OK A> SELECT count(*) AS on_call FROM doctors WHERE on_call; ⏳ A is waiting for a lock… B> ROLLBACK; Query OK ⏵ A resumes: on_call --------- 1 (1 row) A> ROLLBACK; Query OK A> SET autocommit = 1; Query OK ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/02-isolation/write-skew-serializable.yaml) ## mysql/03-locking/alter-table-outage.yaml - engine: mysql (MySQL 8.4.11) - claim: In this MySQL 8.4 InnoDB schedule, ALTER TABLE waits for A's transaction-held metadata lock, and C's later SELECT waits too. Both complete after A commits. ```timeline A: SELECT (a long-lived transaction) B: ALTER TABLE … ADD COLUMN → ⏳ waits C: SELECT — just a read! → ⏳ waits A: COMMIT B: ⏵ ALTER TABLE … ADD COLUMN → completes C: ⏵ SELECT — just a read! → completes ``` *A is any long-lived transaction that has touched the table — a report, a stuck job…* ```transcript A> BEGIN; Query OK A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) ``` *The migration needs an exclusive metadata lock, so it waits for A. Expected. But now —* ```transcript B> ALTER TABLE accounts ADD COLUMN note varchar(50); ⏳ B is waiting for a lock… ``` *C's new SELECT queues behind the waiting ALTER in this schedule.* ```transcript C> SELECT balance FROM accounts WHERE id = 1; ⏳ C is waiting for a lock… M> SELECT state, info FROM performance_schema.processlist WHERE state = 'Waiting for table metadata lock' ORDER BY info; state | info ---------------------------------+-------------------------------------------------- Waiting for table metadata lock | ALTER TABLE accounts ADD COLUMN note varchar(50) Waiting for table metadata lock | SELECT balance FROM accounts WHERE id = 1 (2 rows) ``` *Only when A ends does the pile-up drain — migration first, then the reads.* ```transcript A> COMMIT; Query OK ⏵ B resumes: Query OK ⏵ C resumes: balance --------- 100 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/03-locking/alter-table-outage.yaml) ## mysql/03-locking/ddl-lock-timeout.yaml - engine: mysql (MySQL 8.4.11) - claim: With lock_wait_timeout = 1, this ALTER TABLE fails with errno 1205 while A retains its metadata lock. After that failure C can read, and a retry succeeds after A commits. Queries during the DDL wait are not tested. ```transcript A> BEGIN; Query OK A> SELECT balance FROM accounts WHERE id = 1; -- the same long transaction as before balance --------- 100 (1 row) ``` *Same migration — but this time it gives up after a second instead of camping in the queue.* ```transcript B> SET SESSION lock_wait_timeout = 1; Query OK B> ALTER TABLE accounts ADD COLUMN note varchar(50); -- ER_LOCK_WAIT_TIMEOUT ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction ``` *After the ALTER times out, C reads successfully while A remains open.* ```transcript C> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) A> COMMIT; Query OK ``` *Retry the migration when it can actually get the lock — now it sails through.* ```transcript B> ALTER TABLE accounts ADD COLUMN note varchar(50); Query OK ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/03-locking/ddl-lock-timeout.yaml) ## mysql/03-locking/deadlock-avoidance.yaml - engine: mysql (MySQL 8.4.11) - claim: In this two-row primary-key schedule, acquiring both rows in id order makes B wait for A; both opposite-direction transfers then commit with the expected balances. This does not prove deadlock freedom for other access paths. ```timeline A: locks id 1,2 (ordered) B: same lock request → ⏳ waits A: COMMIT B: ⏵ same lock request → completes ``` *Both transfers grab *all* their row locks up front, ordered by id.* ```transcript A> BEGIN; Query OK A> SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE; id ---- 1 2 (2 rows) B> BEGIN; Query OK B> SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE; ⏳ B is waiting for a lock… ``` *In this schedule B waits before holding any record lock A needs.* ```transcript A> UPDATE accounts SET balance = balance - 10 WHERE id = 1; Query OK, 1 row affected A> UPDATE accounts SET balance = balance + 10 WHERE id = 2; Query OK, 1 row affected A> COMMIT; Query OK ⏵ B resumes: id ---- 1 2 (2 rows) B> UPDATE accounts SET balance = balance - 25 WHERE id = 2; Query OK, 1 row affected B> UPDATE accounts SET balance = balance + 25 WHERE id = 1; Query OK, 1 row affected B> COMMIT; Query OK A> SELECT owner, balance FROM accounts ORDER BY id; -- both transfers landed — same workload, zero deadlocks owner | balance -------+--------- alice | 115 bob | 85 (2 rows) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/03-locking/deadlock-avoidance.yaml) ## mysql/03-locking/deadlock.yaml - engine: mysql (MySQL 8.4.11) - claim: With MySQL 8.4 InnoDB deadlock detection enabled, these opposite-order updates form a cycle. B receives errno 1213, its earlier debit is rolled back, and A commits with balances 90 and 110. Detection latency is not measured. ```timeline A: locks alice (id=1) B: locks bob (id=2) A: needs bob (id=2) → ⏳ waits B: needs alice (id=1) ← 1213 Deadlock found when trying to get lock A: ⏵ needs bob (id=2) → completes ``` *A transfers 10 from alice to bob; B transfers 25 from bob to alice.* ```transcript A> BEGIN; Query OK A> UPDATE accounts SET balance = balance - 10 WHERE id = 1; -- A locks alice Query OK, 1 row affected B> BEGIN; Query OK B> UPDATE accounts SET balance = balance - 25 WHERE id = 2; -- B locks bob Query OK, 1 row affected ``` *A now needs bob's row (B has it) — it waits.* ```transcript A> UPDATE accounts SET balance = balance + 10 WHERE id = 2; ⏳ A is waiting for a lock… ``` *B now needs alice's row (A has it). A waits for B, B waits for A: a cycle.* ```transcript B> UPDATE accounts SET balance = balance + 25 WHERE id = 1; -- ER_LOCK_DEADLOCK — B's whole transaction is rolled back… ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction ``` *The victim's abort frees bob's row, so A's stuck UPDATE completes.* ```transcript ⏵ A resumes: Query OK, 1 row affected A> COMMIT; Query OK A> SELECT owner, balance FROM accounts ORDER BY id; -- A's transfer survived; B's evaporated — retry it owner | balance -------+--------- alice | 90 bob | 110 (2 rows) ``` *Unlike a row-lock timeout with innodb_rollback_on_timeout=OFF, this deadlock rolls back B's entire transaction — there is nothing left to ROLLBACK.* Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/03-locking/deadlock.yaml) ## mysql/03-locking/fk-shared-lock.yaml - engine: mysql (MySQL 8.4.11) - claim: For this MySQL 8.4 InnoDB table-level foreign key with the default RESTRICT action, a child INSERT makes a parent non-key UPDATE wait until commit. The later parent DELETE fails with errno 1451. The shared parent-record lock mechanism is documented in the MySQL manual, not inspected here. ```timeline A: INSERT child (S-locks parent) B: UPDATE parent balance → ⏳ waits A: COMMIT — releases S lock B: ⏵ UPDATE parent balance → completes B: DELETE parent ← 1451 Cannot delete or update a parent row: a foreign key constraint fails (`app`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`)) ``` ```transcript A> BEGIN; Query OK A> INSERT INTO orders VALUES (1, 1); -- FK check takes an S lock on customers row 1 Query OK, 1 row affected ``` *InnoDB has no key-share granularity: B's harmless balance update needs an X lock and waits.* ```transcript B> UPDATE customers SET balance = 50 WHERE id = 1; ⏳ B is waiting for a lock… A> COMMIT; Query OK ⏵ B resumes: Query OK, 1 row affected ``` *With this RESTRICT foreign key and committed child, the parent DELETE fails with 1451.* ```transcript B> DELETE FROM customers WHERE id = 1; -- ER_ROW_IS_REFERENCED_2 ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`app`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`)) B> SELECT balance FROM customers WHERE id = 1; -- the parent survived, with B's update applied after the wait balance --------- 50 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/03-locking/fk-shared-lock.yaml) ## mysql/03-locking/for-update-blocks.yaml - engine: mysql (MySQL 8.4.11) - claim: At MySQL 8.4 InnoDB REPEATABLE READ, A's FOR UPDATE on an existing PRIMARY key does not prevent B's consistent SELECT, but B's UPDATE waits. After A commits 150, B's decrement produces 140. Locking readers have different rules. ```timeline A: SELECT … FOR UPDATE (locks the row) B: consistent SELECT balance → 100 B: UPDATE -10 → ⏳ waits A: COMMIT (releases the lock) B: ⏵ UPDATE -10 → completes ``` ```transcript A> BEGIN; Query OK A> SELECT * FROM accounts WHERE id = 1 FOR UPDATE; id | owner | balance ----+-------+--------- 1 | alice | 100 (1 row) ``` *B's consistent SELECT does not request a record lock and completes while A holds its lock.* ```transcript B> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) ``` *Writing to it is another story: B's UPDATE must wait for A.* ```transcript B> UPDATE accounts SET balance = balance - 10 WHERE id = 1; ⏳ B is waiting for a lock… A> UPDATE accounts SET balance = 150 WHERE id = 1; Query OK, 1 row affected A> COMMIT; -- releases the row lock Query OK ⏵ B resumes: Query OK, 1 row affected B> SELECT balance FROM accounts WHERE id = 1; -- B's -10 applied on top of A's committed 150 balance --------- 140 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/03-locking/for-update-blocks.yaml) ## mysql/03-locking/gap-locks.yaml - engine: mysql (MySQL 8.4.11) - claim: On MySQL 8.4 InnoDB, the demonstrated PRIMARY-index range read at REPEATABLE READ makes insertion of slot 15 wait with X,GAP,INSERT_INTENTION. At READ COMMITTED the later insertion of 17 completes before A commits. Other queries, indexes, and constraint checks can have different coverage. ```timeline A: SELECT 10–20 FOR UPDATE B: INSERT slot 15 → ⏳ waits A: waiting lock is X,GAP,INSERT_INTENTION A: COMMIT — gap opens B: ⏵ INSERT slot 15 → completes A: same read, READ COMMITTED B: INSERT slot 17 — no wait ``` *A runs the classic "hold the range while I decide" query. Slots 10 and 20 exist; 11–19 is a gap — nothing there to lock. Or is there?* ```transcript A> BEGIN; Query OK A> SELECT slot FROM bookings WHERE slot BETWEEN 10 AND 20 FOR UPDATE; slot ------ 10 20 (2 rows) ``` *B books slot 15. No such row exists — yet the INSERT blocks.* ```transcript B> BEGIN; Query OK B> INSERT INTO bookings VALUES (15, 'mallory'); ⏳ B is waiting for a lock… A> SELECT lock_mode FROM performance_schema.data_locks WHERE object_name = 'bookings' AND lock_status = 'WAITING'; -- B waits for an insert-intention lock on the gap A's range scan locked lock_mode ------------------------ X,GAP,INSERT_INTENTION (1 row) A> COMMIT; -- the gap opens Query OK ⏵ B resumes: Query OK, 1 row affected B> COMMIT; Query OK ``` *Same story at READ COMMITTED: the locking read locks only the three rows it found — the gaps stay free.* ```transcript A> SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; Query OK A> BEGIN; Query OK A> SELECT slot FROM bookings WHERE slot BETWEEN 10 AND 20 FOR UPDATE; slot ------ 10 15 20 (3 rows) B> INSERT INTO bookings VALUES (17, 'trent'); -- straight through — no gap lock to wait on Query OK, 1 row affected A> COMMIT; Query OK A> SELECT slot FROM bookings ORDER BY slot; slot ------ 10 15 17 20 30 (5 rows) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/03-locking/gap-locks.yaml) ## mysql/03-locking/lock-mode-matrix.yaml - engine: mysql (MySQL 8.4.11) - claim: On this existing MySQL 8.4 InnoDB PRIMARY record, two FOR SHARE reads coexist; an UPDATE waits for FOR SHARE, and FOR SHARE waits for an UPDATE. The documented S/X record-lock matrix does not describe gap locks or nonlocking consistent reads. ```timeline A: FOR SHARE (S) B: FOR SHARE (S) — coexists B: UPDATE (X) — needs the row → ⏳ waits A: COMMIT B: ⏵ UPDATE (X) — needs the row → completes A: UPDATE (X) B: FOR SHARE (S) — vs X → ⏳ waits A: COMMIT B: ⏵ FOR SHARE (S) — vs X → completes ``` *Two FOR SHARE locks on the same row coexist happily…* ```transcript A> BEGIN; Query OK A> SELECT id FROM accounts WHERE id = 1 FOR SHARE; id ---- 1 (1 row) B> BEGIN; Query OK B> SELECT id FROM accounts WHERE id = 1 FOR SHARE; id ---- 1 (1 row) B> COMMIT; Query OK ``` *…but a FOR SHARE still blocks a plain UPDATE (which needs an X lock).* ```transcript B> UPDATE accounts SET balance = 200 WHERE id = 1; ⏳ B is waiting for a lock… A> COMMIT; Query OK ⏵ B resumes: Query OK, 1 row affected ``` *An X record lock conflicts with FOR SHARE's S request; this locking reader waits.* ```transcript A> BEGIN; Query OK A> UPDATE accounts SET balance = 300 WHERE id = 1; Query OK, 1 row affected B> SELECT id FROM accounts WHERE id = 1 FOR SHARE; ⏳ B is waiting for a lock… A> COMMIT; Query OK ⏵ B resumes: id ---- 1 (1 row) ``` *The S/X record-lock contract is documented in the MySQL 8.4 locking manual; gap locks have different compatibility.* Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/03-locking/lock-mode-matrix.yaml) ## mysql/03-locking/lock-queue.yaml - engine: mysql (MySQL 8.4.11) - claim: In this MySQL 8.4 InnoDB primary-key schedule, B and C wait for A's lock; sys.innodb_lock_waits identifies B's blocker. Both queued updates complete after A commits, giving balance 211. Grant order and general eventual completion are not asserted. ```timeline A: UPDATE +1 (takes the row lock) B: UPDATE +10 → ⏳ waits M: who's waiting? → B blocked by A C: UPDATE +100 → ⏳ waits A: COMMIT → waiters drain B: ⏵ UPDATE +10 → completes C: ⏵ UPDATE +100 → completes ``` ```transcript A> BEGIN; Query OK A> UPDATE accounts SET balance = balance + 1 WHERE id = 1; Query OK, 1 row affected B> UPDATE accounts SET balance = balance + 10 WHERE id = 1; ⏳ B is waiting for a lock… ``` *A fourth session, M, can watch the wait live.* ```transcript M> SELECT waiting_pid, blocking_pid FROM sys.innodb_lock_waits; waiting_pid | blocking_pid -------------+-------------- pid(B) | pid(A) (1 row) C> UPDATE accounts SET balance = balance + 100 WHERE id = 1; ⏳ C is waiting for a lock… ``` *A commits — the waiters drain. (InnoDB's CATS scheduler does not promise strict FIFO order; this run checks both completions, not their order.)* ```transcript A> COMMIT; Query OK ⏵ B resumes: Query OK, 1 row affected ⏵ C resumes: Query OK, 1 row affected C> SELECT balance FROM accounts WHERE id = 1; -- 100 + 1 + 10 + 100 — nothing was lost in the pile-up balance --------- 211 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/03-locking/lock-queue.yaml) ## mysql/03-locking/lock-timeout.yaml - engine: mysql (MySQL 8.4.11) - claim: With innodb_lock_wait_timeout set, a statement waits for a row lock only that long, then fails with errno 1205 — only the statement is rolled back, the explicit transaction survives when innodb_rollback_on_timeout is OFF; its earlier change and record lock remain until ROLLBACK. ```timeline A: UPDATE (holds row lock) B: UPDATE — waits 1s ← 1205 Lock wait timeout exceeded A: COMMIT B: retry UPDATE → 300 ``` ```transcript A> BEGIN; Query OK A> UPDATE accounts SET balance = 200 WHERE id = 1; Query OK, 1 row affected B> SET SESSION innodb_lock_wait_timeout = 1; Query OK B> SELECT @@innodb_rollback_on_timeout AS rollback_on_timeout; rollback_on_timeout --------------------- 0 (1 row) B> BEGIN; Query OK B> UPDATE accounts SET balance = 125 WHERE id = 2; Query OK, 1 row affected ``` *B queues for the row lock like anyone else — but gives up after a second.* ```transcript B> UPDATE accounts SET balance = 300 WHERE id = 1; -- ER_LOCK_WAIT_TIMEOUT, raised after the timeout ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction ``` *B's earlier change survives, and C still waits for B's lock on bob.* ```transcript B> SELECT balance FROM accounts WHERE id = 2; balance --------- 125 (1 row) C> UPDATE accounts SET balance = balance + 1 WHERE id = 2; ⏳ C is waiting for a lock… B> ROLLBACK; Query OK ⏵ C resumes: Query OK, 1 row affected C> SELECT balance FROM accounts WHERE id = 2; balance --------- 101 (1 row) ``` *After A commits, B can retry the failed update as a new autocommit statement.* ```transcript A> COMMIT; Query OK B> UPDATE accounts SET balance = 300 WHERE id = 1; Query OK, 1 row affected B> SELECT balance FROM accounts WHERE id = 1; balance --------- 300 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/03-locking/lock-timeout.yaml) ## mysql/03-locking/monitoring-locks.yaml - engine: mysql (MySQL 8.4.11) - claim: For this MySQL 8.4 InnoDB existing-primary-key UPDATE, data_locks shows a granted table IX lock and X,REC_NOT_GAP record lock, then B's WAITING record request. sys.innodb_lock_waits identifies A as B's blocker. This is not a count of every lock type or every UPDATE access path. ```transcript A> BEGIN; Query OK A> UPDATE accounts SET balance = 200 WHERE id = 1; Query OK, 1 row affected ``` *This existing PRIMARY-key UPDATE shows a table IX lock and an exclusive record lock.* ```transcript M> SELECT object_name, index_name, lock_type, lock_mode, lock_status, lock_data FROM performance_schema.data_locks WHERE object_schema = DATABASE() AND object_name = 'accounts' ORDER BY lock_type DESC; object_name | index_name | lock_type | lock_mode | lock_status | lock_data -------------+------------+-----------+---------------+-------------+----------- accounts | | TABLE | IX | GRANTED | accounts | PRIMARY | RECORD | X,REC_NOT_GAP | GRANTED | 1 (2 rows) B> UPDATE accounts SET balance = 300 WHERE id = 1; ⏳ B is waiting for a lock… ``` *The waiter's tell: a record-lock request with lock_status = WAITING.* ```transcript M> SELECT object_name, lock_mode, lock_status, lock_data FROM performance_schema.data_locks WHERE object_schema = DATABASE() AND object_name = 'accounts' AND lock_status = 'WAITING'; object_name | lock_mode | lock_status | lock_data -------------+---------------+-------------+----------- accounts | X,REC_NOT_GAP | WAITING | 1 (1 row) ``` *You rarely need to decode data_locks by hand — sys.innodb_lock_waits names the culprit.* ```transcript M> SELECT waiting_pid, blocking_pid FROM sys.innodb_lock_waits WHERE locked_table_schema = DATABASE() AND locked_table_name = 'accounts'; waiting_pid | blocking_pid -------------+-------------- pid(B) | pid(A) (1 row) A> COMMIT; Query OK ⏵ B resumes: Query OK, 1 row affected ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/03-locking/monitoring-locks.yaml) ## mysql/03-locking/nowait.yaml - engine: mysql (MySQL 8.4.11) - claim: For this locked MySQL 8.4 InnoDB primary-key row, FOR UPDATE NOWAIT returns errno 3572; the same query succeeds after A commits. The row-lock NOWAIT contract does not exclude metadata-lock waits or measure total latency. ```transcript A> BEGIN; Query OK A> SELECT id FROM accounts WHERE id = 1 FOR UPDATE; id ---- 1 (1 row) B> SELECT id FROM accounts WHERE id = 1 FOR UPDATE NOWAIT; -- ER_LOCK_NOWAIT, no wait for this record lock ERROR 3572 (HY000): Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set. ``` *Once A is done, the same statement succeeds.* ```transcript A> COMMIT; Query OK B> SELECT id FROM accounts WHERE id = 1 FOR UPDATE NOWAIT; id ---- 1 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/03-locking/nowait.yaml) ## mysql/03-locking/skip-locked.yaml - engine: mysql (MySQL 8.4.11) - claim: In this MySQL 8.4 InnoDB schedule, FOR UPDATE SKIP LOCKED selects different available job rows for A, B, and C; D finds none, then can select job 1 after A rolls back. This tests row selection and explicit rollback, not worker crashes or duplicate-free external execution. ```timeline A: grabs job 1 B: job 1 taken → grabs job 2 C: grabs job 3 D: no available row → nothing A: ROLLBACK → job 1 lock released D: grabs job 1 ``` *Four sessions issue the same query in the order shown, with A, B, and C retaining their locks.* ```transcript A> BEGIN; Query OK A> SELECT * FROM jobs ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | task ----+------------ 1 | send email (1 row) B> BEGIN; Query OK B> SELECT * FROM jobs ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; -- job 1 is locked by A — skipped, no waiting id | task ----+-------------- 2 | resize image (1 row) C> BEGIN; Query OK C> SELECT * FROM jobs ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | task ----+-------------- 3 | build report (1 row) ``` *D finds no available row; the table still contains the locked jobs.* ```transcript D> SELECT * FROM jobs ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; Empty set ``` *A explicitly rolls back, releasing its job-row lock. No crash is injected.* ```transcript A> ROLLBACK; Query OK D> SELECT * FROM jobs ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | task ----+------------ 1 | send email (1 row) B> COMMIT; Query OK C> COMMIT; Query OK ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/03-locking/skip-locked.yaml) ## mysql/04-mvcc/history-list-length.yaml - engine: mysql (MySQL 8.4.11) - claim: On MySQL 8.4 InnoDB, R retains a REPEATABLE READ view at v=0 while 200 single-row UPDATE transactions commit. The history-list counter is at least 200 and R still reads zero. The run does not measure retained bytes, an exact counter delta, or purge completion after R commits. ```timeline R: read view opens A: 200 commits pile up undo A: history_len ≥ 200 — pinned R: R still sees v=0 R: COMMIT → purge can drain it ``` *R opens a read view — and then does nothing.* ```transcript R> BEGIN; Query OK R> SELECT v FROM counters; v --- 0 (1 row) ``` *Meanwhile the application hums along: 200 small transactions, each updating one row and committing. Every one of them must keep its undo — R's old read view prevents purge from advancing past the retained history.* ```transcript A> CALL bump(200); -- 200 committed single-row updates Query OK A> SELECT count >= 200 AS pinned_by_reader FROM information_schema.INNODB_METRICS WHERE name = 'trx_rseg_history_len'; -- the history-list counter is at least 200 while R retains its view pinned_by_reader ------------------ 1 (1 row) R> SELECT v FROM counters; -- R still reads its original world — that's what all that undo buys v --- 0 (1 row) R> COMMIT; Query OK ``` *R's commit removes its read-view retention requirement. Background purge and other readers determine later cleanup; this run does not wait for or assert history-list drainage.* Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/04-mvcc/history-list-length.yaml) ## mysql/04-mvcc/read-views.yaml - engine: mysql (MySQL 8.4.11) - claim: At MySQL 8.4 InnoDB REPEATABLE READ, R sees a commit after BEGIN but before its first consistent read. WITH CONSISTENT SNAPSHOT instead retains the start-time balance. This build shows a trx_id above 2^48 before R writes and below it afterward; that threshold is an observation, not an ID-format contract. ```timeline A: UPDATE balance=999 (+ commit) R: first read → 999 (view opens here, not at BEGIN) R: consistent snapshot — view opens now A: UPDATE balance=111 R: read → 999 (snapshot predates it) ``` ```transcript R> BEGIN; Query OK ``` *R has "begun" — but hasn't read anything. A commits a change meanwhile.* ```transcript A> UPDATE accounts SET balance = 999 WHERE id = 1; Query OK, 1 row affected R> SELECT balance FROM accounts WHERE id = 1; -- A's update is visible — the read view was created just now, by this SELECT balance --------- 999 (1 row) R> COMMIT; Query OK ``` *START TRANSACTION WITH CONSISTENT SNAPSHOT moves the snapshot to the start:* ```transcript R> START TRANSACTION WITH CONSISTENT SNAPSHOT; Query OK A> UPDATE accounts SET balance = 111 WHERE id = 1; Query OK, 1 row affected R> SELECT balance FROM accounts WHERE id = 1; -- this time the read view predates A's update balance --------- 999 (1 row) ``` *The documented nonlocking read-only optimization avoids a persistent transaction ID. This build exposes a placeholder above 2^48 for R; that numeric representation is not a public format guarantee.* ```transcript A> SELECT CAST(trx_id AS UNSIGNED) > 281474976710656 AS placeholder_id FROM information_schema.innodb_trx; -- R is the only open transaction; this build reports an ID above 2^48 placeholder_id ---------------- 1 (1 row) R> UPDATE accounts SET balance = balance + 1 WHERE id = 1; -- R's first write… Query OK, 1 row affected A> SELECT CAST(trx_id AS UNSIGNED) > 281474976710656 AS placeholder_id FROM information_schema.innodb_trx; -- after the write, this build reports an ID below 2^48 placeholder_id ---------------- 0 (1 row) R> COMMIT; Query OK ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/04-mvcc/read-views.yaml) ## mysql/04-mvcc/undo-logs.yaml - engine: mysql (MySQL 8.4.11) - claim: At MySQL 8.4 InnoDB REPEATABLE READ, R's earlier read view still returns three rows after A commits their deletion and counts zero. R counts zero after ending its transaction. Undo reconstruction and deferred physical removal are documented mechanisms, not physical-page observations here. ```timeline R: reads 3 rows — snapshot opens A: DELETE all 3 (+ commit) A: table now empty R: still sees 3 rows (from undo) R: COMMIT — snapshot released R: now sees 0 too ``` ```transcript R> BEGIN; Query OK R> SELECT id, balance FROM accounts ORDER BY id; -- the read view opens here id | balance ----+--------- 1 | 100 2 | 200 3 | 300 (3 rows) ``` *A deletes and commits all three rows; its current SELECT counts zero, without inspecting physical storage.* ```transcript A> DELETE FROM accounts; Query OK, 3 rows affected A> SELECT count(*) AS remaining FROM accounts; remaining ----------- 0 (1 row) ``` *R's SELECT still returns three rows. The MySQL multi-versioning manual explains this using undo reconstruction; the SELECT asserts visibility, not a count of internal reconstruction operations.* ```transcript R> SELECT id, balance FROM accounts ORDER BY id; -- the prior read view still returns the original rows id | balance ----+--------- 1 | 100 2 | 200 3 | 300 (3 rows) R> COMMIT; Query OK R> SELECT count(*) AS remaining FROM accounts; -- the read view is gone — and with it, R's claim on that history remaining ----------- 0 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/04-mvcc/undo-logs.yaml) ## mysql/05-patterns/advisory-locks.yaml - engine: mysql (MySQL 8.4.11) - claim: In this cooperative named-lock schedule, B gets 0 with timeouts 0 and 1 while A holds the name, still gets 0 after A commits, then gets 1 after A releases it. B acquires two names and RELEASE_ALL_LOCKS reports 2. ```timeline A: GET_LOCK → held B: GET_LOCK(0) → 0 (no wait) B: GET_LOCK(1s) → 0 (waited) A: COMMIT — releases nothing B: GET_LOCK → 0 (still A's) A: RELEASE_LOCK B: GET_LOCK → held ``` *Two deploy runners must not migrate the same database at once. They agree the name 'migration' means "migration in progress".* ```transcript A> SELECT GET_LOCK('migration', 0) AS got_it; got_it -------- 1 (1 row) B> SELECT GET_LOCK('migration', 0) AS got_it; -- timeout 0 — an instant answer, no waiting got_it -------- 0 (1 row) ``` *A positive timeout waits, but only that long. B gives it one second:* ```transcript B> SELECT GET_LOCK('migration', 1) AS got_it; -- A still holds it — B gets 0 after the deadline instead of an error got_it -------- 0 (1 row) B> SELECT IS_FREE_LOCK('migration') AS free; -- you can ask without trying to take it free ------ 0 (1 row) ``` *Advisory locks ignore transaction boundaries entirely — COMMIT releases nothing.* ```transcript A> BEGIN; Query OK A> COMMIT; Query OK B> SELECT GET_LOCK('migration', 0) AS got_it; -- A's COMMIT changed nothing — the lock belongs to A's SESSION got_it -------- 0 (1 row) A> SELECT RELEASE_LOCK('migration') AS released; released ---------- 1 (1 row) B> SELECT GET_LOCK('migration', 0) AS got_it; -- now B is the migration runner got_it -------- 1 (1 row) ``` *B acquires a second name, then RELEASE_ALL_LOCKS releases both. Session termination is a documented release path, not executed here.* ```transcript B> SELECT GET_LOCK('cache-rebuild', 0) AS got_it; got_it -------- 1 (1 row) B> SELECT RELEASE_ALL_LOCKS() AS released; released ---------- 2 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/05-patterns/advisory-locks.yaml) ## mysql/05-patterns/check-then-insert-race.yaml - engine: mysql (MySQL 8.4.11) - claim: At InnoDB's default REPEATABLE READ, these two plain checks both see 0 rows. With no unique constraint, both inserts commit and the final count for the email is 2. ```timeline A: any bob? → 0 B: any bob? → 0 A: INSERT bob A: COMMIT B: INSERT bob (check already passed) B: COMMIT A: count bobs → 2 — the "impossible" duplicate ``` *The same person double-clicks 'Sign up'. Two app servers each run: check, then insert.* ```transcript A> BEGIN; Query OK A> SELECT count(*) AS existing FROM signups WHERE email = 'bob@example.com'; existing ---------- 0 (1 row) B> BEGIN; Query OK B> SELECT count(*) AS existing FROM signups WHERE email = 'bob@example.com'; -- B's check also passes — A hasn't committed anything existing ---------- 0 (1 row) ``` *Both checks passed, so both insert. Nothing blocks, nothing errors.* ```transcript A> INSERT INTO signups (email) VALUES ('bob@example.com'); Query OK, 1 row affected A> COMMIT; Query OK B> INSERT INTO signups (email) VALUES ('bob@example.com'); Query OK, 1 row affected B> COMMIT; Query OK A> SELECT count(*) AS bobs FROM signups WHERE email = 'bob@example.com'; -- the "impossible" duplicate bobs ------ 2 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/05-patterns/check-then-insert-race.yaml) ## mysql/05-patterns/checked-stock.yaml - engine: mysql (MySQL 8.4.11) - claim: Two buyers each request four of five units. B waits for A; after A commits, B's checked decrement affects zero rows and B rolls back. One unit remains. A subsequent unguarded decrement leaves minus three. ```transcript A> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; Query OK B> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; Query OK A> BEGIN; Query OK B> BEGIN; Query OK A> UPDATE stock SET quantity = quantity - 4 WHERE id = 1 AND quantity >= 4; Query OK, 1 row affected B> UPDATE stock SET quantity = quantity - 4 WHERE id = 1 AND quantity >= 4; ⏳ B is waiting for a lock… A> COMMIT; Query OK ⏵ B resumes: Query OK, 0 rows affected B> ROLLBACK; Query OK A> SELECT quantity FROM stock WHERE id = 1; quantity ---------- 1 (1 row) ``` *Contrast an unconditional decrement after the checked rejection. This deliberately breaks the stock rule.* ```transcript B> BEGIN; Query OK B> UPDATE stock SET quantity = quantity - 4 WHERE id = 1; Query OK, 1 row affected B> COMMIT; Query OK A> SELECT quantity FROM stock WHERE id = 1; quantity ---------- -3 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/05-patterns/checked-stock.yaml) ## mysql/05-patterns/fix-lost-update-atomic.yaml - engine: mysql (MySQL 8.4.11) - claim: In this single-row InnoDB REPEATABLE READ schedule, the second arithmetic UPDATE waits for the first writer's commit and computes from 110; both deposits survive with a final balance of 120. *Same two +10 deposits that lost an update in chapter 2 — but the math moved into the UPDATE itself.* ```transcript A> BEGIN; Query OK A> UPDATE accounts SET balance = balance + 10 WHERE id = 1; Query OK, 1 row affected A> SELECT balance FROM accounts WHERE id = 1; balance --------- 110 (1 row) B> BEGIN; Query OK B> UPDATE accounts SET balance = balance + 10 WHERE id = 1; ⏳ B is waiting for a lock… ``` *No stale read exists to write back: B waits for A's row lock, then computes from the committed 110.* ```transcript A> COMMIT; Query OK ⏵ B resumes: Query OK, 1 row affected B> SELECT balance FROM accounts WHERE id = 1; balance --------- 120 (1 row) B> COMMIT; Query OK A> SELECT balance FROM accounts WHERE id = 1; -- both deposits survived balance --------- 120 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/05-patterns/fix-lost-update-atomic.yaml) ## mysql/05-patterns/fix-lost-update-for-update.yaml - engine: mysql (MySQL 8.4.11) - claim: In this single-row InnoDB REPEATABLE READ schedule, both writers use SELECT ... FOR UPDATE inside their transactions. B waits, reads 110 after A commits, and the final balance is 120. *The app must apply business rules to the balance in code — so it locks the row while it reads.* ```transcript A> BEGIN; Query OK A> SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; balance --------- 100 (1 row) B> BEGIN; Query OK B> SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; ⏳ B is waiting for a lock… A> UPDATE accounts SET balance = 100 + 10 WHERE id = 1; Query OK, 1 row affected A> COMMIT; Query OK ``` *B's locking read waited for A's commit and returns 110. No prior plain-read snapshot is established for B here.* ```transcript ⏵ B resumes: balance --------- 110 (1 row) B> UPDATE accounts SET balance = 110 + 10 WHERE id = 1; Query OK, 1 row affected B> COMMIT; Query OK A> SELECT balance FROM accounts WHERE id = 1; -- both deposits survived balance --------- 120 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/05-patterns/fix-lost-update-for-update.yaml) ## mysql/05-patterns/fix-lost-update-version-column.yaml - engine: mysql (MySQL 8.4.11) - claim: In this InnoDB REPEATABLE READ schedule, B's stale version predicate affects 0 rows. B rolls back and retries from version 2 in a fresh transaction; the final balance is 120 and version is 3. *Both sessions read balance and version without a locking read. The UPDATEs still acquire write locks.* ```transcript A> BEGIN; Query OK A> SELECT balance, version FROM accounts WHERE id = 1; balance | version ---------+--------- 100 | 1 (1 row) B> BEGIN; Query OK B> SELECT balance, version FROM accounts WHERE id = 1; balance | version ---------+--------- 100 | 1 (1 row) ``` *Every write bumps the version and only matches the version it read.* ```transcript A> UPDATE accounts SET balance = 100 + 10, version = version + 1 WHERE id = 1 AND version = 1; Query OK, 1 row affected A> COMMIT; Query OK B> UPDATE accounts SET balance = 100 + 10, version = version + 1 WHERE id = 1 AND version = 1; -- 0 rows matched — the row moved on; B's deposit did NOT silently vanish Query OK, 0 rows affected ``` *Zero affected rows is the signal to retry: roll back, re-read, write against the new version.* ```transcript B> ROLLBACK; Query OK B> BEGIN; Query OK B> SELECT balance, version FROM accounts WHERE id = 1; balance | version ---------+--------- 110 | 2 (1 row) B> UPDATE accounts SET balance = 110 + 10, version = version + 1 WHERE id = 1 AND version = 2; Query OK, 1 row affected B> COMMIT; Query OK A> SELECT balance, version FROM accounts WHERE id = 1; -- both deposits survived balance | version ---------+--------- 120 | 3 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/05-patterns/fix-lost-update-version-column.yaml) ## mysql/05-patterns/idempotency-key.yaml - engine: mysql (MySQL 8.4.11) - claim: With retained primary keys and CLIENT_FOUND_ROWS absent, a committed duplicate and an in-flight duplicate each affect 0 rows after the original commits. The asserted balances show one database charge for each of the two keys; network response loss and remote charges are not executed. *The client sends 'charge $30' with idempotency key req-42. Server A processes it.* ```transcript A> BEGIN; Query OK A> INSERT INTO payments VALUES ('req-42', 30) ON DUPLICATE KEY UPDATE amount = amount; -- 1 row inserted: this key is new — do the work Query OK, 1 row affected A> UPDATE accounts SET balance = balance - 30 WHERE id = 1; Query OK, 1 row affected A> COMMIT; Query OK ``` *Model a same-key retry after commit. No network failure or application response is executed; B reads the stored amount.* ```transcript B> BEGIN; Query OK B> INSERT INTO payments VALUES ('req-42', 30) ON DUPLICATE KEY UPDATE amount = amount; -- 0 rows: existing key, skip the balance update; the next SELECT reads the stored amount Query OK, 0 rows affected B> SELECT amount FROM payments WHERE idempotency_key = 'req-42'; amount -------- 30 (1 row) B> COMMIT; Query OK A> SELECT balance FROM accounts WHERE id = 1; -- charged exactly once balance --------- 70 (1 row) ``` *The nasty case: the retry arrives while the original is still in flight, uncommitted.* ```transcript A> BEGIN; Query OK A> INSERT INTO payments VALUES ('req-99', 25) ON DUPLICATE KEY UPDATE amount = amount; Query OK, 1 row affected A> UPDATE accounts SET balance = balance - 25 WHERE id = 1; Query OK, 1 row affected B> INSERT INTO payments VALUES ('req-99', 25) ON DUPLICATE KEY UPDATE amount = amount; ⏳ B is waiting for a lock… ``` *The unique index parks the retry until the original decides. A commits — the retry absorbs to 0 rows.* ```transcript A> COMMIT; Query OK ⏵ B resumes: Query OK, 0 rows affected ``` *This in-flight duplicate affects 0 rows after A commits. No additional balance update is issued.* ```transcript A> SELECT balance FROM accounts WHERE id = 1; -- 100 - 30 - 25: every charge applied exactly once balance --------- 45 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/05-patterns/idempotency-key.yaml) ## mysql/05-patterns/implicit-commit.yaml - engine: mysql (MySQL 8.4.11) - claim: This CREATE INDEX implicitly commits the preceding InnoDB INSERT: B sees the order before A issues COMMIT, and a later ROLLBACK leaves it visible. This is one listed implicit-commit statement, not every kind of DDL. *A migration script wraps its work in a transaction, believing that makes it atomic: insert data, add an index, and if anything fails — roll back.* ```transcript A> BEGIN; Query OK A> INSERT INTO orders VALUES (1, 'draft'); Query OK, 1 row affected B> SELECT count(*) AS visible FROM orders; -- uncommitted, invisible — so far so good visible --------- 0 (1 row) A> CREATE INDEX idx_orders_state ON orders (state); -- DDL — and an implicit COMMIT, right here Query OK B> SELECT count(*) AS visible FROM orders; -- A never said COMMIT. The CREATE INDEX did. visible --------- 1 (1 row) ``` *A now explicitly rolls back. No migration exception is injected.* ```transcript A> ROLLBACK; Query OK B> SELECT count(*) AS visible FROM orders; -- rolled back nothing — the INSERT was already committed visible --------- 1 (1 row) ``` *CREATE INDEX has already committed the INSERT. Check the manual's implicit-commit list and exceptions before relying on a migration wrapper; this schedule does not execute every DDL statement.* Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/05-patterns/implicit-commit.yaml) ## mysql/05-patterns/job-queue.yaml - engine: mysql (MySQL 8.4.11) - claim: In this InnoDB schedule, B skips A's locked job and selects job 2. After an explicit rollback, B can select job 2 again; both database job states finish as done. No external work or process crash is executed. ```timeline A: claim → job 1 B: claim → job 2 (skips locked job 1) A: job 1 done A: COMMIT B: ROLLBACK → job 2 available B: claim → job 2 (back in queue) B: job 2 done B: COMMIT A: both jobs done ``` *Two sessions select the lowest available queued id under a row lock. Only database job-state changes are executed.* ```transcript A> BEGIN; Query OK A> SELECT id, task FROM jobs WHERE state = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | task ----+-------------------- 1 | send welcome email (1 row) B> BEGIN; Query OK B> SELECT id, task FROM jobs WHERE state = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; -- job 1 is claimed — skipped without waiting id | task ----+------------------ 2 | generate invoice (1 row) ``` *A marks job 1 done and commits. B explicitly rolls back, releasing its claim on job 2.* ```transcript A> UPDATE jobs SET state = 'done' WHERE id = 1; Query OK, 1 row affected A> COMMIT; Query OK B> ROLLBACK; Query OK ``` *B starts a new transaction and selects job 2 again. No restarted process or external task execution is observed.* ```transcript B> BEGIN; Query OK B> SELECT id, task FROM jobs WHERE state = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | task ----+------------------ 2 | generate invoice (1 row) B> UPDATE jobs SET state = 'done' WHERE id = 2; Query OK, 1 row affected B> COMMIT; Query OK A> SELECT id, state FROM jobs ORDER BY id; id | state ----+------- 1 | done 2 | done (2 rows) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/05-patterns/job-queue.yaml) ## mysql/05-patterns/on-duplicate-key.yaml - engine: mysql (MySQL 8.4.11) - claim: In this InnoDB schedule, B's duplicate INSERT waits for A's commit, then fails with 1062. A subsequent upsert increments attempts to 2 and reports 2 affected rows; INSERT IGNORE skips the duplicate and reports 0. ```timeline A: INSERT bob B: INSERT bob (duplicate) → ⏳ waits A: COMMIT B: ⏵ INSERT bob (duplicate) ← 1062 Duplicate entry 'bob@example.com' for key 'signups.email' ``` *Same double-click as the previous lesson, but now the table has UNIQUE (email).* ```transcript A> BEGIN; Query OK A> INSERT INTO signups (email) VALUES ('bob@example.com'); Query OK, 1 row affected ``` *B's insert can't decide yet — the winner hasn't committed. It waits on A's transaction.* ```transcript B> INSERT INTO signups (email) VALUES ('bob@example.com'); ⏳ B is waiting for a lock… A> COMMIT; Query OK ⏵ B's blocked statement fails: ERROR 1062 (23000): Duplicate entry 'bob@example.com' for key 'signups.email' ``` *ER_DUP_ENTRY — the race is now loud instead of silent.* *ON DUPLICATE KEY UPDATE makes the duplicate do something useful instead of erroring:* ```transcript B> INSERT INTO signups (email) VALUES ('bob@example.com') ON DUPLICATE KEY UPDATE attempts = attempts + 1; -- affected = 2 is MySQL's way of saying 'existing row updated' Query OK, 2 rows affected B> SELECT email, attempts FROM signups; -- one row, and it counted the duplicate attempt email | attempts -----------------+---------- bob@example.com | 2 (1 row) ``` *INSERT IGNORE skips this duplicate with 0 affected rows. The manual documents other ignorable errors too, not every error. An upsert reacts to any conflicting primary or unique key, not a named conflict target.* ```transcript B> INSERT IGNORE INTO signups (email) VALUES ('bob@example.com'); Query OK, 0 rows affected ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/05-patterns/on-duplicate-key.yaml) ## mysql/05-patterns/retry-deadlocks.ts - engine: mysql (MySQL 8.4.11) - claim: In this forced InnoDB deadlock, B receives 1213 and its transaction rolls back. Replaying both UPDATEs in a new transaction succeeds on attempt 2; the asserted balances are 115 and 85. This does not promise eventual success for every deadlock. ```transcript B> BEGIN; Query OK B> UPDATE accounts SET balance = balance - 25 WHERE id = 2; Query OK, 1 row affected ``` *B holds bob. A locks alice, then wants bob — and blocks. B then wants alice: a cycle.* ```transcript A> BEGIN; Query OK A> UPDATE accounts SET balance = balance - 10 WHERE id = 1; Query OK, 1 row affected A> UPDATE accounts SET balance = balance + 10 WHERE id = 2; ⏳ A is waiting for a lock… B> UPDATE accounts SET balance = balance + 25 WHERE id = 1; ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction ⏵ A resumes: Query OK, 1 row affected A> COMMIT; Query OK B> BEGIN; Query OK B> UPDATE accounts SET balance = balance - 25 WHERE id = 2; Query OK, 1 row affected ``` *Attempt 2 is a brand-new transaction. A is done — B's transfer sails through.* ```transcript B> UPDATE accounts SET balance = balance + 25 WHERE id = 1; Query OK, 1 row affected B> COMMIT; Query OK A> SELECT balance FROM accounts WHERE id = 1; balance --------- 115 (1 row) A> SELECT balance FROM accounts WHERE id = 2; balance --------- 85 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/05-patterns/retry-deadlocks.ts) ## mysql/05-patterns/stale-edit.yaml - engine: mysql (MySQL 8.4.11) - claim: Both editors load version 1 outside their save transactions. A saves version 2. B's version-1 replacement affects zero rows; after rollback a fresh read still returns A's text and version 2. Then blindly using the latest version with B's old draft replaces A's edit. ```transcript A> SELECT body, version FROM documents WHERE id = 1; body | version ----------+--------- Original | 1 (1 row) B> SELECT body, version FROM documents WHERE id = 1; body | version ----------+--------- Original | 1 (1 row) A> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; Query OK B> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; Query OK A> BEGIN; Query OK A> UPDATE documents SET body = 'A edit', version = version + 1 WHERE id = 1 AND version = 1; Query OK, 1 row affected A> COMMIT; Query OK B> BEGIN; Query OK B> UPDATE documents SET body = 'B edit', version = version + 1 WHERE id = 1 AND version = 1; Query OK, 0 rows affected B> ROLLBACK; Query OK B> SELECT body, version FROM documents WHERE id = 1; body | version --------+--------- A edit | 2 (1 row) ``` *Contrast blindly substituting the latest version while keeping B's old draft. This deliberately replaces A's edit.* ```transcript B> BEGIN; Query OK B> UPDATE documents SET body = 'B edit', version = version + 1 WHERE id = 1 AND version = 2; Query OK, 1 row affected B> COMMIT; Query OK A> SELECT body, version FROM documents WHERE id = 1; body | version --------+--------- B edit | 3 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/05-patterns/stale-edit.yaml) ## mysql/06-distributed/dual-write-problem.yaml - engine: mysql (MySQL 8.4.11) - claim: Two modeled failure windows leave mismatched records: a committed order with no stand-in event, then an autocommitted stand-in event whose order fails with 3819. The broker is a local table, not an observed delivery service. *Attempt 1 — write, then publish. The order commits…* ```transcript App> BEGIN; Query OK App> INSERT INTO orders VALUES (1, 'alice', 90); Query OK, 1 row affected App> COMMIT; Query OK ``` *The stand-in publish is omitted after commit. This models a failure window without killing a process.* ```transcript App> SELECT (SELECT count(*) FROM orders) AS orders, (SELECT count(*) FROM broker) AS events; orders | events --------+-------- 1 | 0 (1 row) ``` *Attempt 2 writes a stand-in event in autocommit before attempting the order.* ```transcript App> INSERT INTO broker VALUES ('order_placed: order 2'); Query OK, 1 row affected ``` *The order INSERT fails its CHECK constraint with 3819. No timeout or crash is injected.* ```transcript App> INSERT INTO orders VALUES (2, 'mallory', -5); -- ER_CHECK_CONSTRAINT_VIOLATED ERROR 3819 (HY000): Check constraint 'orders_chk_1' is violated. ``` *The stand-in event exists without order 2. No downstream processing is observed.* ```transcript App> SELECT (SELECT count(*) FROM orders WHERE id = 2) AS orders, (SELECT count(*) FROM broker WHERE event LIKE '%order 2%') AS events; orders | events --------+-------- 0 | 1 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/06-distributed/dual-write-problem.yaml) ## mysql/06-distributed/saga-compensation.yaml - engine: mysql (MySQL 8.4.11) - claim: In this single-database saga model, Reader sees the committed flight reservation between steps. The hotel UPDATE affects 0 rows; a new local compensation restores seats to 5, which Reader observes after commit. *Step 1 — book the flight. A local transaction, committed immediately.* ```transcript Saga> BEGIN; Query OK Saga> UPDATE flights SET seats = seats - 1 WHERE id = 1; Query OK, 1 row affected Saga> SELECT seats FROM flights WHERE id = 1; seats ------- 4 (1 row) Saga> COMMIT; Query OK ``` *This autocommit Reader sees the committed flight reservation between steps. Local transaction isolation still applies.* ```transcript Reader> SELECT seats FROM flights WHERE id = 1; seats ------- 4 (1 row) ``` *Step 2 — book the hotel. No rooms left: the step fails as a business outcome, not an error.* ```transcript Saga> BEGIN; Query OK Saga> UPDATE hotels SET rooms = rooms - 1 WHERE id = 1 AND rooms > 0; -- 0 rows — nothing to book Query OK, 0 rows affected Saga> ROLLBACK; Query OK ``` *Step 1 already committed — there is nothing a ROLLBACK could undo. The saga runs a COMPENSATING transaction: a new forward transaction that reverses the booking.* ```transcript Saga> BEGIN; Query OK Saga> UPDATE flights SET seats = seats + 1 WHERE id = 1; Query OK, 1 row affected Saga> SELECT seats FROM flights WHERE id = 1; seats ------- 5 (1 row) Saga> COMMIT; Query OK Reader> SELECT seats FROM flights WHERE id = 1; seats ------- 5 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/06-distributed/saga-compensation.yaml) ## mysql/06-distributed/transactional-outbox.yaml - engine: mysql (MySQL 8.4.11) - claim: The committed attempt retains both order and outbox row; the rolled-back attempt retains neither. Rolling back the relay's DELETE makes the event selectable again, then a committed DELETE empties the outbox. No external publication, receiver effect, or process crash is executed. *The order and its event are written in ONE transaction — both land in the same database.* ```transcript App> BEGIN; Query OK App> INSERT INTO orders VALUES (1, 'alice', 90); Query OK, 1 row affected App> INSERT INTO outbox (event) VALUES ('order_placed: order 1'); Query OK, 1 row affected App> COMMIT; Query OK App> SELECT id FROM orders ORDER BY id; id ---- 1 (1 row) ``` *The second attempt explicitly rolls back. The next SELECTs assert that only order 1 and its outbox row remain.* ```transcript App> BEGIN; Query OK App> INSERT INTO orders VALUES (2, 'bob', 75); Query OK, 1 row affected App> INSERT INTO outbox (event) VALUES ('order_placed: order 2'); Query OK, 1 row affected App> ROLLBACK; Query OK App> SELECT id FROM orders ORDER BY id; id ---- 1 (1 row) App> SELECT id, event FROM outbox ORDER BY id; id | event ----+----------------------- 1 | order_placed: order 1 (1 row) ``` *A relay claims the event exactly like a chapter-5 job-queue worker…* ```transcript Relay> BEGIN; Query OK Relay> SELECT id, event FROM outbox ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | event ----+----------------------- 1 | order_placed: order 1 (1 row) ``` *The relay deletes the row and explicitly rolls back. Publication is omitted; no HTTP call or crash is executed.* ```transcript Relay> DELETE FROM outbox WHERE id = 1; Query OK, 1 row affected Relay> ROLLBACK; Query OK ``` *The rolled-back DELETE leaves the event available for reselection. A later relay transaction selects and deletes it again. This establishes database reselection, not redelivery to a recipient.* ```transcript Relay> BEGIN; Query OK Relay> SELECT id, event FROM outbox ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | event ----+----------------------- 1 | order_placed: order 1 (1 row) Relay> DELETE FROM outbox WHERE id = 1; Query OK, 1 row affected Relay> COMMIT; Query OK Relay> SELECT count(*) AS pending FROM outbox; pending --------- 0 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/06-distributed/transactional-outbox.yaml) ## mysql/06-distributed/xa-transactions.yaml - engine: mysql (MySQL 8.4.11) - claim: With xa_detach_on_prepare=ON, this prepared InnoDB branch remains in XA RECOVER and blocks B's NOWAIT read before and after A's session is killed. B commits it by XID and reads balance 200. No server restart or multi-resource coordinator is executed. ```transcript A> SET SESSION xa_detach_on_prepare = ON; Query OK A> SELECT @@session.xa_detach_on_prepare AS detached; detached ---------- 1 (1 row) ``` *A is one participant in a distributed transfer. It does its work, then PREPARES — phase one.* ```transcript A> XA START 'transfer-42'; Query OK A> UPDATE accounts SET balance = 200 WHERE id = 1; Query OK, 1 row affected A> XA END 'transfer-42'; Query OK A> XA PREPARE 'transfer-42'; Query OK ``` *XA PREPARE detached the transaction from the session: A itself no longer sees its own change.* ```transcript A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) M> XA RECOVER; formatID | gtrid_length | bqual_length | data ----------+--------------+--------------+------------- 1 | 11 | 0 | transfer-42 (1 row) ``` *The prepared transaction still holds its row locks — with no session attached.* ```transcript B> SELECT balance FROM accounts WHERE id = 1 FOR UPDATE NOWAIT; -- ER_LOCK_NOWAIT ERROR 3572 (HY000): Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set. ``` *M kills participant session A. No Transaction Manager process is modeled.* ```transcript M> CALL kill_session('A'); Query OK A> SELECT 1; ERROR ERR_MYSQL_CONNECTION_CLOSED (HY000): Connection closed ``` *A's session is gone. XA RECOVER still lists the prepared branch and B's NOWAIT read still fails. Server restart is not tested here.* ```transcript M> XA RECOVER; formatID | gtrid_length | bqual_length | data ----------+--------------+--------------+------------- 1 | 11 | 0 | transfer-42 (1 row) B> SELECT balance FROM accounts WHERE id = 1 FOR UPDATE NOWAIT; ERROR 3572 (HY000): Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set. ``` *Phase two: B, another permitted connection, commits this detached branch by XID.* ```transcript B> XA COMMIT 'transfer-42'; Query OK B> SELECT balance FROM accounts WHERE id = 1; balance --------- 200 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/06-distributed/xa-transactions.yaml) ## mysql/08-production/deadlock-counter.yaml - engine: mysql (MySQL 8.4.11) - claim: On MySQL 8.4 InnoDB with deadlock detection and the lock_deadlocks metric enabled, this opposite-order schedule raises 1213 and the server-wide counter increases by at least one. This is not a permanent incident record. ```timeline A: debit id=1 B: debit id=2 A: credit id=2 → ⏳ waits B: credit id=1 ← 1213 Deadlock found when trying to get lock A: ⏵ credit id=2 → completes ``` ```transcript M> SELECT @@innodb_deadlock_detect AS detection; detection ----------- 1 (1 row) M> SELECT status FROM information_schema.INNODB_METRICS WHERE name = 'lock_deadlocks'; status --------- enabled (1 row) ``` *The same two opposite-order transfers as chapter 3 — one will be the victim.* ```transcript A> BEGIN; Query OK A> UPDATE accounts SET balance = balance - 10 WHERE id = 1; Query OK, 1 row affected B> BEGIN; Query OK B> UPDATE accounts SET balance = balance - 25 WHERE id = 2; Query OK, 1 row affected A> UPDATE accounts SET balance = balance + 10 WHERE id = 2; ⏳ A is waiting for a lock… B> UPDATE accounts SET balance = balance + 25 WHERE id = 1; ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction ⏵ A resumes: Query OK, 1 row affected A> COMMIT; Query OK ``` *The detected deadlock is also visible as a counter delta in this run:* ```transcript M> SELECT im.count - b.n >= 1 AS deadlocks_since_snapshot FROM information_schema.INNODB_METRICS im, deadlocks_before b WHERE im.name = 'lock_deadlocks' -- sample rates within one enabled interval; account for restart and reset deadlocks_since_snapshot -------------------------- 1 (1 row) ``` *Documented separately: SHOW ENGINE INNODB STATUS reports the latest detected deadlock; innodb_print_all_deadlocks enables error-log reports. This scenario does not inspect either log output or retention.* Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/08-production/deadlock-counter.yaml) ## mysql/08-production/find-long-transactions.yaml - engine: mysql (MySQL 8.4.11) - claim: On MySQL 8.4 InnoDB, the tagged session A appears in innodb_trx after reading orders: it is older than one second, its processlist command is Sleep, and trx_rows_modified is zero. Transaction age does not establish read-view age or prove that this session is the cause of a production backlog. ```transcript A> SELECT @@session.transaction_isolation AS isolation_level; isolation_level ----------------- REPEATABLE-READ (1 row) ``` *A starts a 'quick report'… and never gets around to committing.* ```transcript A> BEGIN; Query OK A> SELECT count(*) AS orders FROM orders; orders -------- 2 (1 row) ``` *Detector 1: the oldest tagged transaction, its owner, and a lower bound on its age.* ```transcript M> SELECT CAST(sn.variable_value AS CHAR) AS session_name, t.trx_state, timestampdiff(SECOND, t.trx_started, now()) >= 1 AS older_than_1s FROM information_schema.innodb_trx t JOIN performance_schema.threads th ON th.processlist_id = t.trx_mysql_thread_id JOIN performance_schema.user_variables_by_thread sn ON sn.thread_id = th.thread_id WHERE sn.variable_name = 'session_name' ORDER BY t.trx_started LIMIT 1; session_name | trx_state | older_than_1s --------------+-----------+--------------- A | RUNNING | 1 (1 row) ``` *Detector 2 — transactions whose session is idle (command Sleep) while holding them open:* ```transcript M> SELECT CAST(sn.variable_value AS CHAR) AS session_name, p.command FROM information_schema.innodb_trx t JOIN performance_schema.processlist p ON p.id = t.trx_mysql_thread_id JOIN performance_schema.threads th ON th.processlist_id = p.id JOIN performance_schema.user_variables_by_thread sn ON sn.thread_id = th.thread_id WHERE sn.variable_name = 'session_name' AND p.command = 'Sleep' AND p.time >= 1; session_name | command --------------+--------- A | Sleep (1 row) ``` *Detector 3: A has modified no rows. This observation does not identify a purge blocker or rely on an implementation-specific transaction ID.* ```transcript M> SELECT t.trx_rows_modified AS rows_modified FROM information_schema.innodb_trx t JOIN performance_schema.threads th ON th.processlist_id = t.trx_mysql_thread_id JOIN performance_schema.user_variables_by_thread sn ON sn.thread_id = th.thread_id WHERE sn.variable_name = 'session_name' AND sn.variable_value = 'A' -- no modified rows in the observed transaction rows_modified --------------- 0 (1 row) A> COMMIT; Query OK ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/08-production/find-long-transactions.yaml) ## mysql/08-production/history-list-health.yaml - engine: mysql (MySQL 8.4.11) - claim: On MySQL 8.4 InnoDB, R retains a REPEATABLE READ view of v=0 while 150 single-row updates commit. The history-list metric is at least 150 and the tagged oldest transaction is R. This run does not measure bytes, identify read-view age from transaction age, or assert later purge drainage. ```transcript R> SELECT @@session.transaction_isolation AS isolation_level; isolation_level ----------------- REPEATABLE-READ (1 row) ``` *R opens a read view and goes quiet; the write workload keeps humming.* ```transcript R> BEGIN; Query OK R> SELECT v FROM counters; v --- 0 (1 row) A> CALL bump(150); -- 150 committed single-row transactions Query OK ``` *Check 1: the history-list metric is at least 150 in this schedule.* ```transcript M> SELECT count >= 150 AS history_backlog FROM information_schema.INNODB_METRICS WHERE name = 'trx_rseg_history_len'; history_backlog ----------------- 1 (1 row) ``` *Check 2: find the oldest tagged transaction, a candidate for investigation.* ```transcript M> SELECT CAST(sn.variable_value AS CHAR) AS session_name, timestampdiff(SECOND, t.trx_started, now()) >= 1 AS older_than_1s FROM information_schema.innodb_trx t JOIN performance_schema.threads th ON th.processlist_id = t.trx_mysql_thread_id JOIN performance_schema.user_variables_by_thread sn ON sn.thread_id = th.thread_id WHERE sn.variable_name = 'session_name' ORDER BY t.trx_started LIMIT 1 -- transaction age is not read-view age; production attribution needs more evidence session_name | older_than_1s --------------+--------------- R | 1 (1 row) A> SELECT v FROM counters; v ----- 150 (1 row) R> SELECT v FROM counters; v --- 0 (1 row) R> COMMIT; Query OK ``` *R releases its read view; background purge and other readers determine later cleanup, which is not asserted here.* Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/08-production/history-list-health.yaml) ## mysql/08-production/timeout-guardrails.yaml - engine: mysql (MySQL 8.4.11) - claim: On MySQL 8.4, SELECT SLEEP(2) returns interrupted=1 with max_execution_time=100 and the session remains usable. With wait_timeout=1, A's next query fails after an idle wait and B sees the original InnoDB balance. This run does not measure exact elapsed time or test general SELECT error handling. *Guardrail 1: max_execution_time applies to eligible read-only SELECTs, not all statements.* ```transcript A> SET SESSION max_execution_time = 100; Query OK A> SELECT SLEEP(2) AS interrupted; -- SLEEP reports interruption; no exact duration is asserted interrupted ------------- 1 (1 row) A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) A> SET SESSION max_execution_time = 0; Query OK ``` *Guardrail 2 — wait_timeout: the server hangs up on a session that goes quiet. A opens a transaction, updates a row… and stops talking.* ```transcript A> SET SESSION wait_timeout = 1; Query OK A> BEGIN; Query OK A> UPDATE accounts SET balance = 999 WHERE id = 1; Query OK, 1 row affected A> SELECT balance FROM accounts WHERE id = 1; ERROR ERR_MYSQL_CONNECTION_CLOSED (HY000): Connection closed ``` *The app discovers the corpse on its next statement — and the uncommitted UPDATE is gone.* ```transcript B> SELECT balance FROM accounts WHERE id = 1; -- rolled back with the session balance --------- 100 (1 row) ``` *The third guardrail, innodb_lock_wait_timeout, was proven in chapter 3 — with innodb_rollback_on_timeout=OFF it rolls back the waiting statement; ON requests transaction rollback. See the chapter 3 evidence and manual.* Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/08-production/timeout-guardrails.yaml) ## mysql/08-production/who-is-blocking-whom.yaml - engine: mysql (MySQL 8.4.11) - claim: On MySQL 8.4 InnoDB, sys.innodb_lock_waits identifies B waiting on A while A's processlist command is Sleep. KILL CONNECTION A releases this wait; B updates row 1 and observes A's row 2 change rolled back. This one-waiter schedule does not establish recovery for every queue. ```timeline A: UPDATE row 1, holds lock A: UPDATE row 2, then idle B: UPDATE balance = 300 → ⏳ waits M: who blocks whom? → B waits on sleeping A M: KILL A B: ⏵ UPDATE balance = 300 → completes ``` *A updates a row and then… goes to lunch. The transaction stays open.* ```transcript A> BEGIN; Query OK A> UPDATE accounts SET balance = 200 WHERE id = 1; Query OK, 1 row affected A> UPDATE accounts SET balance = 200 WHERE id = 2; Query OK, 1 row affected B> UPDATE accounts SET balance = 300 WHERE id = 1; ⏳ B is waiting for a lock… ``` *Someone pages you: 'updates are hanging'. This is the query you paste:* ```transcript M> SELECT w.waiting_pid, w.waiting_query, w.blocking_pid, bp.command AS blocker_state, bp.info AS blocker_running FROM sys.innodb_lock_waits w JOIN performance_schema.processlist bp ON bp.id = w.blocking_pid; waiting_pid | waiting_query | blocking_pid | blocker_state | blocker_running -------------+------------------------------------------------+--------------+---------------+----------------- pid(B) | UPDATE accounts SET balance = 300 WHERE id = 1 | pid(A) | Sleep | (1 row) ``` *The culprit isn't running anything — command Sleep, no current statement, holding locks. sys.innodb_lock_waits even pre-writes the KILL statement for you (sql_kill_blocking_connection). This run ends the connection; production use requires privileges and an application recovery decision.* ```transcript M> CALL kill_session('A'); Query OK ``` *A's transaction dies and rolls back; B gets the lock and finishes at last.* ```transcript ⏵ B resumes: Query OK, 1 row affected B> SELECT balance FROM accounts WHERE id = 1; -- B's autocommit update completed balance --------- 300 (1 row) B> SELECT balance FROM accounts WHERE id = 2; -- A's separate uncommitted change was rolled back balance --------- 100 (1 row) ``` Verified against MySQL 8.4.11 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/mysql/08-production/who-is-blocking-whom.yaml) ## postgres/01-basics/aborted-transaction.yaml - engine: postgres (PostgreSQL 18.6) - claim: After division by zero in this explicit transaction, SELECT fails with 25P02; ROLLBACK ends the failed transaction and a new SELECT succeeds. In the second transaction, COMMIT after the error rolls back the preceding INSERT. ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> SELECT 1 / 0; -- division_by_zero ERROR: 22012: division by zero ``` *The transaction is now aborted. Even a perfectly innocent statement is refused.* ```transcript A> SELECT 1 AS innocent; -- in_failed_sql_transaction ERROR: 25P02: current transaction is aborted, commands ignored until end of transaction block ``` *This first transaction uses full ROLLBACK. The next transaction checks COMMIT after an error; savepoint recovery has its own Scenario.* ```transcript A> ROLLBACK; ROLLBACK A> SELECT 1 AS innocent; innocent ---------- 1 (1 row) A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> INSERT INTO samples VALUES (1); INSERT 0 1 A> SELECT 1 / 0; ERROR: 22012: division by zero A> COMMIT; -- a failed transaction ends by rolling back, even when COMMIT is sent ROLLBACK A> SELECT count(*)::int AS remaining FROM samples; remaining ----------- 0 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/01-basics/aborted-transaction.yaml) ## postgres/01-basics/atomicity.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this explicit transaction, a CHECK violation follows a successful credit; after ROLLBACK, both balances retain their original values. ```timeline A: credit bob +150 (uncommitted) B: SELECT bob → 50 ← A's credit is invisible A: debit alice −150 ← 23514 new row for relation "accounts" violates check constraint "accounts_balance_check" A: ROLLBACK ← bob's credit vanishes too B: SELECT → alice 100, bob 50 ← nothing changed ``` *A transfers 150 from alice to bob. Crediting bob works fine…* ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> UPDATE accounts SET balance = balance + 150 WHERE owner = 'bob'; UPDATE 1 B> SELECT balance FROM accounts WHERE owner = 'bob'; -- B can't see A's uncommitted credit balance --------- 50 (1 row) ``` *…but debiting alice violates the CHECK constraint — she only has 100.* ```transcript A> UPDATE accounts SET balance = balance - 150 WHERE owner = 'alice'; -- check_violation ERROR: 23514: new row for relation "accounts" violates check constraint "accounts_balance_check" ``` *This run uses full ROLLBACK after the CHECK violation. Bob's earlier credit is undone along with the failed transfer.* ```transcript A> ROLLBACK; ROLLBACK B> SELECT owner, balance FROM accounts ORDER BY id; owner | balance -------+--------- alice | 100 bob | 50 (2 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/01-basics/atomicity.yaml) ## postgres/01-basics/autocommit-visibility.yaml - engine: postgres (PostgreSQL 18.6) - claim: B sees A's successful autocommit UPDATE in its next plain SELECT at READ COMMITTED; an explicit transaction's UPDATE becomes visible to B only after COMMIT. ```timeline A: UPDATE balance = 150 (autocommit, committed at once) B: SELECT → 150 ← visible right away A: UPDATE balance = 999 (uncommitted) B: SELECT → 150 ← still the old value A: COMMIT B: SELECT → 999 ← now B sees it ``` *No BEGIN: this successful UPDATE commits as its own transaction before the next SELECT.* ```transcript A> UPDATE accounts SET balance = 150 WHERE id = 1; UPDATE 1 B> SELECT balance FROM accounts WHERE id = 1; -- B sees it immediately balance --------- 150 (1 row) ``` *Inside an explicit transaction, A's change is invisible to B…* ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> UPDATE accounts SET balance = 999 WHERE id = 1; UPDATE 1 B> SELECT balance FROM accounts WHERE id = 1; -- still the old value balance --------- 150 (1 row) ``` *…until A commits.* ```transcript A> COMMIT; COMMIT B> SELECT balance FROM accounts WHERE id = 1; balance --------- 999 (1 row) ``` *A failed autocommit statement does not leave the next statement in a failed transaction.* ```transcript A> SELECT 1 / 0; ERROR: 22012: division by zero A> SELECT 1 AS recovered; recovered ----------- 1 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/01-basics/autocommit-visibility.yaml) ## postgres/01-basics/ddl-rollback.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this schedule, CREATE TABLE and non-concurrent CREATE INDEX do not commit the preceding INSERT; after a statement error and ROLLBACK, the inserted row, new table, and new index are absent. *A migration script wraps its work in a transaction, believing that makes it atomic: insert data, add an index, create a table — and if anything fails, roll back.* ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> INSERT INTO orders VALUES (1, 'draft'); INSERT 0 1 B> SELECT count(*)::int AS visible FROM orders; -- uncommitted, invisible — so far so good visible --------- 0 (1 row) A> CREATE INDEX idx_orders_state ON orders (state); -- DDL — on MySQL this is where the implicit COMMIT would fire CREATE INDEX A> CREATE TABLE migration_log (id int PRIMARY KEY, note text); CREATE TABLE A> SELECT to_regclass('migration_log') IS NOT NULL AS table_exists, to_regclass('idx_orders_state') IS NOT NULL AS index_exists; table_exists | index_exists --------------+-------------- t | t (1 row) B> SELECT count(*)::int AS visible FROM orders; -- still nothing committed — the DDL joined the transaction visible --------- 0 (1 row) B> SELECT count(*) FROM migration_log; -- undefined_table — uncommitted schema is invisible, not merely empty ERROR: 42P01: relation "migration_log" does not exist ``` *The script now hits an error and rolls back, trusting the transaction to clean up:* ```transcript A> INSERT INTO orders VALUES (1, 'duplicate'); ERROR: 23505: duplicate key value violates unique constraint "orders_pkey" A> ROLLBACK; ROLLBACK B> SELECT count(*)::int AS visible FROM orders; -- the row is gone visible --------- 0 (1 row) B> SELECT to_regclass('migration_log') IS NULL AS table_gone, to_regclass('idx_orders_state') IS NULL AS index_gone; -- so is the table, and so is the index table_gone | index_gone ------------+------------ t | t (1 row) ``` *This rollback removed the INSERT, the non-concurrent index, and the new table. It does not test all DDL or external migration effects.* Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/01-basics/ddl-rollback.yaml) ## postgres/01-basics/savepoint-nesting.yaml - engine: postgres (PostgreSQL 18.6) - claim: Rolling back to outer_sp removes the later rows and inner_sp; RELEASE outer_sp retains row 4, and COMMIT preserves rows 1 and 4. ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> INSERT INTO steps VALUES (1); INSERT 0 1 A> SAVEPOINT outer_sp; SAVEPOINT A> INSERT INTO steps VALUES (2); INSERT 0 1 A> SAVEPOINT inner_sp; SAVEPOINT A> INSERT INTO steps VALUES (3); INSERT 0 1 ``` *Rolling back to the OUTER savepoint discards rows 2 and 3 — and inner_sp itself.* ```transcript A> ROLLBACK TO SAVEPOINT outer_sp; ROLLBACK A> ROLLBACK TO SAVEPOINT inner_sp; -- no such savepoint — it was destroyed by the outer rollback ERROR: 3B001: savepoint "inner_sp" does not exist A> ROLLBACK TO SAVEPOINT outer_sp; -- recover from that error, same trick as before ROLLBACK ``` *RELEASE keeps the work done after the savepoint, but you can no longer rewind to it.* ```transcript A> INSERT INTO steps VALUES (4); INSERT 0 1 A> RELEASE SAVEPOINT outer_sp; RELEASE A> SAVEPOINT after_release; SAVEPOINT A> ROLLBACK TO SAVEPOINT outer_sp; -- RELEASE removed outer_sp; recover using the newer savepoint ERROR: 3B001: savepoint "outer_sp" does not exist A> ROLLBACK TO SAVEPOINT after_release; ROLLBACK A> COMMIT; COMMIT A> SELECT n FROM steps ORDER BY n; n --- 1 4 (2 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/01-basics/savepoint-nesting.yaml) ## postgres/01-basics/savepoint-recovery.yaml - engine: postgres (PostgreSQL 18.6) - claim: ROLLBACK TO the savepoint recovers from this uniqueness violation; the earlier INSERT and a later replacement INSERT commit successfully. ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> INSERT INTO items VALUES (2, 'gadget'); INSERT 0 1 A> SAVEPOINT before_risky; SAVEPOINT A> INSERT INTO items VALUES (3, 'widget'); -- unique_violation — the transaction is aborted ERROR: 23505: duplicate key value violates unique constraint "items_name_key" ``` *Without the savepoint this transaction would be doomed. With it, we rewind past the failure and carry on.* ```transcript A> ROLLBACK TO SAVEPOINT before_risky; ROLLBACK A> INSERT INTO items VALUES (3, 'doohickey'); INSERT 0 1 A> COMMIT; COMMIT A> SELECT id, name FROM items ORDER BY id; -- survived — it predates the savepoint id | name ----+----------- 1 | widget 2 | gadget 3 | doohickey (3 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/01-basics/savepoint-recovery.yaml) ## postgres/02-isolation/circular-information-flow.yaml - engine: postgres (PostgreSQL 18.6) - claim: At READ COMMITTED, both plain SELECTs read the original balance rather than the other transaction's uncommitted UPDATE; both writes later commit. This excludes a dirty-read cycle in this schedule, not every form of dependency cycle. ```timeline A: UPDATE alice = 111 (uncommitted) B: UPDATE bob = 222 (uncommitted) A: SELECT bob → 100 ← B's 222 invisible B: SELECT alice → 100 ← A's 111 invisible A: COMMIT B: COMMIT A: SELECT → 111, 222 ← both writes, no cross-read ``` *A adjusts alice's balance while B adjusts bob's — then each peeks at the other's row. If both saw the other's uncommitted write, information would flow in a circle: A → B → A. No serial order can do that.* ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN B> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> UPDATE accounts SET balance = 111 WHERE id = 1; UPDATE 1 B> UPDATE accounts SET balance = 222 WHERE id = 2; UPDATE 1 A> SELECT balance FROM accounts WHERE id = 2; -- B's uncommitted 222 is invisible to A balance --------- 100 (1 row) B> SELECT balance FROM accounts WHERE id = 1; -- and A's uncommitted 111 is invisible to B balance --------- 100 (1 row) A> COMMIT; COMMIT B> COMMIT; COMMIT A> SELECT id, balance FROM accounts ORDER BY id; -- both writes landed — but neither transaction ever saw the other's id | balance ----+--------- 1 | 111 2 | 222 (2 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/circular-information-flow.yaml) ## postgres/02-isolation/concurrent-update-40001.yaml - engine: postgres (PostgreSQL 18.6) - claim: A's UPDATE at REPEATABLE READ fails with 40001 when B updates its target row after A's snapshot, both when B has already committed and when A waits for B to commit; when B rolls back instead, A's waiting UPDATE succeeds. ```timeline A: SELECT (snapshot taken) B: UPDATE balance = 300 (uncommitted) A: UPDATE balance = 999 → ⏳ waits B: COMMIT A: ⏵ UPDATE balance = 999 ← 40001 could not serialize access due to concurrent update ``` ```transcript A> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN A> SELECT balance FROM accounts WHERE id = 1; -- snapshot taken balance --------- 100 (1 row) ``` *B commits a change. A can keep READING its stale snapshot — but writing that row is refused.* ```transcript B> UPDATE accounts SET balance = 150 WHERE id = 1; UPDATE 1 A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) A> UPDATE accounts SET balance = 200 WHERE id = 1; -- serialization_failure — retry the whole transaction ERROR: 40001: could not serialize access due to concurrent update A> ROLLBACK; ROLLBACK ``` *If the competing write is NOT yet committed, the outcome is decided later: A first waits on the row lock…* ```transcript A> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN A> SELECT balance FROM accounts WHERE id = 1; -- snapshot taken balance --------- 150 (1 row) B> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN B> UPDATE accounts SET balance = 300 WHERE id = 1; UPDATE 1 A> UPDATE accounts SET balance = 999 WHERE id = 1; ⏳ A is waiting for a lock… ``` *A's waiting UPDATE fails with 40001 after B commits. The next schedule checks the different outcome when B rolls back.* ```transcript B> COMMIT; COMMIT ⏵ A's blocked statement fails: ERROR: 40001: could not serialize access due to concurrent update A> ROLLBACK; ROLLBACK A> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN A> SELECT balance FROM accounts WHERE id = 1; balance --------- 300 (1 row) B> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN B> UPDATE accounts SET balance = 400 WHERE id = 1; UPDATE 1 A> UPDATE accounts SET balance = 999 WHERE id = 1; ⏳ A is waiting for a lock… B> ROLLBACK; ROLLBACK ⏵ A resumes: UPDATE 1 A> COMMIT; COMMIT B> SELECT balance FROM accounts WHERE id = 1; balance --------- 999 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/concurrent-update-40001.yaml) ## postgres/02-isolation/dirty-write.yaml - engine: postgres (PostgreSQL 18.6) - claim: At READ COMMITTED, B's UPDATE of row 1 waits for A to commit before proceeding; after both transactions update both rows and commit in this order, both final prices are B's. ```timeline A: UPDATE id=1 price=11 B: UPDATE id=1 price=12 → ⏳ waits A: UPDATE id=2 price=21 A: COMMIT ← locks released, B wakes up B: ⏵ UPDATE id=1 price=12 → completes B: UPDATE id=2 price=22 B: COMMIT A: SELECT → 12, 22 ← both final prices are B's ``` *Both batch jobs update the same two rows. A dirty write would overwrite a row before its previous writer commits or rolls back; the wait below prevents that overwrite in this schedule.* ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN B> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> UPDATE items SET price = 11 WHERE id = 1; UPDATE 1 ``` *B wants the same row. Even at READ COMMITTED it must wait for A's lock.* ```transcript B> UPDATE items SET price = 12 WHERE id = 1; ⏳ B is waiting for a lock… A> UPDATE items SET price = 21 WHERE id = 2; UPDATE 1 A> COMMIT; -- releases both row locks COMMIT ⏵ B resumes: UPDATE 1 B> UPDATE items SET price = 22 WHERE id = 2; UPDATE 1 B> COMMIT; COMMIT A> SELECT id, price FROM items ORDER BY id; -- both final prices are B's in this order id | price ----+------- 1 | 12 2 | 22 (2 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/dirty-write.yaml) ## postgres/02-isolation/intermediate-read.yaml - engine: postgres (PostgreSQL 18.6) - claim: B's plain SELECT reads 100 while A's draft 999 is uncommitted, and its SELECT after A commits reads the final 110. ```timeline A: UPDATE balance = 999 (draft, uncommitted) B: SELECT → 100 ← draft 999 invisible A: UPDATE balance = 110 (final value) A: COMMIT B: SELECT → 110 ← only the final value, never 999 ``` ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> UPDATE accounts SET balance = 999 WHERE id = 1; -- a working draft — A isn't done yet UPDATE 1 B> SELECT balance FROM accounts WHERE id = 1; -- the draft 999 is invisible balance --------- 100 (1 row) A> UPDATE accounts SET balance = 110 WHERE id = 1; -- A settles on the final value… UPDATE 1 A> COMMIT; COMMIT B> SELECT balance FROM accounts WHERE id = 1; balance --------- 110 (1 row) ``` *B's two SELECTs returned 100 and 110, never A's uncommitted draft 999. A transaction with an older stable snapshot need not see 110 yet.* Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/intermediate-read.yaml) ## postgres/02-isolation/lost-update-read-committed.yaml - engine: postgres (PostgreSQL 18.6) - claim: Two read-modify-write transactions at READ COMMITTED both read 100 and write 110; both commit, leaving 110 rather than the intended 120. ```timeline A: SELECT balance → 100 B: SELECT balance → 100 (same stale read) A: UPDATE balance = 100 + 10 A: COMMIT B: UPDATE balance = 100 + 10 (stale math) B: COMMIT A: SELECT balance → 110 — one deposit gone ``` *Two app servers process a +10 deposit each: read the balance, add 10 in code, write it back.* ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) B> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN B> SELECT balance FROM accounts WHERE id = 1; -- B reads the same 100 — A hasn't committed balance --------- 100 (1 row) A> UPDATE accounts SET balance = 100 + 10 WHERE id = 1; UPDATE 1 A> COMMIT; COMMIT ``` *B computed 100 + 10 from its stale read. Nothing stops the write — A's transaction is long gone.* ```transcript B> UPDATE accounts SET balance = 100 + 10 WHERE id = 1; UPDATE 1 B> COMMIT; COMMIT A> SELECT balance FROM accounts WHERE id = 1; -- two +10 deposits, but only one survived balance --------- 110 (1 row) ``` *A's deposit vanished without any error. Fixes: atomic UPDATE, SELECT FOR UPDATE, or REPEATABLE READ — see the lesson.* Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/lost-update-read-committed.yaml) ## postgres/02-isolation/lost-update-repeatable-read.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this schedule at REPEATABLE READ, B's stale UPDATE fails with 40001 after A commits 110; after ROLLBACK, B reads 110 in a fresh transaction and commits 120. ```timeline A: SELECT balance → 100 B: SELECT balance → 100 (B's pre-commit snapshot) A: UPDATE balance = 100 + 10 A: COMMIT B: UPDATE balance = 100 + 10 ← 40001 could not serialize access due to concurrent update A: SELECT balance → 110 ← B's deposit has not committed A: SELECT balance → 120 ← B's fresh retry committed ``` *The same two +10 deposits — but this time at REPEATABLE READ.* ```transcript A> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) B> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN B> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) A> UPDATE accounts SET balance = 100 + 10 WHERE id = 1; UPDATE 1 A> COMMIT; COMMIT ``` *B's snapshot predates A's commit, so B's write is refused instead of silently clobbering it.* ```transcript B> UPDATE accounts SET balance = 100 + 10 WHERE id = 1; -- serialization_failure ERROR: 40001: could not serialize access due to concurrent update B> ROLLBACK; ROLLBACK A> SELECT balance FROM accounts WHERE id = 1; -- only A's deposit has committed so far balance --------- 110 (1 row) ``` *Retrying B from scratch reads the fresh 110 and correctly produces 120.* ```transcript B> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN B> SELECT balance FROM accounts WHERE id = 1; balance --------- 110 (1 row) B> UPDATE accounts SET balance = 110 + 10 WHERE id = 1; UPDATE 1 B> COMMIT; COMMIT A> SELECT balance FROM accounts WHERE id = 1; balance --------- 120 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/lost-update-repeatable-read.yaml) ## postgres/02-isolation/no-dirty-reads.yaml - engine: postgres (PostgreSQL 18.6) - claim: B accepts the READ UNCOMMITTED setting but its plain SELECT reads the committed 100 rather than A's uncommitted 999, which A later rolls back. ```timeline A: UPDATE balance = 999 (uncommitted) B: isolation = read uncommitted ← setting accepted B: SELECT → 100 ← A's 999 stays invisible ``` ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> UPDATE accounts SET balance = 999 WHERE id = 1; UPDATE 1 ``` *The SQL standard permits dirty reads at READ UNCOMMITTED; PostgreSQL maps that request to READ COMMITTED behavior.* ```transcript B> BEGIN ISOLATION LEVEL READ UNCOMMITTED; BEGIN B> SELECT current_setting('transaction_isolation') AS isolation; -- the setting is accepted… isolation ------------------ read uncommitted (1 row) B> SELECT balance FROM accounts WHERE id = 1; -- …but A's uncommitted 999 stays invisible balance --------- 100 (1 row) B> COMMIT; COMMIT A> ROLLBACK; ROLLBACK ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/no-dirty-reads.yaml) ## postgres/02-isolation/non-repeatable-read.yaml - engine: postgres (PostgreSQL 18.6) - claim: A's plain SELECTs at READ COMMITTED return 100 and then 200 around B's committed UPDATE; in the following writer schedule, B waits for A's row lock before committing 400. ```timeline A: SELECT balance → 100 B: UPDATE balance = 200 (autocommit) A: SELECT balance → 200 — same txn, different answer ``` ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) ``` *While A's transaction is still open, B updates the row and commits.* ```transcript B> UPDATE accounts SET balance = 200 WHERE id = 1; UPDATE 1 A> SELECT balance FROM accounts WHERE id = 1; -- same query, same transaction — different answer balance --------- 200 (1 row) A> COMMIT; COMMIT ``` *The plain SELECTs above did not wait for a row lock. The following UPDATE of the same row makes B wait for A's row lock; SELECT can still wait for conflicting table locks.* ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> UPDATE accounts SET balance = 300 WHERE id = 1; UPDATE 1 B> UPDATE accounts SET balance = 400 WHERE id = 1; ⏳ B is waiting for a lock… A> COMMIT; -- releases the row lock COMMIT ⏵ B resumes: UPDATE 1 B> SELECT balance FROM accounts WHERE id = 1; -- B's write landed on top of A's committed 300 balance --------- 400 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/non-repeatable-read.yaml) ## postgres/02-isolation/observed-transaction-vanishes.yaml - engine: postgres (PostgreSQL 18.6) - claim: C's plain SELECTs at READ COMMITTED see both of A's committed balances while B's overwrites are uncommitted; after B commits both changes, C's next SELECT sees both of B's balances. ```timeline A: UPDATE alice = 11 A: UPDATE bob = 19 B: UPDATE alice = 12 → ⏳ waits A: COMMIT ← lock released, B proceeds B: ⏵ UPDATE alice = 12 → completes C: SELECT → 11, 19 ← all of A, together B: UPDATE bob = 18 (uncommitted) C: SELECT → 11, 19 ← B's drafts don't count B: COMMIT C: SELECT → 12, 18 ← now all of B, atomically ``` *A rewrites both balances. B will overwrite one of them right after.* ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> UPDATE accounts SET balance = 11 WHERE id = 1; UPDATE 1 A> UPDATE accounts SET balance = 19 WHERE id = 2; UPDATE 1 B> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN B> UPDATE accounts SET balance = 12 WHERE id = 1; ⏳ B is waiting for a lock… A> COMMIT; -- A's lock released — B's overwrite of alice proceeds COMMIT ⏵ B resumes: UPDATE 1 ``` *C now watches from the side. B holds an uncommitted overwrite of alice — but A's committed transaction must still be visible in full.* ```transcript C> SELECT id, balance FROM accounts ORDER BY id; -- A's writes appear together — 11 AND 19 id | balance ----+--------- 1 | 11 2 | 19 (2 rows) B> UPDATE accounts SET balance = 18 WHERE id = 2; UPDATE 1 C> SELECT id, balance FROM accounts ORDER BY id; -- B's drafts change nothing for C id | balance ----+--------- 1 | 11 2 | 19 (2 rows) B> COMMIT; COMMIT C> SELECT id, balance FROM accounts ORDER BY id; -- only now does C move on — to ALL of B, atomically id | balance ----+--------- 1 | 12 2 | 18 (2 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/observed-transaction-vanishes.yaml) ## postgres/02-isolation/phantom-read.yaml - engine: postgres (PostgreSQL 18.6) - claim: A's first aggregate at READ COMMITTED counts two matching orders; after B commits a matching INSERT, A's next aggregate counts three and totals 1500. ```timeline A: SELECT count → 2 B: INSERT order 3 (700), committed A: SELECT count → 3, total 1500 ← a phantom row A: COMMIT ``` *A computes a report twice inside one transaction: count first, then the total.* ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> SELECT count(*)::int AS n FROM orders WHERE amount >= 100; n --- 2 (1 row) ``` *Between A's two statements, B commits a new order that matches A's WHERE clause.* ```transcript B> INSERT INTO orders VALUES (3, 700); INSERT 0 1 A> SELECT count(*)::int AS n, sum(amount)::int AS total FROM orders WHERE amount >= 100; -- a third row appeared out of nowhere — a phantom n | total ---+------- 3 | 1500 (1 row) A> COMMIT; COMMIT ``` *A's report now says '2 orders' in one place and '3 orders, total 1500' in another.* Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/phantom-read.yaml) ## postgres/02-isolation/read-only-anomaly.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this schedule, the REPEATABLE READ report commits with two receipts before the cashier commits a third into the closed batch; with all three transactions SERIALIZABLE, the report commits and the cashier's COMMIT fails with 40001. ```timeline Cashier: SELECT deposit_no → 1 (current batch) Cashier: INSERT receipt 3 into batch 1 (slow, uncommitted) Closer: UPDATE deposit_no = 2 (batch 1 closed) Closer: COMMIT Report: SELECT deposit_no → 2 ← batch 1 is closed Report: SELECT batch 1 → receipts 1, 2 (total 300) ← report published Report: COMMIT Cashier: COMMIT ← receipt 3 lands in the closed batch 1 Report: re-read batch 1 → 3 receipts ← the published report was wrong ``` *The report is modeled by SELECT results; no printing, external publication, or cashier retry is executed.* *A bank tracks receipts per deposit batch. The cashier files a receipt into the current batch (1) — slowly.* ```transcript Cashier> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN Cashier> SELECT deposit_no FROM control; deposit_no ------------ 1 (1 row) Cashier> INSERT INTO receipts VALUES (3, 1, 400); INSERT 0 1 ``` *Meanwhile the closer moves the bank to batch 2 — from now on, batch 1 is supposedly complete.* ```transcript Closer> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN Closer> UPDATE control SET deposit_no = 2; UPDATE 1 Closer> COMMIT; COMMIT ``` *An auditor prints the report for the closed batch 1.* ```transcript Report> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN Report> SELECT deposit_no FROM control; -- batch 1 is closed… deposit_no ------------ 2 (1 row) Report> SELECT receipt_no, amount FROM receipts WHERE deposit_no = 1 ORDER BY receipt_no; -- …and contains receipts 1 and 2, total 300. The report is published. receipt_no | amount ------------+-------- 1 | 100 2 | 200 (2 rows) Report> COMMIT; COMMIT ``` *Now the cashier's receipt lands — in batch 1, which the report just declared final.* ```transcript Cashier> COMMIT; COMMIT Report> SELECT receipt_no, amount FROM receipts WHERE deposit_no = 1 ORDER BY receipt_no; -- the published report was wrong: no serial order of these three transactions produces it receipt_no | amount ------------+-------- 1 | 100 2 | 200 3 | 400 (3 rows) ``` *Rewind and replay the exact same interleaving — all three transactions SERIALIZABLE.* ```transcript Report> DELETE FROM receipts WHERE receipt_no = 3; DELETE 1 Report> UPDATE control SET deposit_no = 1; UPDATE 1 Cashier> BEGIN ISOLATION LEVEL SERIALIZABLE; BEGIN Cashier> SELECT deposit_no FROM control; deposit_no ------------ 1 (1 row) Cashier> INSERT INTO receipts VALUES (3, 1, 400); INSERT 0 1 Closer> BEGIN ISOLATION LEVEL SERIALIZABLE; BEGIN Closer> UPDATE control SET deposit_no = 2; UPDATE 1 Closer> COMMIT; COMMIT Report> BEGIN ISOLATION LEVEL SERIALIZABLE; BEGIN Report> SELECT deposit_no FROM control; deposit_no ------------ 2 (1 row) Report> SELECT receipt_no, amount FROM receipts WHERE deposit_no = 1 ORDER BY receipt_no; receipt_no | amount ------------+-------- 1 | 100 2 | 200 (2 rows) Report> COMMIT; -- the report itself commits fine — COMMIT ``` *— because SERIALIZABLE protects it by aborting the transaction that would invalidate it: the cashier.* ```transcript Cashier> COMMIT; ERROR: 40001: could not serialize access due to read/write dependencies among transactions Report> SELECT receipt_no, amount FROM receipts WHERE deposit_no = 1 ORDER BY receipt_no; -- batch 1 still has two receipts; no cashier retry is executed here receipt_no | amount ------------+-------- 1 | 100 2 | 200 (2 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/read-only-anomaly.yaml) ## postgres/02-isolation/read-skew.yaml - engine: postgres (PostgreSQL 18.6) - claim: At READ COMMITTED, A's separate SELECTs around B's committed transfer return balances totaling 125; in the second schedule at REPEATABLE READ, the two reads total 100 despite B's intervening transfer. ```timeline A: SELECT alice → 50 (before the transfer) B: UPDATE alice −25 B: UPDATE bob +25 B: COMMIT ← transfer done, invariant intact A: SELECT bob → 75 ← 50+75=125, money that never existed ``` *The invariant: alice + bob = 100 at every moment. A is an auditor summing the accounts row by row; B transfers 25 between them mid-audit.* ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> SELECT balance FROM accounts WHERE owner = 'alice'; balance --------- 50 (1 row) B> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN B> UPDATE accounts SET balance = balance - 25 WHERE owner = 'alice'; UPDATE 1 B> UPDATE accounts SET balance = balance + 25 WHERE owner = 'bob'; UPDATE 1 B> COMMIT; -- a perfectly correct transfer — atomic, invariant preserved COMMIT A> SELECT balance FROM accounts WHERE owner = 'bob'; -- 50 + 75 = 125. The auditor found 25 that never existed. balance --------- 75 (1 row) A> COMMIT; COMMIT ``` *Neither row was ever wrong — A read alice BEFORE the transfer and bob AFTER it. Fresh-snapshot-per-statement cannot hold two rows still. REPEATABLE READ can:* ```transcript A> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN A> SELECT balance FROM accounts WHERE owner = 'alice'; balance --------- 25 (1 row) B> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN B> UPDATE accounts SET balance = balance - 10 WHERE owner = 'alice'; UPDATE 1 B> UPDATE accounts SET balance = balance + 10 WHERE owner = 'bob'; UPDATE 1 B> COMMIT; COMMIT A> SELECT balance FROM accounts WHERE owner = 'bob'; -- 25 + 75 = 100 — one snapshot, one moment in time balance --------- 75 (1 row) A> COMMIT; COMMIT ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/read-skew.yaml) ## postgres/02-isolation/stable-snapshot.yaml - engine: postgres (PostgreSQL 18.6) - claim: A's first plain SELECT at REPEATABLE READ includes B's change after BEGIN; subsequent SELECTs exclude B's later committed UPDATE and INSERT but include A's own UPDATE. After COMMIT, A's next SELECT sees all committed rows. ```timeline A: SELECT → alice 101, bob 50 (snapshot frozen here) B: UPDATE alice = 999 (committed) B: INSERT carol (committed) A: SELECT → 101, 50 ← no 999, no carol A: COMMIT A: SELECT → 999 and carol ← new txn, new snapshot ``` ```transcript A> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN B> UPDATE accounts SET balance = 101 WHERE id = 1; -- commits after BEGIN but before A's first query UPDATE 1 ``` *The snapshot is taken by the FIRST query, not by BEGIN.* ```transcript A> SELECT id, balance FROM accounts ORDER BY id; id | balance ----+--------- 1 | 101 2 | 50 (2 rows) ``` *B changes an existing row AND inserts a new one — both committed instantly.* ```transcript B> UPDATE accounts SET balance = 999 WHERE id = 1; UPDATE 1 B> INSERT INTO accounts VALUES (3, 'carol', 300); INSERT 0 1 A> SELECT id, balance FROM accounts ORDER BY id; -- not 999 — no non-repeatable read; and no carol — no phantom id | balance ----+--------- 1 | 101 2 | 50 (2 rows) ``` *A sees its own UPDATE even though B's later changes remain outside the snapshot.* ```transcript A> UPDATE accounts SET balance = 60 WHERE id = 2; UPDATE 1 A> SELECT id, balance FROM accounts ORDER BY id; id | balance ----+--------- 1 | 101 2 | 60 (2 rows) A> COMMIT; COMMIT ``` *Only a NEW transaction gets a new snapshot.* ```transcript A> SELECT id, balance FROM accounts ORDER BY id; id | balance ----+--------- 1 | 999 2 | 60 3 | 300 (3 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/stable-snapshot.yaml) ## postgres/02-isolation/update-recheck.yaml - engine: postgres (PostgreSQL 18.6) - claim: B's UPDATE at READ COMMITTED waits for A to commit, re-checks value = 10 against the changed row, and affects zero rows; the final values remain 20 and 30. ```timeline A: UPDATE id=1 value 10→20 (uncommitted) B: UPDATE WHERE value=10 → ⏳ waits A: COMMIT ← row 1 is now 20 B: ⏵ UPDATE WHERE value=10 → completes B: SELECT → 20, 30 ← B re-checked WHERE, matched 0 rows ``` ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> UPDATE items SET value = value * 2 WHERE id = 1; -- row 1: 10 → 20, uncommitted UPDATE 1 ``` *B targets WHERE value = 10. In B's snapshot row 1 still qualifies — but it's locked by A, so B waits.* ```transcript B> UPDATE items SET value = 99 WHERE value = 10; ⏳ B is waiting for a lock… ``` *A commits. B wakes up and re-checks the row it waited for — against the NEW version, where value is 20.* ```transcript A> COMMIT; COMMIT ⏵ B resumes: UPDATE 0 ``` *UPDATE 0 — the row slipped away.* ```transcript B> SELECT id, value FROM items ORDER BY id; id | value ----+------- 1 | 20 2 | 30 (2 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/update-recheck.yaml) ## postgres/02-isolation/visibility-operations.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this PostgreSQL REPEATABLE READ schedule, A's plain SELECT retains 100 after B commits 150, but SELECT FOR UPDATE fails with 40001. After rollback, a fresh attempt locks 150, writes 200, and reads its own 200 while B still reads 150; after A commits, B reads 200. ```timeline A: Plain SELECT B: UPDATE; autocommit A: Plain SELECT A: Locking SELECT ← 40001 could not serialize access due to concurrent update A: Locking SELECT in fresh attempt A: Plain SELECT after own UPDATE ``` ```transcript A> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) B> UPDATE accounts SET balance = 150 WHERE id = 1; UPDATE 1 A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) A> SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; ERROR: 40001: could not serialize access due to concurrent update A> ROLLBACK; ROLLBACK A> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN A> SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; balance --------- 150 (1 row) A> UPDATE accounts SET balance = balance + 50 WHERE id = 1; UPDATE 1 A> SELECT balance FROM accounts WHERE id = 1; balance --------- 200 (1 row) B> SELECT balance FROM accounts WHERE id = 1; balance --------- 150 (1 row) A> COMMIT; COMMIT B> SELECT balance FROM accounts WHERE id = 1; balance --------- 200 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/visibility-operations.yaml) ## postgres/02-isolation/write-skew-rr.yaml - engine: postgres (PostgreSQL 18.6) - claim: Both REPEATABLE READ transactions read two on-call doctors, update different rows, and commit in this schedule; the final asserted on-call count is zero. ```timeline A: SELECT on_call → 2 ← "safe for me to leave" B: SELECT on_call → 2 ← "safe for me to leave" A: UPDATE alice off-call B: UPDATE bob off-call (a different row) A: COMMIT B: COMMIT ← both succeed, no conflict to detect A: SELECT on_call → 0 ← invariant broken ``` *Hospital rule: at least one doctor must stay on call. Alice and Bob both want the night off.* ```transcript A> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN B> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN A> SELECT count(*)::int AS on_call FROM doctors WHERE on_call; -- "two of us — safe for me to leave" on_call --------- 2 (1 row) B> SELECT count(*)::int AS on_call FROM doctors WHERE on_call; -- "two of us — safe for me to leave" on_call --------- 2 (1 row) ``` *Each updates a DIFFERENT row, so there is no write-write conflict to detect.* ```transcript A> UPDATE doctors SET on_call = false WHERE name = 'alice'; UPDATE 1 B> UPDATE doctors SET on_call = false WHERE name = 'bob'; UPDATE 1 A> COMMIT; COMMIT B> COMMIT; -- both succeed! COMMIT A> SELECT count(*)::int AS on_call FROM doctors WHERE on_call; -- nobody is on call — the invariant is broken on_call --------- 0 (1 row) ``` *Both transactions checked their own snapshots, but the final count is zero. SERIALIZABLE rejects this schedule; coordinating all writers with suitable explicit locks is another approach.* Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/write-skew-rr.yaml) ## postgres/02-isolation/write-skew-serializable.yaml - engine: postgres (PostgreSQL 18.6) - claim: With both transactions SERIALIZABLE, A commits and B's COMMIT fails with 40001 in this schedule; one doctor remains on call. B's fresh transaction observes one and leaves that doctor on call. ```timeline A: on-call count → 2 B: on-call count → 2 A: alice off call B: bob off call A: COMMIT succeeds in this schedule B: COMMIT ← 40001 could not serialize access due to read/write dependencies among transactions ``` *Same story, same statements, same order — only the isolation level differs.* ```transcript A> BEGIN ISOLATION LEVEL SERIALIZABLE; BEGIN B> BEGIN ISOLATION LEVEL SERIALIZABLE; BEGIN A> SELECT count(*)::int AS on_call FROM doctors WHERE on_call; on_call --------- 2 (1 row) B> SELECT count(*)::int AS on_call FROM doctors WHERE on_call; on_call --------- 2 (1 row) A> UPDATE doctors SET on_call = false WHERE name = 'alice'; UPDATE 1 B> UPDATE doctors SET on_call = false WHERE name = 'bob'; UPDATE 1 ``` *In this schedule A commits and B is rejected. Other schedules can fail at a statement or select a different victim.* ```transcript A> COMMIT; COMMIT B> COMMIT; -- serialization_failure ERROR: 40001: could not serialize access due to read/write dependencies among transactions A> SELECT count(*)::int AS on_call FROM doctors WHERE on_call; -- the invariant survived on_call --------- 1 (1 row) ``` *B now starts a fresh transaction, checks the count again, and keeps the remaining doctor on call.* ```transcript B> BEGIN ISOLATION LEVEL SERIALIZABLE; BEGIN B> SELECT count(*)::int AS on_call FROM doctors WHERE on_call; on_call --------- 1 (1 row) B> COMMIT; COMMIT A> SELECT name, on_call FROM doctors ORDER BY name; name | on_call -------+--------- alice | f bob | t (2 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/02-isolation/write-skew-serializable.yaml) ## postgres/03-locking/alter-table-outage.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this schedule ALTER TABLE ADD COLUMN waits behind A's retained ACCESS SHARE, and C's new SELECT waits behind the queued ACCESS EXCLUSIVE request. Both complete after A commits; this is not a universal queue-order guarantee. ```timeline A: SELECT (a long-lived transaction) B: ALTER TABLE … ADD COLUMN → ⏳ waits C: SELECT — just a read! → ⏳ waits A: COMMIT B: ⏵ ALTER TABLE … ADD COLUMN → completes C: ⏵ SELECT — just a read! → completes ``` *A reads accounts inside an explicit transaction and retains its table lock.* ```transcript A> BEGIN; BEGIN A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) ``` *The migration needs ACCESS EXCLUSIVE, so it waits for A. Expected. But now —* ```transcript B> ALTER TABLE accounts ADD COLUMN note text; ⏳ B is waiting for a lock… ``` *C's new SELECT now waits behind the queued ALTER request.* ```transcript C> SELECT balance FROM accounts WHERE id = 1; ⏳ C is waiting for a lock… M> SELECT waiter.application_name AS waiter, blocker.application_name AS blocker FROM pg_stat_activity waiter JOIN pg_stat_activity blocker ON blocker.pid = ANY (pg_blocking_pids(waiter.pid)) WHERE waiter.wait_event_type = 'Lock' ORDER BY waiter.application_name, blocker.application_name; waiter | blocker --------+--------- B | A C | B (2 rows) ``` *A commits; B's standalone ALTER and C's read then complete.* ```transcript A> COMMIT; COMMIT ⏵ B resumes: ALTER TABLE ⏵ C resumes: balance --------- 100 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/03-locking/alter-table-outage.yaml) ## postgres/03-locking/ddl-lock-timeout.yaml - engine: postgres (PostgreSQL 18.6) - claim: B's standalone ALTER waits for a lock and fails with 55P03 under a 100ms lock_timeout. C reads successfully after that request leaves the queue; B's retry after A commits adds the column. ```timeline A: SELECT (long-lived txn) → holds ACCESS SHARE B: ALTER TABLE … → gives up after 100ms ← 55P03 canceling statement due to lock timeout C: SELECT after ALTER timeout → 100 A: COMMIT B: ALTER TABLE … (retry completes) ``` ```transcript A> BEGIN; BEGIN A> SELECT balance FROM accounts WHERE id = 1; -- the same long transaction as before balance --------- 100 (1 row) ``` *Same migration — but this time it gives up after 100ms instead of camping in the queue.* ```transcript B> SET lock_timeout = '100ms'; SET B> ALTER TABLE accounts ADD COLUMN note text; ERROR: 55P03: canceling statement due to lock timeout ``` *After B's timeout removes its request, C's read returns 100. No read during B's wait is tested.* ```transcript C> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) A> COMMIT; COMMIT ``` *Retry the migration when it can actually get the lock — now it sails through.* ```transcript B> ALTER TABLE accounts ADD COLUMN note text; ALTER TABLE C> SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'accounts' AND column_name = 'note'; column_name ------------- note (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/03-locking/ddl-lock-timeout.yaml) ## postgres/03-locking/deadlock-avoidance.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this two-row schedule both transfers lock rows in id order first. B waits for A, then both commit, leaving balances 115 and 85. Other resources and schedules are not tested. ```timeline A: SELECT id IN (1,2) … FOR UPDATE → locks both, in id order B: SELECT id IN (1,2) … FOR UPDATE → ⏳ waits A: COMMIT → releases both B: ⏵ SELECT id IN (1,2) … FOR UPDATE → completes ``` *Both transfers grab *all* their row locks up front, ordered by id.* ```transcript A> BEGIN; BEGIN A> SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE; id ---- 1 2 (2 rows) B> BEGIN; BEGIN B> SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE; ⏳ B is waiting for a lock… ``` *No cycle is possible: B parks at the first row and holds nothing A needs.* ```transcript A> UPDATE accounts SET balance = balance - 10 WHERE id = 1; UPDATE 1 A> UPDATE accounts SET balance = balance + 10 WHERE id = 2; UPDATE 1 A> COMMIT; COMMIT ⏵ B resumes: id ---- 1 2 (2 rows) B> UPDATE accounts SET balance = balance - 25 WHERE id = 2; UPDATE 1 B> UPDATE accounts SET balance = balance + 25 WHERE id = 1; UPDATE 1 B> COMMIT; COMMIT A> SELECT owner, balance FROM accounts ORDER BY id; -- both transfers committed in this schedule owner | balance -------+--------- alice | 115 bob | 85 (2 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/03-locking/deadlock-avoidance.yaml) ## postgres/03-locking/deadlock.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this opposite-order two-row schedule, with B's detection timeout shorter than A's, B gets 40P01, A completes and commits, and the asserted balances retain only A's transfer. General victim choice is not guaranteed. ```timeline A: locks alice (id=1) B: locks bob (id=2) A: needs bob (id=2) → ⏳ waits B: needs alice (id=1) ← 40P01 deadlock detected A: ⏵ needs bob (id=2) → completes ``` ```transcript A> SET deadlock_timeout = '10s'; -- General victim choice must not be relied on. These unequal detection timeouts make B the observed victim in this controlled schedule; no universal minimum cycle duration is asserted. SET B> SET deadlock_timeout = '50ms'; SET ``` *A transfers 10 from alice to bob; B transfers 25 from bob to alice.* ```transcript A> BEGIN; BEGIN A> UPDATE accounts SET balance = balance - 10 WHERE id = 1; -- A locks alice UPDATE 1 B> BEGIN; BEGIN B> UPDATE accounts SET balance = balance - 25 WHERE id = 2; -- B locks bob UPDATE 1 ``` *A now needs bob's row (B has it) — it waits.* ```transcript A> UPDATE accounts SET balance = balance + 10 WHERE id = 2; ⏳ A is waiting for a lock… ``` *B now needs alice's row (A has it). A waits for B, B waits for A: a cycle.* ```transcript B> UPDATE accounts SET balance = balance + 25 WHERE id = 1; -- deadlock_detected — B is aborted… ERROR: 40P01: deadlock detected ``` *The victim's abort frees bob's row, so A's stuck UPDATE completes.* ```transcript ⏵ A resumes: UPDATE 1 A> COMMIT; COMMIT B> ROLLBACK; ROLLBACK A> SELECT owner, balance FROM accounts ORDER BY id; -- A's transfer committed; B's database changes did not commit owner | balance -------+--------- alice | 90 bob | 110 (2 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/03-locking/deadlock.yaml) ## postgres/03-locking/fk-key-share.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this immediate foreign-key insert schedule, B's non-key parent UPDATE succeeds, its DELETE waits for A, and after A commits the DELETE fails with 23503. This conflict signature is consistent with FOR KEY SHARE. ```timeline A: INSERT child → FK locks parent FOR KEY SHARE B: UPDATE parent balance → allowed (non-key) B: DELETE parent → needs FOR UPDATE → ⏳ waits A: COMMIT B: ⏵ DELETE parent → needs FOR UPDATE ← 23503 update or delete on table "customers" violates foreign key constraint "orders_customer_id_fkey" on table "orders" ``` ```transcript A> BEGIN; BEGIN A> INSERT INTO orders VALUES (1, 1); -- FK check locks customers row 1 FOR KEY SHARE INSERT 0 1 ``` *FOR KEY SHARE doesn't mind non-key updates — B can change the balance.* ```transcript B> UPDATE customers SET balance = 50 WHERE id = 1; UPDATE 1 ``` *But DELETE needs the strongest row lock (FOR UPDATE) — B has to wait.* ```transcript B> DELETE FROM customers WHERE id = 1; ⏳ B is waiting for a lock… A> COMMIT; COMMIT ``` *A's order is now committed, so B's DELETE resumes — straight into the FK.* ```transcript ⏵ B's blocked statement fails: ERROR: 23503: update or delete on table "customers" violates foreign key constraint "orders_customer_id_fkey" on table "orders" B> SELECT balance FROM customers WHERE id = 1; -- the parent survived, with B's earlier non-key update intact balance --------- 50 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/03-locking/fk-key-share.yaml) ## postgres/03-locking/for-update-blocks.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this Read Committed schedule B's ordinary SELECT reads 100 while A holds FOR UPDATE; B's UPDATE waits, then uses A's committed 150 to leave 140. Locking reads can conflict; table-lock waits are not excluded. ```timeline A: SELECT … FOR UPDATE (locks the row) B: ordinary SELECT → 100 B: UPDATE -10 → ⏳ waits A: COMMIT (releases the lock) B: ⏵ UPDATE -10 → completes ``` ```transcript A> BEGIN; BEGIN A> SELECT * FROM accounts WHERE id = 1 FOR UPDATE; id | owner | balance ----+-------+--------- 1 | alice | 100 (1 row) ``` *B's ordinary SELECT reads the row without a conflicting row-lock request; cost is not measured.* ```transcript B> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) ``` *Writing to it is another story: B's UPDATE must wait for A.* ```transcript B> UPDATE accounts SET balance = balance - 10 WHERE id = 1; ⏳ B is waiting for a lock… A> UPDATE accounts SET balance = 150 WHERE id = 1; UPDATE 1 A> COMMIT; -- releases the row lock COMMIT ⏵ B resumes: UPDATE 1 B> SELECT balance FROM accounts WHERE id = 1; -- B's -10 applied on top of A's committed 150 balance --------- 140 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/03-locking/for-update-blocks.yaml) ## postgres/03-locking/lock-mode-matrix.yaml - engine: postgres (PostgreSQL 18.6) - claim: This schedule asserts SHARE/SHARE coexistence, SHARE blocking a non-key UPDATE, KEY SHARE coexisting with that UPDATE, and FOR UPDATE waiting for it. The complete compatibility matrix is a manual contract. ```timeline A: SELECT … FOR SHARE (A) B: SELECT … FOR SHARE (B) → coexists B: UPDATE → FOR NO KEY UPDATE → ⏳ waits A: COMMIT (releases A's FOR SHARE) B: ⏵ UPDATE → FOR NO KEY UPDATE → completes A: UPDATE → FOR NO KEY UPDATE (A) B: SELECT … FOR KEY SHARE → coexists with the UPDATE B: SELECT … FOR UPDATE → ⏳ waits A: COMMIT (releases A) B: ⏵ SELECT … FOR UPDATE → completes ``` *Two FOR SHARE locks on the same row coexist happily…* ```transcript A> BEGIN; BEGIN A> SELECT id FROM accounts WHERE id = 1 FOR SHARE; id ---- 1 (1 row) B> BEGIN; BEGIN B> SELECT id FROM accounts WHERE id = 1 FOR SHARE; id ---- 1 (1 row) B> COMMIT; COMMIT ``` *…but FOR SHARE still blocks a plain UPDATE (which takes FOR NO KEY UPDATE).* ```transcript B> UPDATE accounts SET balance = 200 WHERE id = 1; ⏳ B is waiting for a lock… A> COMMIT; COMMIT ⏵ B resumes: UPDATE 1 ``` *The weakest lock, FOR KEY SHARE, even coexists with a running UPDATE…* ```transcript A> BEGIN; BEGIN A> UPDATE accounts SET balance = 300 WHERE id = 1; UPDATE 1 B> SELECT id FROM accounts WHERE id = 1 FOR KEY SHARE; id ---- 1 (1 row) ``` *…while the strongest, FOR UPDATE, has to wait for it.* ```transcript B> SELECT id FROM accounts WHERE id = 1 FOR UPDATE; ⏳ B is waiting for a lock… A> COMMIT; COMMIT ⏵ B resumes: id ---- 1 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/03-locking/lock-mode-matrix.yaml) ## postgres/03-locking/lock-queue-fifo.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this single-row update schedule B completes after A commits while C remains waiting; after B commits C completes, and the balance is 211. This observation does not establish universal FIFO fairness. ```timeline A: UPDATE +1 (takes the row lock) B: UPDATE +10 → ⏳ waits C: UPDATE +100 → ⏳ waits M: who's waiting? → B and C A: COMMIT → lock passes to B B: ⏵ UPDATE +10 → completes B: COMMIT → lock passes to C C: ⏵ UPDATE +100 → completes ``` ```transcript A> BEGIN; BEGIN A> UPDATE accounts SET balance = balance + 1 WHERE id = 1; UPDATE 1 B> BEGIN; BEGIN B> UPDATE accounts SET balance = balance + 10 WHERE id = 1; ⏳ B is waiting for a lock… C> UPDATE accounts SET balance = balance + 100 WHERE id = 1; ⏳ C is waiting for a lock… ``` *A fourth session, M, can watch the pile-up in pg_stat_activity.* ```transcript M> SELECT application_name AS waiting, pg_blocking_pids(pid) AS blocked_by FROM pg_stat_activity WHERE wait_event_type = 'Lock' ORDER BY application_name; waiting | blocked_by ---------+------------ B | {pid(A)} C | {pid(B)} (2 rows) ``` *A commits. B completes while C is observed waiting again.* ```transcript A> COMMIT; COMMIT ⏵ B resumes: UPDATE 1 M> SELECT application_name AS waiting, pg_blocking_pids(pid) AS blocked_by FROM pg_stat_activity WHERE wait_event_type = 'Lock' ORDER BY application_name -- C is still in line, now behind B waiting | blocked_by ---------+------------ C | {pid(B)} (1 row) B> COMMIT; COMMIT ⏵ C resumes: UPDATE 1 C> SELECT balance FROM accounts WHERE id = 1; -- 100 + 1 + 10 + 100 — every update landed, in queue order balance --------- 211 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/03-locking/lock-queue-fifo.yaml) ## postgres/03-locking/lock-timeout.yaml - engine: postgres (PostgreSQL 18.6) - claim: B's standalone UPDATE fails with 55P03 under a 100ms lock_timeout while A holds the row lock. After A commits, B retries successfully and reads 300. lock_timeout limits each acquisition, not total statement time. ```timeline A: UPDATE 200 (locks row 1) B: UPDATE 300 → gives up after 100ms ← 55P03 canceling statement due to lock timeout A: COMMIT B: UPDATE 300 (retry succeeds) ``` ```transcript A> BEGIN; BEGIN A> UPDATE accounts SET balance = 200 WHERE id = 1; UPDATE 1 B> SET lock_timeout = '100ms'; SET ``` *B queues for the row lock like anyone else — but gives up after 100ms.* ```transcript B> UPDATE accounts SET balance = 300 WHERE id = 1; -- lock_not_available, raised after the timeout ERROR: 55P03: canceling statement due to lock timeout ``` *B's failed standalone statement ends its implicit transaction; a fresh attempt after A commits works here.* ```transcript A> COMMIT; COMMIT B> UPDATE accounts SET balance = 300 WHERE id = 1; UPDATE 1 B> SELECT balance FROM accounts WHERE id = 1; balance --------- 300 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/03-locking/lock-timeout.yaml) ## postgres/03-locking/monitoring-locks.yaml - engine: postgres (PostgreSQL 18.6) - claim: For this table and primary index, M asserts four pg_locks entries for A's UPDATE, B's ungranted transaction-id ShareLock, and B's direct blocker A. Ordinary on-disk row locks normally do not appear directly in pg_locks. ```timeline A: UPDATE (takes the row lock) B: UPDATE → waits on A → ⏳ waits A: COMMIT B: ⏵ UPDATE → waits on A → completes ``` ```transcript A> BEGIN; BEGIN A> UPDATE accounts SET balance = 200 WHERE id = 1; UPDATE 1 ``` *This UPDATE's inspected lock entries: table, index, assigned xid and virtual xid.* ```transcript M> SELECT l.locktype, l.relation::regclass AS relation, l.mode, l.granted FROM pg_locks l JOIN pg_stat_activity a ON a.pid = l.pid WHERE a.application_name = 'A' ORDER BY l.locktype, l.relation::regclass::text, l.mode; locktype | relation | mode | granted ---------------+---------------+------------------+--------- relation | accounts | RowExclusiveLock | t relation | accounts_pkey | RowExclusiveLock | t transactionid | | ExclusiveLock | t virtualxid | | ExclusiveLock | t (4 rows) B> UPDATE accounts SET balance = 300 WHERE id = 1; ⏳ B is waiting for a lock… ``` *The waiter's tell: a lock row with granted = f — it wants A's transaction id.* ```transcript M> SELECT l.locktype, l.mode, l.granted FROM pg_locks l JOIN pg_stat_activity a ON a.pid = l.pid WHERE a.application_name = 'B' AND NOT l.granted; locktype | mode | granted ---------------+-----------+--------- transactionid | ShareLock | f (1 row) ``` *You rarely need to decode pg_locks by hand — pg_blocking_pids() names the culprit.* ```transcript M> SELECT waiter.application_name AS waiter, blocker.application_name AS blocker FROM pg_stat_activity waiter JOIN pg_stat_activity blocker ON blocker.pid = ANY (pg_blocking_pids(waiter.pid)) WHERE waiter.wait_event_type = 'Lock' ORDER BY waiter.application_name, blocker.application_name; waiter | blocker --------+--------- B | A (1 row) A> COMMIT; COMMIT ⏵ B resumes: UPDATE 1 ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/03-locking/monitoring-locks.yaml) ## postgres/03-locking/nowait.yaml - engine: postgres (PostgreSQL 18.6) - claim: B's FOR UPDATE NOWAIT gets 55P03 while A holds a conflicting row lock; after A commits, B's standalone retry returns row 1. NOWAIT concerns row locks and does not eliminate table-lock waits or other errors. ```timeline A: SELECT … FOR UPDATE (locks row 1) B: … FOR UPDATE NOWAIT ← 55P03 could not obtain lock on row in relation "accounts" A: COMMIT (releases the lock) B: … NOWAIT → row 1 ``` ```transcript A> BEGIN; BEGIN A> SELECT id FROM accounts WHERE id = 1 FOR UPDATE; id ---- 1 (1 row) B> SELECT id FROM accounts WHERE id = 1 FOR UPDATE NOWAIT; -- lock_not_available from the conflicting row-lock request ERROR: 55P03: could not obtain lock on row in relation "accounts" ``` *Once A is done, the same statement succeeds.* ```transcript A> COMMIT; COMMIT B> SELECT id FROM accounts WHERE id = 1 FOR UPDATE NOWAIT; id ---- 1 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/03-locking/nowait.yaml) ## postgres/03-locking/skip-locked.yaml - engine: postgres (PostgreSQL 18.6) - claim: In overlapping transactions, the scheduled FOR UPDATE SKIP LOCKED reads return jobs 1, 2 and 3, then no available row. After A explicitly rolls back, D reads job 1 again. No external execution or universal no-wait guarantee is established. ```timeline A: SKIP LOCKED → job 1 B: SKIP LOCKED → job 2 (skips 1) C: SKIP LOCKED → job 3 (skips 1, 2) D: SKIP LOCKED → nothing free A: ROLLBACK → job 1 back on the queue D: SKIP LOCKED → job 1 ``` *Four sessions run the same query in the listed order with overlapping transactions.* ```transcript A> BEGIN; BEGIN A> SELECT * FROM jobs ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | task ----+------------ 1 | send email (1 row) B> BEGIN; BEGIN B> SELECT * FROM jobs ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; -- job 1 is locked by A — skipped, no waiting id | task ----+-------------- 2 | resize image (1 row) C> BEGIN; BEGIN C> SELECT * FROM jobs ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | task ----+-------------- 3 | build report (1 row) ``` *D finds no lockable row in this query; three rows still exist.* ```transcript D> SELECT * FROM jobs ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; (0 rows) ``` *Explicit ROLLBACK releases A's row lock; a process crash is not injected.* ```transcript A> ROLLBACK; ROLLBACK D> SELECT * FROM jobs ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | task ----+------------ 1 | send email (1 row) B> COMMIT; COMMIT C> COMMIT; COMMIT ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/03-locking/skip-locked.yaml) ## postgres/04-mvcc/dead-tuples-and-bloat.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this setup three updates leave four inspected tuple versions and one live value. Updating 1000 rows grows the heap from 5 to 9 pages; deleting them leaves zero live rows and 9 pages at the next observation. Reuse, pruning and vacuum can change later size. ```transcript A> INSERT INTO counters VALUES (1, 0) RETURNING xmin, n; xmin | n ------+--- 1001 | 0 (1 row) ``` *Three updates to one row. Watch each one get a fresh xid — and leave a corpse.* ```transcript A> UPDATE counters SET n = 1 WHERE id = 1 RETURNING xmin, n; xmin | n ------+--- 1002 | 1 (1 row) A> UPDATE counters SET n = 2 WHERE id = 1 RETURNING xmin, n; xmin | n ------+--- 1003 | 2 (1 row) A> UPDATE counters SET n = 3 WHERE id = 1 RETURNING xmin, n; xmin | n ------+--- 1004 | 3 (1 row) ``` *SELECT sees one row. The page holds four tuples — a version chain, three of them dead.* ```transcript A> SELECT n FROM counters; n --- 3 (1 row) A> SELECT lp, t_xmin, t_xmax, t_ctid FROM heap_page_items(get_raw_page('counters', 0)) ORDER BY lp; lp | t_xmin | t_xmax | t_ctid ----+--------+--------+-------- 1 | 1001 | 1002 | (0,2) 2 | 1002 | 1003 | (0,3) 3 | 1003 | 1004 | (0,4) 4 | 1004 | 0 | (0,4) (4 rows) ``` *The same effect at scale: 1000 rows fit in 5 pages of 8 kB.* ```transcript A> INSERT INTO bloat SELECT g, 'x' FROM generate_series(1, 1000) g; INSERT 0 1000 A> SELECT (pg_relation_size('bloat') / 8192)::int AS pages; pages ------- 5 (1 row) ``` *This UPDATE of all 1000 rows grows the heap from 5 to 9 pages, not an exact doubling.* ```transcript A> UPDATE bloat SET filler = 'y'; UPDATE 1000 A> SELECT (pg_relation_size('bloat') / 8192)::int AS pages; pages ------- 9 (1 row) ``` *Now delete everything. Zero rows — and not a single byte returned.* ```transcript A> DELETE FROM bloat; DELETE 1000 A> SELECT count(*)::int AS live_rows FROM bloat; live_rows ----------- 0 (1 row) A> SELECT (pg_relation_size('bloat') / 8192)::int AS pages; pages ------- 9 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/04-mvcc/dead-tuples-and-bloat.yaml) ## postgres/04-mvcc/long-transactions.ts - engine: postgres (PostgreSQL 18.6) - claim: With A holding an old Repeatable Read snapshot, VACUUM leaves the inspected jobs tuple-chain fields unchanged and A still reads new. After A commits, a second VACUUM reclaims the three obsolete versions. Other tables and other VACUUM work are not observed. *A opens a long report transaction — one query, then it sits there idle.* ```transcript A> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN A> SELECT xmin, id, status FROM jobs; xmin | id | status ------+----+-------- 1001 | 1 | new (1 row) ``` *Meanwhile B churns through the row, leaving dead versions behind.* ```transcript B> UPDATE jobs SET status = 'running' WHERE id = 1 RETURNING xmin, status; xmin | status ------+--------- 1002 | running (1 row) B> UPDATE jobs SET status = 'done' WHERE id = 1 RETURNING xmin, status; xmin | status ------+-------- 1003 | done (1 row) B> UPDATE jobs SET status = 'archived' WHERE id = 1 RETURNING xmin, status; xmin | status ------+---------- 1004 | archived (1 row) B> SELECT lp, t_xmin, t_xmax, t_ctid FROM heap_page_items(get_raw_page('jobs', 0)) ORDER BY lp; lp | t_xmin | t_xmax | t_ctid ----+--------+--------+-------- 1 | 1001 | 1002 | (0,2) 2 | 1002 | 1003 | (0,3) 3 | 1003 | 1004 | (0,4) 4 | 1004 | 0 | (0,4) (4 rows) B> VACUUM jobs; VACUUM ``` *VACUUM completed. The following assertion checks unchanged tuple-chain fields while A retains its old snapshot.* ```transcript B> SELECT lp, t_xmin, t_xmax, t_ctid FROM heap_page_items(get_raw_page('jobs', 0)) ORDER BY lp; lp | t_xmin | t_xmax | t_ctid ----+--------+--------+-------- 1 | 1001 | 1002 | (0,2) 2 | 1002 | 1003 | (0,3) 3 | 1003 | 1004 | (0,4) 4 | 1004 | 0 | (0,4) (4 rows) ``` *And indeed: A still reads the version from before all three updates.* ```transcript A> SELECT id, status FROM jobs; id | status ----+-------- 1 | new (1 row) A> COMMIT; COMMIT B> VACUUM jobs; VACUUM ``` *Same command, a moment after A commits — now the three dead versions are gone.* ```transcript B> SELECT lp, lp_flags, t_xmin, t_xmax, t_ctid FROM heap_page_items(get_raw_page('jobs', 0)) ORDER BY lp; lp | lp_flags | t_xmin | t_xmax | t_ctid ----+----------+--------+--------+-------- 1 | 2 | | | 2 | 0 | | | 3 | 0 | | | 4 | 1 | 1004 | 0 | (0,4) (4 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/04-mvcc/long-transactions.ts) ## postgres/04-mvcc/row-versions.ts - engine: postgres (PostgreSQL 18.6) - claim: In this setup UPDATE creates a new tuple at (0,2), while B's old Repeatable Read snapshot still reads the original balance at (0,1). After DELETE there are zero live rows but both tuple versions remain in the inspected page. This is not a promise of permanent physical retention. *Inspect this tuple version: xmin identifies its inserting transaction, ctid its physical location. xmax can record deletion or row locking; this schedule follows the update/delete case.* ```transcript A> SELECT xmin, xmax, ctid, balance FROM accounts WHERE id = 1; xmin | xmax | ctid | balance ------+------+-------+--------- 1001 | 0 | (0,1) | 100 (1 row) B> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN B> SELECT xmin, xmax, ctid, balance FROM accounts WHERE id = 1; xmin | xmax | ctid | balance ------+------+-------+--------- 1001 | 0 | (0,1) | 100 (1 row) ``` *A's UPDATE creates a new tuple version and changes the old version's xmax and successor pointer.* ```transcript A> UPDATE accounts SET balance = 200 WHERE id = 1 RETURNING xmin, xmax, ctid, balance; xmin | xmax | ctid | balance ------+------+-------+--------- 1002 | 0 | (0,2) | 200 (1 row) ``` *B still reads the old version — but its xmax is no longer 0: A's xid is stamped on it.* ```transcript B> SELECT xmin, xmax, ctid, balance FROM accounts WHERE id = 1; xmin | xmax | ctid | balance ------+------+-------+--------- 1001 | 1002 | (0,1) | 100 (1 row) B> COMMIT; COMMIT B> SELECT xmin, xmax, ctid, balance FROM accounts WHERE id = 1; xmin | xmax | ctid | balance ------+------+-------+--------- 1002 | 0 | (0,2) | 200 (1 row) ``` *pageinspect shows both versions physically on page 0 — the old one points at its successor.* ```transcript A> SELECT lp, t_xmin, t_xmax, t_ctid FROM heap_page_items(get_raw_page('accounts', 0)) ORDER BY lp; lp | t_xmin | t_xmax | t_ctid ----+--------+--------+-------- 1 | 1001 | 1002 | (0,2) 2 | 1002 | 0 | (0,2) (2 rows) ``` *DELETE marks the current version deleted; the following page inspection checks that its tuple body remains here.* ```transcript A> DELETE FROM accounts WHERE id = 1 RETURNING xmin, xmax, ctid; xmin | xmax | ctid ------+------+------- 1002 | 1003 | (0,2) (1 row) A> SELECT count(*)::int AS live_rows FROM accounts; live_rows ----------- 0 (1 row) ``` *Zero rows for SELECT — yet both versions are still on disk, awaiting VACUUM.* ```transcript A> SELECT lp, t_xmin, t_xmax, t_ctid FROM heap_page_items(get_raw_page('accounts', 0)) ORDER BY lp; lp | t_xmin | t_xmax | t_ctid ----+--------+--------+-------- 1 | 1001 | 1002 | (0,2) 2 | 1002 | 1003 | (0,2) (2 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/04-mvcc/row-versions.ts) ## postgres/04-mvcc/snapshots-under-the-hood.ts - engine: postgres (PostgreSQL 18.6) - claim: C's Repeatable Read snapshot records A as in progress and B as completed. C reads A's old value and B's committed value, repeats that view after A commits, then sees A's new value in a fresh transaction. The exposed snapshot components are not the complete tuple-visibility algorithm. *A's initial ordinary read does not assign an xid; pg_current_xact_id() could assign one without a table write.* ```transcript A> BEGIN; BEGIN A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) A> SELECT pg_current_xact_id_if_assigned() AS xid; xid ----- (1 row) A> UPDATE accounts SET balance = 150 WHERE id = 1; UPDATE 1 A> SELECT pg_current_xact_id_if_assigned() AS xid; xid ------ 1001 (1 row) ``` *B grabs the next xid and commits immediately. A is still in progress.* ```transcript B> UPDATE accounts SET balance = 200 WHERE id = 2 RETURNING xmin, balance; xmin | balance ------+--------- 1002 | 200 (1 row) ``` *C inspects its retained snapshot bounds; commit status and tuple metadata also matter for visibility.* ```transcript C> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN C> SELECT pg_snapshot_xmin(pg_current_snapshot()) AS xmin, pg_snapshot_xmax(pg_current_snapshot()) AS xmax; xmin | xmax ------+------ 1001 | 1003 (1 row) ``` *xip = the xids that were in progress at snapshot time. A is on the list — so A is invisible even after it commits.* ```transcript C> SELECT pg_snapshot_xip(pg_current_snapshot()) AS xid; xid ------ 1001 (1 row) ``` *The arithmetic in action: B (committed, below xmax) is visible; A (in xip) is not.* ```transcript C> SELECT id, owner, balance FROM accounts ORDER BY id; id | owner | balance ----+-------+--------- 1 | alice | 100 2 | bob | 200 (2 rows) A> COMMIT; COMMIT ``` *A has now committed — but C's snapshot already decided: still invisible.* ```transcript C> SELECT id, owner, balance FROM accounts ORDER BY id; id | owner | balance ----+-------+--------- 1 | alice | 100 2 | bob | 200 (2 rows) C> COMMIT; COMMIT ``` *C's fresh transaction now reads A's committed value; own-write visibility is a separate rule.* ```transcript C> SELECT id, owner, balance FROM accounts ORDER BY id; id | owner | balance ----+-------+--------- 1 | alice | 150 2 | bob | 200 (2 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/04-mvcc/snapshots-under-the-hood.ts) ## postgres/04-mvcc/vacuum.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this setup VACUUM frees inspected counters slots and the next INSERT reuses slot 2. Standard VACUUM leaves bloat at 9 pages; VACUUM FULL compacts it to 5. Standard VACUUM can truncate empty trailing pages under suitable locking conditions, a variant not executed here. *Three updates leave three dead tuples on the page (the bloat lesson showed the chain).* ```transcript A> UPDATE counters SET n = 1 WHERE id = 1; UPDATE 1 A> UPDATE counters SET n = 2 WHERE id = 1; UPDATE 1 A> UPDATE counters SET n = 3 WHERE id = 1 RETURNING xmin, n; xmin | n ------+--- 1001 | 3 (1 row) A> VACUUM counters; VACUUM ``` *After VACUUM: slot 1 is a redirect to the live version, slots 2–3 are unused (reusable), only slot 4 still holds a tuple. The corpses are gone.* ```transcript A> SELECT lp, lp_flags, t_xmin, t_xmax, t_ctid FROM heap_page_items(get_raw_page('counters', 0)) ORDER BY lp; lp | lp_flags | t_xmin | t_xmax | t_ctid ----+----------+--------+--------+-------- 1 | 2 | | | 2 | 0 | | | 3 | 0 | | | 4 | 1 | 1001 | 0 | (0,4) (4 rows) ``` *The freed space is immediately reusable: the next INSERT lands in slot 2.* ```transcript A> INSERT INTO counters VALUES (2, 0) RETURNING ctid, id; ctid | id -------+---- (0,2) | 2 (1 row) ``` *At file level this 1000-row heap grows from 5 to 9 pages after UPDATE.* ```transcript A> SELECT (pg_relation_size('bloat') / 8192)::int AS pages; pages ------- 5 (1 row) A> UPDATE bloat SET filler = 'y'; UPDATE 1000 A> SELECT (pg_relation_size('bloat') / 8192)::int AS pages; pages ------- 9 (1 row) A> VACUUM bloat; VACUUM ``` *Standard VACUUM completes and the asserted file size remains 9 pages. This size observation does not count reclaimed tuples or reusable bytes.* ```transcript A> SELECT (pg_relation_size('bloat') / 8192)::int AS pages; pages ------- 9 (1 row) A> VACUUM FULL bloat; VACUUM ``` *VACUUM FULL rewrites the table from scratch — back to 5 pages. The price: it holds ACCESS EXCLUSIVE for the whole rewrite.* ```transcript A> SELECT (pg_relation_size('bloat') / 8192)::int AS pages; pages ------- 5 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/04-mvcc/vacuum.yaml) ## postgres/05-patterns/advisory-locks.yaml - engine: postgres (PostgreSQL 18.6) - claim: With these exclusive advisory keys, B's try-lock returns false while A holds the key, and a blocking acquisition waits for unlock. COMMIT leaves the session-level key held but releases the transaction-level key. ```timeline A: lock(42) → held B: try-lock(42) → false (no wait) B: lock(42) → ⏳ waits A: unlock(42) B: ⏵ lock(42) → completes ``` *Two deploy runners must not migrate the same database at once. They agree lock 42 means 'migration in progress'.* ```transcript A> SELECT pg_advisory_lock(42); pg_advisory_lock ------------------ (1 row) B> SELECT pg_try_advisory_lock(42) AS got_it; -- false without waiting to acquire this advisory lock; latency is not measured got_it -------- f (1 row) ``` *try-lock says no without waiting. A runner can also queue up for the lock:* ```transcript B> SELECT pg_advisory_lock(42); ⏳ B is waiting for a lock… A> SELECT pg_advisory_unlock(42) AS released; released ---------- t (1 row) ⏵ B resumes: pg_advisory_lock ------------------ (1 row) ``` *COMMIT does not release A's session-level advisory lock on key 9.* ```transcript A> BEGIN; BEGIN A> SELECT pg_advisory_lock(9); pg_advisory_lock ------------------ (1 row) A> COMMIT; COMMIT B> SELECT pg_try_advisory_lock(9) AS got_it; got_it -------- f (1 row) A> SELECT pg_advisory_unlock(9) AS released; released ---------- t (1 row) ``` *After A commits, the next try-lock checks that its transaction-level key 7 is available.* ```transcript A> BEGIN; BEGIN A> SELECT pg_advisory_xact_lock(7); pg_advisory_xact_lock ----------------------- (1 row) B> SELECT pg_try_advisory_lock(7) AS got_it; got_it -------- f (1 row) A> COMMIT; COMMIT B> SELECT pg_try_advisory_lock(7) AS got_it; -- freed by A's COMMIT alone got_it -------- t (1 row) B> SELECT pg_advisory_unlock(7); pg_advisory_unlock -------------------- t (1 row) B> SELECT pg_advisory_unlock(42); pg_advisory_unlock -------------------- t (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/05-patterns/advisory-locks.yaml) ## postgres/05-patterns/check-then-insert-race.yaml - engine: postgres (PostgreSQL 18.6) - claim: At READ COMMITTED without a UNIQUE email constraint, two concurrent check-then-insert requests both see zero matching rows, both insert, and the final email count is two. Neither insertion errors in this schedule. ```timeline A: any bob? → 0 B: any bob? → 0 A: INSERT bob A: COMMIT B: INSERT bob (check already passed) B: COMMIT A: count bobs → 2 — the "impossible" duplicate ``` *The same person double-clicks 'Sign up'. Two app servers each run: check, then insert.* ```transcript A> BEGIN; BEGIN A> SELECT count(*)::int AS existing FROM signups WHERE email = 'bob@example.com'; existing ---------- 0 (1 row) B> BEGIN; BEGIN B> SELECT count(*)::int AS existing FROM signups WHERE email = 'bob@example.com'; -- B's check also passes — A hasn't committed anything existing ---------- 0 (1 row) ``` *Both checks passed, so both insert. Nothing blocks, nothing errors.* ```transcript A> INSERT INTO signups (email) VALUES ('bob@example.com'); INSERT 0 1 A> COMMIT; COMMIT B> INSERT INTO signups (email) VALUES ('bob@example.com'); INSERT 0 1 B> COMMIT; COMMIT A> SELECT count(*)::int AS bobs FROM signups WHERE email = 'bob@example.com'; -- the "impossible" duplicate bobs ------ 2 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/05-patterns/check-then-insert-race.yaml) ## postgres/05-patterns/checked-stock.yaml - engine: postgres (PostgreSQL 18.6) - claim: Two buyers each request four of five units. B waits for A; after A commits, B's checked decrement affects zero rows and B rolls back. One unit remains. A subsequent unguarded decrement leaves minus three. ```transcript A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN B> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> UPDATE stock SET quantity = quantity - 4 WHERE id = 1 AND quantity >= 4; UPDATE 1 B> UPDATE stock SET quantity = quantity - 4 WHERE id = 1 AND quantity >= 4; ⏳ B is waiting for a lock… A> COMMIT; COMMIT ⏵ B resumes: UPDATE 0 B> ROLLBACK; ROLLBACK A> SELECT quantity FROM stock WHERE id = 1; quantity ---------- 1 (1 row) ``` *Contrast an unconditional decrement after the checked rejection. This deliberately breaks the stock rule.* ```transcript B> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN B> UPDATE stock SET quantity = quantity - 4 WHERE id = 1; UPDATE 1 B> COMMIT; COMMIT A> SELECT quantity FROM stock WHERE id = 1; quantity ---------- -3 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/05-patterns/checked-stock.yaml) ## postgres/05-patterns/fix-lost-update-atomic.yaml - engine: postgres (PostgreSQL 18.6) - claim: At READ COMMITTED, two relative single-row balance increments serialize: B waits for A's commit and returns 120; the final balance is 120. *Same two +10 deposits that lost an update in chapter 2 — but the math moved into the UPDATE itself.* ```transcript A> BEGIN; BEGIN A> UPDATE accounts SET balance = balance + 10 WHERE id = 1 RETURNING balance; balance --------- 110 (1 row) B> BEGIN; BEGIN B> UPDATE accounts SET balance = balance + 10 WHERE id = 1 RETURNING balance; ⏳ B is waiting for a lock… ``` *No stale read exists to write back: B waits for A's row lock, then re-reads the committed 110.* ```transcript A> COMMIT; COMMIT ⏵ B resumes: balance --------- 120 (1 row) B> COMMIT; COMMIT A> SELECT balance FROM accounts WHERE id = 1; -- both deposits survived balance --------- 120 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/05-patterns/fix-lost-update-atomic.yaml) ## postgres/05-patterns/fix-lost-update-for-update.yaml - engine: postgres (PostgreSQL 18.6) - claim: At READ COMMITTED, both writers lock before reading and update within the same transaction. B waits and reads A's committed 110; the final balance is 120. Other writer protocols and external effects are not tested. *The app must apply business rules to the balance in code — so it locks the row while it reads.* ```transcript A> BEGIN; BEGIN A> SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; balance --------- 100 (1 row) B> BEGIN; BEGIN B> SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; ⏳ B is waiting for a lock… A> UPDATE accounts SET balance = 100 + 10 WHERE id = 1; UPDATE 1 A> COMMIT; COMMIT ``` *B's locking read waited for A's transaction. The next assertion checks that it returns 110.* ```transcript ⏵ B resumes: balance --------- 110 (1 row) B> UPDATE accounts SET balance = 110 + 10 WHERE id = 1; UPDATE 1 B> COMMIT; COMMIT A> SELECT balance FROM accounts WHERE id = 1; -- both deposits survived balance --------- 120 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/05-patterns/fix-lost-update-for-update.yaml) ## postgres/05-patterns/fix-lost-update-version-column.yaml - engine: postgres (PostgreSQL 18.6) - claim: At READ COMMITTED, B's stale version predicate affects zero rows. B rolls back, rereads, and reapplies its additive deposit; the final balance is 120 and version 3. Both writers check and advance the version. *Both writers read the row and version without taking a FOR UPDATE row lock. Their transactions still acquire table locks.* ```transcript A> BEGIN; BEGIN A> SELECT balance, version FROM accounts WHERE id = 1; balance | version ---------+--------- 100 | 1 (1 row) B> BEGIN; BEGIN B> SELECT balance, version FROM accounts WHERE id = 1; balance | version ---------+--------- 100 | 1 (1 row) ``` *Every write bumps the version and only matches the version it read.* ```transcript A> UPDATE accounts SET balance = 100 + 10, version = version + 1 WHERE id = 1 AND version = 1; UPDATE 1 A> COMMIT; COMMIT B> UPDATE accounts SET balance = 100 + 10, version = version + 1 WHERE id = 1 AND version = 1; -- UPDATE 0 — the row moved on; B's deposit did NOT silently vanish UPDATE 0 ``` *For this additive deposit, B retries after UPDATE 0. Other applications may need to report or reconsider a stale edit; deletion can also yield zero rows.* ```transcript B> ROLLBACK; ROLLBACK B> BEGIN; BEGIN B> SELECT balance, version FROM accounts WHERE id = 1; balance | version ---------+--------- 110 | 2 (1 row) B> UPDATE accounts SET balance = 110 + 10, version = version + 1 WHERE id = 1 AND version = 2; UPDATE 1 B> COMMIT; COMMIT A> SELECT balance, version FROM accounts WHERE id = 1; -- both deposits survived balance | version ---------+--------- 120 | 3 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/05-patterns/fix-lost-update-version-column.yaml) ## postgres/05-patterns/idempotency-key.yaml - engine: postgres (PostgreSQL 18.6) - claim: At READ COMMITTED, a payment key and balance update commit together. The two demonstrated same-key duplicates, one after commit and one in flight, insert no row; the final balance is 45. No remote charge is tested. *The client sends 'charge $30' with idempotency key req-42. Server A processes it.* ```transcript A> BEGIN; BEGIN A> INSERT INTO payments VALUES ('req-42', 30) ON CONFLICT (idempotency_key) DO NOTHING RETURNING idempotency_key; -- a row came back: this key is new — do the work idempotency_key ----------------- req-42 (1 row) A> UPDATE accounts SET balance = balance - 30 WHERE id = 1; UPDATE 1 A> COMMIT; COMMIT ``` *B repeats the same key after commit. No response loss or network fault is injected.* ```transcript B> BEGIN; BEGIN B> INSERT INTO payments VALUES ('req-42', 30) ON CONFLICT (idempotency_key) DO NOTHING RETURNING idempotency_key; -- 0 rows for this retained key: skip the balance change and read the stored amount INSERT 0 0 B> SELECT amount FROM payments WHERE idempotency_key = 'req-42'; amount -------- 30 (1 row) B> COMMIT; COMMIT A> SELECT balance FROM accounts WHERE id = 1; -- charged exactly once balance --------- 70 (1 row) ``` *The nasty case: the retry arrives while the original is still in flight, uncommitted.* ```transcript A> BEGIN; BEGIN A> INSERT INTO payments VALUES ('req-99', 25) ON CONFLICT (idempotency_key) DO NOTHING RETURNING idempotency_key; idempotency_key ----------------- req-99 (1 row) A> UPDATE accounts SET balance = balance - 25 WHERE id = 1; UPDATE 1 B> INSERT INTO payments VALUES ('req-99', 25) ON CONFLICT (idempotency_key) DO NOTHING RETURNING idempotency_key; ⏳ B is waiting for a lock… ``` *The unique index parks the retry until the original decides. A commits — the retry absorbs to 0 rows.* ```transcript A> COMMIT; COMMIT ⏵ B resumes: INSERT 0 0 ``` *This in-flight duplicate inserted no row. The next assertion checks database-local charges only.* ```transcript A> SELECT balance FROM accounts WHERE id = 1; -- 100 - 30 - 25: every charge applied exactly once balance --------- 45 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/05-patterns/idempotency-key.yaml) ## postgres/05-patterns/idle-in-transaction-timeout.yaml - engine: postgres (PostgreSQL 18.6) - claim: With idle_in_transaction_session_timeout set to 500ms, A goes idle after an UPDATE. After a 1500ms wait the monitor finds no A session, COMMIT sees a closed connection, and the order remains pending. No ORM or API runs. *A opens a transaction and updates a row. A sleep models idle client time; no ORM or external API is executed.* ```transcript A> SET idle_in_transaction_session_timeout = '500ms'; SET A> BEGIN; BEGIN A> UPDATE orders SET status = 'paid' WHERE id = 1; UPDATE 1 ``` *From the outside this is the classic pathology — a session holding locks while doing nothing:* ```transcript M> SELECT state FROM pg_stat_activity WHERE application_name = 'A'; state --------------------- idle in transaction (1 row) ``` *The modeled idle time exceeds the configured timeout. The next queries check session absence and client failure; no server log is captured.* ```transcript M> SELECT state FROM pg_stat_activity WHERE application_name = 'A'; -- the backend is gone (0 rows) ``` *The app finds out only when it finally comes back to commit:* ```transcript A> COMMIT; ERROR: ERR_POSTGRES_CONNECTION_CLOSED: Connection closed M> SELECT status FROM orders WHERE id = 1; -- the UPDATE was rolled back with the killed session status --------- pending (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/05-patterns/idle-in-transaction-timeout.yaml) ## postgres/05-patterns/job-queue.yaml - engine: postgres (PostgreSQL 18.6) - claim: At READ COMMITTED, two workers select different available jobs with FOR UPDATE SKIP LOCKED. An explicit rollback leaves job 2 queued for selection again; both jobs end in state done. No external task execution is tested. ```timeline A: claim → job 1 B: claim → job 2 (skips locked job 1) A: job 1 done A: COMMIT B: ROLLBACK → job 2 remains queued B: claim → job 2 (back in queue) B: job 2 done B: COMMIT A: both jobs done ``` *Two workers select available queued rows in id order and mark database state done. Task names are data; no email or invoice is executed.* ```transcript A> BEGIN; BEGIN A> SELECT id, task FROM jobs WHERE state = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | task ----+-------------------- 1 | send welcome email (1 row) B> BEGIN; BEGIN B> SELECT id, task FROM jobs WHERE state = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; -- job 1 is claimed — skipped without waiting id | task ----+------------------ 2 | generate invoice (1 row) ``` *A marks job 1 done and commits. B explicitly rolls back; no worker process is killed.* ```transcript A> UPDATE jobs SET state = 'done' WHERE id = 1; UPDATE 1 A> COMMIT; COMMIT B> ROLLBACK; ROLLBACK ``` *B selects job 2 again after rollback. This checks row availability, not the number of external effects.* ```transcript B> BEGIN; BEGIN B> SELECT id, task FROM jobs WHERE state = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | task ----+------------------ 2 | generate invoice (1 row) B> UPDATE jobs SET state = 'done' WHERE id = 2; UPDATE 1 B> COMMIT; COMMIT A> SELECT id, state FROM jobs ORDER BY id; id | state ----+------- 1 | done 2 | done (2 rows) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/05-patterns/job-queue.yaml) ## postgres/05-patterns/on-conflict.yaml - engine: postgres (PostgreSQL 18.6) - claim: At READ COMMITTED with UNIQUE on a non-NULL email, B's duplicate waits for A's commit then fails with 23505. DO NOTHING affects zero rows; DO UPDATE returns the existing id and email in the shown statements. ```timeline A: INSERT bob B: INSERT bob (duplicate) → ⏳ waits A: COMMIT B: ⏵ INSERT bob (duplicate) ← 23505 duplicate key value violates unique constraint "signups_email_key" ``` *Same double-click, but now the table has UNIQUE (email).* ```transcript A> BEGIN; BEGIN A> INSERT INTO signups (email) VALUES ('bob@example.com'); INSERT 0 1 ``` *B's insert can't decide yet — the winner hasn't committed. It waits on A's transaction.* ```transcript B> INSERT INTO signups (email) VALUES ('bob@example.com'); ⏳ B is waiting for a lock… A> COMMIT; COMMIT ⏵ B's blocked statement fails: ERROR: 23505: duplicate key value violates unique constraint "signups_email_key" ``` *unique_violation — the race is now loud instead of silent.* *ON CONFLICT DO NOTHING absorbs the duplicate instead of erroring:* ```transcript B> INSERT INTO signups (email) VALUES ('bob@example.com') ON CONFLICT (email) DO NOTHING; -- INSERT 0 0 INSERT 0 0 ``` *And DO UPDATE makes it an upsert — here just to read back the existing row's id:* ```transcript B> INSERT INTO signups (email) VALUES ('bob@example.com') ON CONFLICT (email) DO UPDATE SET email = EXCLUDED.email RETURNING id, email; id | email ----+----------------- 1 | bob@example.com (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/05-patterns/on-conflict.yaml) ## postgres/05-patterns/retry-serialization-failures.ts - engine: postgres (PostgreSQL 18.6) - claim: In this forced REPEATABLE READ conflict, B rolls back after 40001 and retries with fresh reads: two attempts produce balance 115. Eventual success is not guaranteed. ```transcript B> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN B> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) ``` *B read 100. Before it writes, A commits a conflicting deposit — B's write is now doomed.* ```transcript A> UPDATE accounts SET balance = balance + 10 WHERE id = 1; UPDATE 1 B> UPDATE accounts SET balance = 105 WHERE id = 1; ERROR: 40001: could not serialize access due to concurrent update B> ROLLBACK; ROLLBACK B> BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN B> SELECT balance FROM accounts WHERE id = 1; balance --------- 110 (1 row) ``` *Attempt 2 is a brand-new transaction: it reads 110 — the state that made attempt 1 impossible.* ```transcript B> UPDATE accounts SET balance = 115 WHERE id = 1; UPDATE 1 B> COMMIT; COMMIT A> SELECT balance FROM accounts WHERE id = 1; balance --------- 115 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/05-patterns/retry-serialization-failures.ts) ## postgres/05-patterns/stale-edit.yaml - engine: postgres (PostgreSQL 18.6) - claim: Both editors load version 1 outside their save transactions. A saves version 2. B's version-1 replacement affects zero rows; after rollback a fresh read still returns A's text and version 2. Then blindly using the latest version with B's old draft replaces A's edit. ```transcript A> SELECT body, version FROM documents WHERE id = 1; body | version ----------+--------- Original | 1 (1 row) B> SELECT body, version FROM documents WHERE id = 1; body | version ----------+--------- Original | 1 (1 row) A> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN A> UPDATE documents SET body = 'A edit', version = version + 1 WHERE id = 1 AND version = 1; UPDATE 1 A> COMMIT; COMMIT B> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN B> UPDATE documents SET body = 'B edit', version = version + 1 WHERE id = 1 AND version = 1; UPDATE 0 B> ROLLBACK; ROLLBACK B> SELECT body, version FROM documents WHERE id = 1; body | version --------+--------- A edit | 2 (1 row) ``` *Contrast blindly substituting the latest version while keeping B's old draft. This deliberately replaces A's edit.* ```transcript B> BEGIN ISOLATION LEVEL READ COMMITTED; BEGIN B> UPDATE documents SET body = 'B edit', version = version + 1 WHERE id = 1 AND version = 2; UPDATE 1 B> COMMIT; COMMIT A> SELECT body, version FROM documents WHERE id = 1; body | version --------+--------- B edit | 3 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/05-patterns/stale-edit.yaml) ## postgres/06-distributed/dual-write-problem.yaml - engine: postgres (PostgreSQL 18.6) - claim: Separate commits in one database model a dual-write boundary: omitting a broker-table insert leaves one order without an event; a CHECK failure after a broker-table insert leaves one event without its order. *Attempt 1 — write, then publish. The order commits…* ```transcript App> BEGIN; BEGIN App> INSERT INTO orders VALUES (1, 'alice', 90); INSERT 0 1 App> COMMIT; COMMIT ``` *Publication is deliberately omitted. No process crashes; the broker table has no order-1 event.* ```transcript App> SELECT (SELECT count(*)::int FROM orders) AS orders, (SELECT count(*)::int FROM broker) AS events; orders | events --------+-------- 1 | 0 (1 row) ``` *Attempt 2 — publish first, then write. The event goes out…* ```transcript App> INSERT INTO broker VALUES ('order_placed: order 2'); INSERT 0 1 ``` *The order INSERT fails its CHECK constraint after the separately committed broker record.* ```transcript App> INSERT INTO orders VALUES (2, 'mallory', -5); -- check_violation ERROR: 23514: new row for relation "orders" violates check constraint "orders_amount_check" ``` *The receiver table has an event without an order. No downstream service is executed.* ```transcript App> SELECT (SELECT count(*)::int FROM orders WHERE id = 2) AS orders, (SELECT count(*)::int FROM broker WHERE event LIKE '%order 2%') AS events; orders | events --------+-------- 0 | 1 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/06-distributed/dual-write-problem.yaml) ## postgres/06-distributed/listen-notify.ts - engine: postgres (PostgreSQL 18.6) - claim: With a psql listener already registered, this run observes silence before COMMIT and after ROLLBACK, a payload after COMMIT, and one payload for two identical same-transaction notifications within the observation windows. *A psql process is attached and ran LISTEN orders; — a separate client, not one of our sessions.* ```transcript A> SELECT pg_backend_pid() AS pid; pid -------- pid(A) (1 row) A> BEGIN; BEGIN A> INSERT INTO orders VALUES (1, 'alice'); INSERT 0 1 A> NOTIFY orders, 'order 1 placed'; NOTIFY ``` *The listener hears nothing — the notification is queued inside A's transaction.* ```transcript A> COMMIT; COMMIT ``` *The listener wakes up: Asynchronous notification "orders" with payload "order 1 placed" received from server process with PID pid(A).* *A rolled-back NOTIFY never happened at all:* ```transcript A> BEGIN; BEGIN A> NOTIFY orders, 'order 2 placed'; NOTIFY A> ROLLBACK; ROLLBACK ``` *Silence — order 2's notification died with its transaction.* *Identical notifications in one transaction are de-duplicated:* ```transcript A> BEGIN; BEGIN A> NOTIFY orders, 'order 3 placed'; NOTIFY A> NOTIFY orders, 'order 3 placed'; NOTIFY A> COMMIT; COMMIT ``` *Two NOTIFYs went in, one notification came out.* Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/06-distributed/listen-notify.ts) ## postgres/06-distributed/saga-compensation.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this two-table saga model, a READ COMMITTED Reader sees four flight seats after the first commit. A hotel update affects zero rows, then a new compensating transaction restores five seats. No remote service runs. *Step 1 — book the flight. A local transaction, committed immediately.* ```transcript Saga> BEGIN; BEGIN Saga> UPDATE flights SET seats = seats - 1 WHERE id = 1 RETURNING seats; seats ------- 4 (1 row) Saga> COMMIT; COMMIT ``` *There is no enclosing transaction across steps. This standalone READ COMMITTED Reader sees the committed intermediate seat count.* ```transcript Reader> SELECT seats FROM flights WHERE id = 1; seats ------- 4 (1 row) ``` *Step 2 — book the hotel. No rooms left: the step fails as a business outcome, not an error.* ```transcript Saga> BEGIN; BEGIN Saga> UPDATE hotels SET rooms = rooms - 1 WHERE id = 1 AND rooms > 0; -- UPDATE 0 — nothing to book UPDATE 0 Saga> ROLLBACK; ROLLBACK ``` *Step 1 already committed — there is nothing a ROLLBACK could undo. The saga runs a COMPENSATING transaction: a new forward transaction that reverses the booking.* ```transcript Saga> BEGIN; BEGIN Saga> UPDATE flights SET seats = seats + 1 WHERE id = 1 RETURNING seats; seats ------- 5 (1 row) Saga> COMMIT; COMMIT ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/06-distributed/saga-compensation.yaml) ## postgres/06-distributed/transactional-outbox.yaml - engine: postgres (PostgreSQL 18.6) - claim: The order and outbox row commit or roll back together in the shown transactions. A relay's rolled-back delete leaves the row selectable again; a committed delete empties the outbox. Publication is not executed. *The order and its event are written in ONE transaction — both land in the same database.* ```transcript App> BEGIN; BEGIN App> INSERT INTO orders VALUES (1, 'alice', 90); INSERT 0 1 App> INSERT INTO outbox (event) VALUES ('order_placed: order 1'); INSERT 0 1 App> COMMIT; COMMIT ``` *Atomicity covers the failure path too: no committed order, no event.* ```transcript App> BEGIN; BEGIN App> INSERT INTO orders VALUES (2, 'bob', 75); INSERT 0 1 App> INSERT INTO outbox (event) VALUES ('order_placed: order 2'); INSERT 0 1 App> ROLLBACK; ROLLBACK App> SELECT id, event FROM outbox ORDER BY id; id | event ----+----------------------- 1 | order_placed: order 1 (1 row) App> SELECT id, customer, amount FROM orders ORDER BY id; id | customer | amount ----+----------+-------- 1 | alice | 90 (1 row) ``` *A relay claims the event exactly like a chapter-5 job-queue worker…* ```transcript Relay> BEGIN; BEGIN Relay> SELECT id, event FROM outbox ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | event ----+----------------------- 1 | order_placed: order 1 (1 row) ``` *A real relay would publish outside this transaction. Here publication is narration only; the DELETE is executed and explicitly rolled back.* ```transcript Relay> DELETE FROM outbox WHERE id = 1; DELETE 1 Relay> ROLLBACK; ROLLBACK ``` *ROLLBACK restored the deleted row. The relay selects it again and commits its deletion. No receiver effect or delivery count is recorded here.* ```transcript Relay> BEGIN; BEGIN Relay> SELECT id, event FROM outbox ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | event ----+----------------------- 1 | order_placed: order 1 (1 row) Relay> DELETE FROM outbox WHERE id = 1; DELETE 1 Relay> COMMIT; COMMIT Relay> SELECT count(*)::int AS pending FROM outbox; pending --------- 0 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/06-distributed/transactional-outbox.yaml) ## postgres/06-distributed/two-phase-commit.yaml - engine: postgres (PostgreSQL 18.6) - claim: With prepared transactions enabled, one prepared update survives backend termination and retains its row lock. VACUUM leaves four occupied ledger tuple slots until a superuser commits the prepared transaction; then it leaves one. No server restart or global coordinator is tested. *A is one participant in a distributed transfer. It does its work, then PREPARES — phase one.* ```transcript A> BEGIN; BEGIN A> UPDATE accounts SET balance = 200 WHERE id = 1; UPDATE 1 A> PREPARE TRANSACTION 'transfer-42'; PREPARE TRANSACTION ``` *PREPARE detached the transaction from the session: A itself no longer sees its own change.* ```transcript A> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) M> SELECT gid, owner, database FROM pg_prepared_xacts; gid | owner | database -------------+----------+---------- transfer-42 | postgres | postgres (1 row) ``` *The prepared transaction still holds its row locks — with no session attached.* ```transcript B> SELECT balance FROM accounts WHERE id = 1 FOR UPDATE NOWAIT; -- lock_not_available ERROR: 55P03: could not obtain lock on row in relation "accounts" ``` *M terminates A's backend. No global coordinator or server process is killed.* ```transcript M> SELECT pg_terminate_backend(pid) AS terminated FROM pg_stat_activity WHERE application_name = 'A'; terminated ------------ t (1 row) A> SELECT 1; ERROR: ERR_POSTGRES_CONNECTION_CLOSED: Connection closed ``` *The originating backend is gone. The prepared entry remains, and B's next NOWAIT request still fails. Server-restart durability is a manual contract, not an executed test here.* ```transcript M> SELECT gid FROM pg_prepared_xacts; gid ------------- transfer-42 (1 row) B> SELECT balance FROM accounts WHERE id = 1 FOR UPDATE NOWAIT; ERROR: 55P03: could not obtain lock on row in relation "accounts" ``` *The prepared transaction retains an old xid horizon. Check occupied tuple slots around VACUUM in ledger, an unrelated table updated after prepare. This does not imply all VACUUM work or every table's reclamation stops.* ```transcript B> UPDATE ledger SET n = 1 WHERE id = 1; UPDATE 1 B> UPDATE ledger SET n = 2 WHERE id = 1; UPDATE 1 B> UPDATE ledger SET n = 3 WHERE id = 1; UPDATE 1 ``` *Four versions of one row on the page — three of them dead.* ```transcript B> SELECT count(*)::int AS versions_on_page FROM heap_page_items(get_raw_page('ledger', 0)) WHERE lp_flags = 1; versions_on_page ------------------ 4 (1 row) B> VACUUM ledger; VACUUM ``` *The next count checks that these four occupied tuple slots remain after VACUUM, not that all maintenance was a no-op.* ```transcript B> SELECT count(*)::int AS versions_on_page FROM heap_page_items(get_raw_page('ledger', 0)) WHERE lp_flags = 1; versions_on_page ------------------ 4 (1 row) ``` *Phase two runs outside a transaction block. B, a superuser in the same database, commits the prepared transaction by name.* ```transcript B> COMMIT PREPARED 'transfer-42'; COMMIT PREPARED B> SELECT balance FROM accounts WHERE id = 1; balance --------- 200 (1 row) ``` *And the horizon moves. The same VACUUM, a moment later, finally collects the three dead versions.* ```transcript B> VACUUM ledger; VACUUM B> SELECT count(*)::int AS versions_on_page FROM heap_page_items(get_raw_page('ledger', 0)) WHERE lp_flags = 1; versions_on_page ------------------ 1 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/06-distributed/two-phase-commit.yaml) ## postgres/07-pitfalls/queue-bloat.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this READ COMMITTED schedule on an 8 KiB-page heap, A holds a row lock and an assigned transaction ID while B completes 1001 jobs. The heap grows from 9 to 17 pages with 1200 rows; VACUUM leaves 2201 occupied line pointers while A is open. After A commits, another VACUUM reduces that count to 1200, without reducing the 17-page file. ```timeline A: A claims job 1, then hangs B: 9 pages B: B claims job 2 (skips A's job 1) B: job 2 completion update B: COMMIT B: drain 250 B: 9 → 11 pages B: drain 750 B: 11 → 17 pages B: 2201 occupied tuple slots B: VACUUM, while A still hangs B: still 2201 occupied tuple slots A: A finally commits, the hang ends B: same VACUUM, a moment later B: 2201 → 1200, reclaimed B: heap file still 17 pages ``` *A is a worker that claims a job and then hangs: the connection stays open and the transaction never commits. This is the queue's own flavor of "idle in transaction."* ```transcript A> BEGIN; BEGIN A> SELECT id, task FROM jobs WHERE state = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; id | task ----+-------------------- 1 | send welcome email (1 row) B> SELECT backend_xid IS NOT NULL AS has_xid FROM pg_stat_activity WHERE application_name = 'A' -- A retains an assigned xid; READ COMMITTED does not establish a transaction-wide RR snapshot has_xid --------- t (1 row) ``` *The queue is 1200 rows in 9 pages, and it keeps humming while A sits there. B is a worker using the chapter 5 selection predicate and completion update. B skips A's locked job 1 and claims job 2.* ```transcript B> SELECT (pg_relation_size('jobs') / 8192)::int AS pages; pages ------- 9 (1 row) B> BEGIN; BEGIN B> SELECT id, task FROM jobs WHERE state = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; -- job 1 is claimed by A, skipped without waiting id | task ----+-------------------- 2 | send welcome email (1 row) B> UPDATE jobs SET state = 'done' WHERE id = 2; UPDATE 1 B> COMMIT; COMMIT ``` *B runs the same selection and completion body a thousand more times. drain(n) commits each cycle, so CALL runs outside a transaction block. Task names are data: no email is sent in this Scenario.* ```transcript B> CALL drain(250); -- 250 more claim/complete cycles CALL B> SELECT (pg_relation_size('jobs') / 8192)::int AS pages; pages ------- 11 (1 row) B> CALL drain(750); -- 750 more CALL B> SELECT (pg_relation_size('jobs') / 8192)::int AS pages; pages ------- 17 (1 row) B> SELECT count(*)::int AS jobs, count(*) FILTER (WHERE state = 'done')::int AS done, count(*) FILTER (WHERE state = 'queued')::int AS queued FROM jobs; jobs | done | queued ------+------+-------- 1200 | 1001 | 199 (1 row) ``` *There are 1200 current rows and 1001 additional occupied tuple slots. † The horizon explanation is an inference from PostgreSQL 18's old-transaction vacuum guidance, linked in the lesson. READ COMMITTED does not give A a transaction-wide RR snapshot or access to every old version.* ```transcript B> SELECT count(*)::int AS occupied FROM generate_series(0, (pg_relation_size('jobs') / 8192)::int - 1) AS p, heap_page_items(get_raw_page('jobs', p::int)) WHERE lp_flags = 1; occupied ---------- 2201 (1 row) B> VACUUM jobs; VACUUM ``` *VACUUM completed, but the occupied line-pointer count did not fall. This measurement does not prove that VACUUM did no other maintenance.* ```transcript B> SELECT count(*)::int AS occupied FROM generate_series(0, (pg_relation_size('jobs') / 8192)::int - 1) AS p, heap_page_items(get_raw_page('jobs', p::int)) WHERE lp_flags = 1; occupied ---------- 2201 (1 row) A> COMMIT; COMMIT ``` *After A commits, a second VACUUM reduces occupied tuple slots to 1200. Commit alone does not perform that cleanup.* ```transcript B> VACUUM jobs; VACUUM B> SELECT count(*)::int AS occupied FROM generate_series(0, (pg_relation_size('jobs') / 8192)::int - 1) AS p, heap_page_items(get_raw_page('jobs', p::int)) WHERE lp_flags = 1; occupied ---------- 1200 (1 row) ``` *The heap file stays at 17 pages in this run. Ordinary VACUUM can truncate entirely empty trailing pages under suitable locking conditions, but does not compact live rows. VACUUM FULL and other table rewrites are separate operations, not executed here. File size alone does not measure reusable space.* ```transcript B> SELECT (pg_relation_size('jobs') / 8192)::int AS pages; pages ------- 17 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/07-pitfalls/queue-bloat.yaml) ## postgres/08-production/deadlock-counter.yaml - engine: postgres (PostgreSQL 18.6) - claim: This two-row deadlock emits 40P01 and increments pg_stat_database.deadlocks by one after a statistics flush. By the PostgreSQL 18 statistics contract, resets and unclean server restarts can clear this cumulative counter; neither is executed here. ```timeline A: holds row 1 B: holds row 2 A: wants row 2 (B holds it) → ⏳ waits B: wants row 1 (A holds it) ← 40P01 deadlock detected A: ⏵ wants row 2 (B holds it) → completes ``` ```transcript A> SET deadlock_timeout = '10s'; -- Pin the victim, as in the chapter-3 deadlock lesson, so the transcript is reproducible. SET B> SET deadlock_timeout = '50ms'; SET ``` *The classic: A and B lock the same two rows in opposite order.* ```transcript A> BEGIN; BEGIN A> UPDATE accounts SET balance = balance - 10 WHERE id = 1; UPDATE 1 B> BEGIN; BEGIN B> UPDATE accounts SET balance = balance - 25 WHERE id = 2; UPDATE 1 A> UPDATE accounts SET balance = balance + 10 WHERE id = 2; ⏳ A is waiting for a lock… B> UPDATE accounts SET balance = balance + 25 WHERE id = 1; -- deadlock_detected ERROR: 40P01: deadlock detected ⏵ A resumes: UPDATE 1 A> COMMIT; COMMIT B> ROLLBACK; ROLLBACK ``` *No retry is executed here. After B rolls back, flush its statistics and read the counter delta:* ```transcript B> SELECT pg_stat_force_next_flush(); pg_stat_force_next_flush -------------------------- (1 row) M> SELECT (d.deadlocks - s.deadlocks)::int AS new_deadlocks FROM pg_stat_database d, stats_before s WHERE d.datname = current_database(); new_deadlocks --------------- 1 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/08-production/deadlock-counter.yaml) ## postgres/08-production/find-long-transactions.yaml - engine: postgres (PostgreSQL 18.6) - claim: Three pg_stat_activity queries identify A's idle READ ONLY REPEATABLE READ transaction, its age over one second, and a retained backend_xmin with no assigned backend_xid. These fields are diagnostics, not a cleanup measurement. *A starts a READ ONLY report at REPEATABLE READ and pauses before committing.* ```transcript A> BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY; BEGIN A> SELECT count(*)::int AS orders FROM orders; orders -------- 2 (1 row) ``` *Detector 1 — the oldest open transaction, and how long it's been open:* ```transcript M> SELECT application_name, state, now() - xact_start > interval '1 second' AS older_than_1s FROM pg_stat_activity WHERE xact_start IS NOT NULL AND pid <> pg_backend_pid() ORDER BY xact_start LIMIT 1; application_name | state | older_than_1s ------------------+---------------------+--------------- A | idle in transaction | t (1 row) ``` *Detector 2 — sessions holding a transaction open while doing nothing:* ```transcript M> SELECT application_name FROM pg_stat_activity WHERE state = 'idle in transaction' AND now() - state_change > interval '1 second' ORDER BY application_name; application_name ------------------ A (1 row) ``` *Detector 3: A retains a snapshot horizon (backend_xmin), without an assigned top-level xid. An xid is not a count of writes; this query does not execute VACUUM or measure storage reclamation.* ```transcript M> SELECT application_name, backend_xid IS NOT NULL AS has_xid, backend_xmin IS NOT NULL AS retains_snapshot FROM pg_stat_activity WHERE backend_xmin IS NOT NULL AND pid <> pg_backend_pid() ORDER BY application_name; application_name | has_xid | retains_snapshot ------------------+---------+------------------ A | f | t (1 row) A> COMMIT; COMMIT ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/08-production/find-long-transactions.yaml) ## postgres/08-production/timeout-guardrails.yaml - engine: postgres (PostgreSQL 18.6) - claim: statement_timeout emits 57014 and preserves the session. In an explicit transaction, the next query emits 25P02 until ROLLBACK. A 500ms transaction_timeout terminates A while idle and its balance update rolls back. *statement_timeout: the per-statement seatbelt.* ```transcript A> SET statement_timeout = '100ms'; SET A> SELECT pg_sleep(2); -- query_canceled ERROR: 57014: canceling statement due to statement timeout ``` *The canceled standalone statement's implicit transaction ended; the session remains usable.* ```transcript A> SELECT 'still here' AS session; session ------------ still here (1 row) ``` *In an explicit transaction, statement cancellation leaves the transaction failed.* ```transcript A> BEGIN; BEGIN A> UPDATE accounts SET balance = 999 WHERE id = 1; UPDATE 1 A> SELECT pg_sleep(2); ERROR: 57014: canceling statement due to statement timeout A> SELECT balance FROM accounts WHERE id = 1; ERROR: 25P02: current transaction is aborted, commands ignored until end of transaction block A> ROLLBACK; ROLLBACK M> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) ``` *transaction_timeout (PostgreSQL 17+) terminates the session when its transaction exceeds the limit. This run exercises the idle case; prepared transactions are exempt by the manual contract.* ```transcript A> RESET statement_timeout; RESET A> SET transaction_timeout = '500ms'; SET A> BEGIN; BEGIN A> UPDATE accounts SET balance = 999 WHERE id = 1; UPDATE 1 ``` *After the transaction timeout interval, A's backend is absent:* ```transcript M> SELECT count(*)::int AS backends FROM pg_stat_activity WHERE application_name = 'A'; backends ---------- 0 (1 row) A> COMMIT; -- psycopg can receive 25P04; Bun reports the closed connection ERROR: ERR_POSTGRES_CONNECTION_CLOSED: Connection closed ``` *The update from the terminated transaction is absent:* ```transcript M> SELECT balance FROM accounts WHERE id = 1; balance --------- 100 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/08-production/timeout-guardrails.yaml) ## postgres/08-production/vacuum-health.yaml - engine: postgres (PostgreSQL 18.6) - claim: After five inserts and three updates, pg_stat_user_tables reports estimated live/dead counts 5/3; after manual VACUUM it reports 5/0 and a last_vacuum timestamp. The database xid age is below the configured freeze-launch threshold, not a demonstrated wraparound safety guarantee. ```transcript A> INSERT INTO inventory SELECT g, 10 FROM generate_series(1, 5) g; INSERT 0 5 A> UPDATE inventory SET qty = qty + 1 WHERE id <= 3; UPDATE 3 A> SELECT pg_stat_force_next_flush(); -- stats reach the views lazily; force it for the demo pg_stat_force_next_flush -------------------------- (1 row) ``` *These are statistics estimates, not an exact heap scan. The small run reports five live and three dead rows:* ```transcript M> SELECT relname, n_live_tup::int, n_dead_tup::int, last_vacuum IS NULL AS no_vacuum_timestamp FROM pg_stat_user_tables WHERE relname = 'inventory'; relname | n_live_tup | n_dead_tup | no_vacuum_timestamp -----------+------------+------------+--------------------- inventory | 5 | 3 | t (1 row) ``` *After manual VACUUM, the estimate is zero dead rows and last_vacuum is present:* ```transcript A> VACUUM inventory; VACUUM M> SELECT relname, n_live_tup::int, n_dead_tup::int, last_vacuum IS NOT NULL AS has_vacuum_timestamp FROM pg_stat_user_tables WHERE relname = 'inventory'; relname | n_live_tup | n_dead_tup | has_vacuum_timestamp -----------+------------+------------+---------------------- inventory | 5 | 0 | t (1 row) ``` *Compare database xid age with the configured autovacuum freeze-launch threshold. Below it is not proof that freezing will finish in time:* ```transcript M> SELECT age(datfrozenxid) < current_setting('autovacuum_freeze_max_age')::int AS below_freeze_threshold FROM pg_database WHERE datname = current_database(); below_freeze_threshold ------------------------ t (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/08-production/vacuum-health.yaml) ## postgres/08-production/who-is-blocking-whom.yaml - engine: postgres (PostgreSQL 18.6) - claim: In this one-waiter schedule, pg_stat_activity and pg_blocking_pids() identify idle blocker A and waiting B. After M signals A's termination, B's update resumes; A's uncommitted 200 is absent and B commits 300. ```timeline A: UPDATE, then goes to lunch (idle in txn) B: UPDATE balance = 300 → ⏳ waits M: who blocks whom? → B waits on idle A M: pg_terminate_backend(A) B: ⏵ UPDATE balance = 300 → completes ``` *A updates a row and then… goes to lunch. The transaction stays open.* ```transcript A> BEGIN; BEGIN A> UPDATE accounts SET balance = 200 WHERE id = 1; UPDATE 1 B> BEGIN; BEGIN B> UPDATE accounts SET balance = 300 WHERE id = 1; ⏳ B is waiting for a lock… ``` *Someone pages you: 'updates are hanging'. This is the query you paste:* ```transcript M> SELECT waiter.application_name AS waiter, waiter.query AS waiting_query, blocker.application_name AS blocker, blocker.state AS blocker_state, blocker.query AS blocker_last_query FROM pg_stat_activity waiter JOIN pg_stat_activity blocker ON blocker.pid = ANY (pg_blocking_pids(waiter.pid)) WHERE waiter.wait_event_type = 'Lock' ORDER BY waiter.application_name, blocker.application_name; waiter | waiting_query | blocker | blocker_state | blocker_last_query --------+------------------------------------------------+---------+---------------------+------------------------------------------------ B | UPDATE accounts SET balance = 300 WHERE id = 1 | A | idle in transaction | UPDATE accounts SET balance = 200 WHERE id = 1 (1 row) ``` *M has permission to signal A. A true return means the signal was sent, not that termination has finished:* ```transcript M> SELECT pg_terminate_backend(pid) AS terminated FROM pg_stat_activity WHERE application_name = 'A'; terminated ------------ t (1 row) ``` *A's transaction dies and rolls back; B gets the lock and finishes at last.* ```transcript ⏵ B resumes: UPDATE 1 M> SELECT balance FROM accounts WHERE id = 1; -- A's uncommitted 200 is absent; B's 300 is not yet committed balance --------- 100 (1 row) B> SELECT balance FROM accounts WHERE id = 1; -- B sees its own uncommitted update balance --------- 300 (1 row) B> COMMIT; COMMIT M> SELECT balance FROM accounts WHERE id = 1; balance --------- 300 (1 row) ``` Verified against PostgreSQL 18.6 · [Run it yourself](/about/run-locally) · [Scenario source](https://github.com/svyatov/database-transactions/blob/main/scenarios/postgres/08-production/who-is-blocking-whom.yaml)