A transaction is all or nothing against failures, but against other transactions it protects you only as far as its isolation level: each level still lets through a known set of bad interleavings, and you close the rest by folding the check into the write, by locking what you read, or by running serializable and retrying.
Fig. 1: one balance, two requests: the interleaving that loses an update, and the three ways out
SET balance = balance - 5, B's update waits on A's row lock (the gold bar) until A commits, then subtracts from 20. Final 15: B waited briefly.SELECT ... FOR UPDATE, B's read waits for A's whole transaction, then returns 20, and B writes 15.Every lane is a real run on PostgreSQL (sections 1, 3 and 5): the first three on 16.2, the retry on 16.15 (section 5's trace). Blue is a read, orange a write, green a commit, a red box a wait for a lock or an error. Correct ends at 15; the collision ends at 25.
You need: SQL, rows and the write-ahead log at the level of the root Topic: databases (Reading sections 3 and 4, where Ben's last credit is spent from two tabs). Results marked measured were recorded for this page on a laptop (an Apple M1 Pro) with two or three live sessions; scripts are in src/measure/.
UPDATE credits SET balance = balance - 10 WHERE user_id = 7 AND balance >= 10, then read how many rows changed.BEGIN ... COMMIT or ROLLBACK: statements treated as one unit.| The problem | What prevents it | What that costs | Section |
|---|---|---|---|
| Half a change survives a crash or an error (credits taken, reply never saved) | A transaction: BEGIN ... COMMIT, all or nothing | Your code must roll back after any error | 1, 2 |
| A committed change vanishes in a power cut | Durability: the log is flushed to disk before COMMIT returns | One disk flush per commit: 6.842 ms per commit on this laptop with the drive cache flushed | 2 |
| Two requests read the same balance and both write (the lost update) | One UPDATE ... SET balance = balance - 10, or SELECT ... FOR UPDATE, or repeatable read / serializable with a retry | Waiting on a lock, or a retry | 3, 6, 9 |
| Two requests each check a rule and write different rows (write skew: the rota, the quota) | Serializable with a retry, or locking a row both must touch | Retries under contention; locks to design | 3, 4 |
| A report sees half of a transfer (read skew) | Repeatable read: one snapshot for the whole transaction | Old row versions kept around | 3, 5 |
| Two transactions wait for each other forever | Deadlock detection kills one; take locks in one order | A retry; a design rule | 7 |
| A transaction left open for an hour | Timeouts: idle_in_transaction_session_timeout, transaction_timeout, lock_timeout | Some work is cancelled | 10 |
Ines (user 7, the same user as in the root's SQL playground) has 30 prepaid credits and the chat open in two tabs. Tab A asks for a long answer costing 10 credits; a second later tab B asks for a short one costing 5. The server's "charge a message" code is reasonable on its own:
balance = db.execute("SELECT balance FROM credits WHERE user_id = 7") # 30
if balance >= cost:
reply = call_model(prompt) # seconds
db.execute("INSERT INTO messages ...")
db.execute("UPDATE credits SET balance = %s WHERE user_id = 7", (balance - cost,))
Run twice at once, both copies read 30 before either writes: A writes 30 - 10 = 20, B writes 30 - 5 = 25, and the last write wins. Ines paid 5 credits for 15 credits of answers; nothing failed and nothing was logged. This is the lost update (the hero's first panel), reproduced on a real Postgres and a real MySQL: final balance 25 instead of 15 measured. Each anomaly on this page is one unlucky interleaving of two sessions.
A transaction groups statements into one unit: BEGIN opens it, COMMIT makes all its changes permanent and visible to others at the same instant, ROLLBACK throws them away. Outside BEGIN, each statement is its own transaction (autocommit). It makes two separate promises, and beginners expect only the first:
BEGIN and COMMIT at Postgres's default level still loses the update: atomicity is not isolation.When a statement fails inside a transaction (a constraint refuses it, a deadlock is detected), Postgres marks the whole transaction failed: every later statement gets ERROR 25P02: current transaction is aborted, commands ignored until end of transaction block, and COMMIT is answered with ROLLBACK (Postgres 16 error codes; the Isolation lab shows a failed transaction's COMMIT answered with ROLLBACK). SQLite undoes only the failed statement and lets you commit the rest, which is how the root's SQL playground lesson 10 ends up with a +50 credit and no debit (Topic: databases, SQL playground tab). The rule that works everywhere: on any error, roll back and decide whether to retry the whole transaction.
With psycopg 3 (the current Postgres driver for Python), with conn.transaction(): issues BEGIN, then COMMIT, or ROLLBACK if an exception escapes. One trap: by default "even a simple SELECT will start a transaction", which stays open until you commit, holding back clean-up (psycopg 3 docs, transactions; section 10 measures the cost).
The four guarantees are known as ACID, a name from Haerder and Reuter's 1983 survey (ACM Computing Surveys). A and D are solved problems with a price tag, C is mostly your job, and I is the rest of this page.
A, atomicity, is cheap to undo in Postgres. Postgres never overwrites a row in place: an UPDATE writes a new version stamped with the writer's transaction number and leaves the old one (section 5 shows them). Whether a version counts depends only on whether its transaction committed, recorded in a small commit log (pg_xact). So ROLLBACK just marks the transaction aborted; its versions become invisible at once, and the price is dead versions that VACUUM must clean up later (sections 5 and 10). MySQL's InnoDB updates in place and keeps old values in an undo log, so rolling back a huge transaction takes about as long as making it (section 5 compares the two designs).
C, consistency, is mostly yours. The database guarantees the rules you declared: NOT NULL, UNIQUE, foreign keys, CHECK (balance >= 0) hold after every commit, whichever code path wrote the row. Rules you did not declare ("at least one engineer on call", "at most 3 messages a day") are only as safe as your code and your isolation level: section 3 breaks both with every statement succeeding. Declare every rule you can.
A constraint can be checked at commit instead of after each statement with DEFERRABLE INITIALLY DEFERRED (unique, primary key, foreign key and exclusion constraints; not CHECK or NOT NULL), which lets two rows briefly swap values inside one transaction (Postgres 16, CREATE TABLE).
D, durability, is the price of one disk flush. Postgres writes every change to its write-ahead log (WAL: an append-only file of changes, written before the data pages) and at COMMIT waits until the operating system confirms the log reached the disk. That wait is a flush (the fsync family of system calls), and for small transactions it is the whole cost of durability. One client committing one small INSERT per transaction, 5 seconds per setting measured:
The Mac's default flush (open_datasync) is fast because macOS's ordinary flush does not force the drive to empty its own volatile cache; Postgres's documentation says "on macOS, write caching can be prevented by setting wal_sync_method to fsync_writethrough" (Postgres 16, reliability and the WAL). With it the true cost appears: tens of times slower. synchronous_commit = off returns before the flush, so it buys about 1.5 times more commits with the Mac's default flush and about 86 times with the drive cache really flushed. Many concurrent commits share one flush (group commit), so many clients do far better than one client's figure suggests.
The default is fdatasync and honesty depends on the drive; datacentre SSDs with power-loss protection make honest flushes cheap.
synchronous_commit = off "buys enormous throughput". Measured here, that holds only when an honest flush is slow (about 86 times with the drive cache flushed); with a fast or cached flush the gain was about 1.5 times (one client in both cases).fsync off on a database you cannot rebuild: "this can result in unrecoverable data corruption in the event of a power failure or system crash" (Postgres 16, WAL settings). If commits are too slow, batch more work per transaction and rely on group commit.synchronous_commit = off is safe in a different way: a crash can lose the last moments of commits (at most three times wal_writer_delay, 200 ms by default, so about 0.6 s), but "the database state will be just the same as if those transactions had been aborted cleanly" (same page). Set it per transaction for writes you could afford to lose (a typing indicator, an analytics event) with SET LOCAL synchronous_commit = off; keep it on for credits and messages.synchronous_commit = remote_apply) is a replication question: Running Postgres in production and Distributed systems fundamentals.Commits per second: 7,983 with the default flush, 12,312 with synchronous_commit off; 146 with fsync_writethrough, 12,633 with it off. Measured 2026-10-04, PostgreSQL 16.2, Apple M1 Pro internal SSD, macOS; one client sending one INSERT per transaction over TCP loopback. A durable commit with the drive cache flushed took 6.842 ms, 55 times the default's 0.125 ms. Script: src/measure/extras.py.
An anomaly is an outcome that could not have happened if the transactions had run one after the other, in some order. Each card is a real recording: one column per session, one row per step; the highlighted cell is the statement issued, its result in grey under it, and a dashed red border means it is waiting for a lock. The chips under each recording are every isolation level on both databases: red, the anomaly happened; green, prevented (hover for how). Click a chip to see that run; the Isolation lab steps through any of them one statement at a time.
Two (or three) live sessions on a real database, driven step by step by a script that hands each session one statement, waits up to half a second, and if the statement has not finished records it as blocked (and asks Postgres what it is waiting for) before moving on. A statement that finishes later, because the other session committed or a deadlock was found, is shown in the step during which it finished. The scripts are in src/measure/.
Session B reads a change that session A has made but not committed, and A then rolls back. B has acted on data that never existed. Here tab A debits all 30 of Ines's credits for a long reply, the model call fails, and A rolls back; meanwhile a billing check in B reads the balance.
Postgres never shows uncommitted data, at any level: it runs READ UNCOMMITTED as read committed, "the only sensible way to map the standard isolation levels to PostgreSQL's multiversion concurrency control architecture" (Postgres 16, transaction isolation). MySQL means it: at READ UNCOMMITTED, B read 0 measured.
B reads a row, A changes it and commits, B reads the row again in the same transaction and gets a different value. An invoice job that reads Ines's balance for the header and again for the footer prints two numbers.
At read committed every statement sees everything committed before it started, so the second read sees A's commit. At repeatable read the whole transaction reads one snapshot taken at its first statement.
The same as a non-repeatable read, but for a condition instead of a row: B counts Ines's messages today, A inserts one and commits, B counts again and gets one more. The new row is the phantom. The SQL standard allows phantoms at repeatable read; Postgres's repeatable read prevents them because a snapshot hides new rows too (the documentation's table says "allowed, but not in PG"); MySQL's plain reads at repeatable read also use a snapshot, so they did not see it either measured.
Section 1's bug. A and B both read 30; A writes 20 and commits; B writes 25 over it. Berenson and colleagues named it P4 in "A Critique of ANSI SQL Isolation Levels" (Berenson et al., 1995), the paper that showed the SQL standard's definitions miss it.
This is the first place the two databases disagree. At repeatable read, Postgres refused B's write: "could not serialize access due to concurrent update" (SQLSTATE 40001), because B tried to change a row that a transaction committed after B's snapshot had already changed. MySQL at repeatable read let B's write through and lost A's 10 credits measured: InnoDB's UPDATE always works on the latest committed row, not on the snapshot, and does not check that the row changed since the transaction's snapshot (its manual: the snapshot "applies to SELECT statements within a transaction, not necessarily to DML statements", MySQL 8.4, consistent reads). Two fixes work everywhere and are the chips marked fix: one atomic UPDATE ... SET balance = balance - 10, or SELECT ... FOR UPDATE before computing.
A moves 10 credits from Ines (user 7) to Quinn (user 12), the transfer from the root's SQL playground lesson 10; the total is always 50. B, an audit job, reads Ines's balance before the transfer and Quinn's after it, and adds them up to 60. Every row B read was committed; the mix is from two moments. Backups, exports and reports that run for minutes at read committed are exposed to exactly this.
The chat product's incident rota needs at least one engineer on call. Ana and Raj are both on call and both feel ill. Each runs "if someone else is on call, take me off". This is the on-call doctors example from Kleppmann's Designing Data-Intensive Applications; Berenson et al. named the pattern A5B.
Fig. 2: write skew on the rota, three recorded runs
SELECT count(*) FROM oncall WHERE on_call: both snapshots honestly show 2.COMMIT with SQLSTATE 40001. Raj stays on call.SELECT engineer FROM oncall WHERE on_call FOR UPDATE, A locks both rows; B's same read waits until A commits, then returns only raj, so Raj stays on call.Postgres's error for B was "could not serialize access due to read/write dependencies among transactions" (SQLSTATE 40001); with FOR UPDATE the second engineer waits, then sees 1 measured. The chips below the recording are every level on both databases.
Ines may send 3 messages a day and has sent 2. Two tabs each count today's messages, see 2, and insert one: 4 messages. The same shape as the rota, with one twist that defeats the usual fix: there is no row to lock. FOR UPDATE on the count would lock the two existing messages, while the conflict is over a third row that neither transaction can see yet.
Three fixes, best first. Materialise the conflict (Kleppmann's term): keep a daily_usage(user_id, day, n) row and make the check and the increment one statement, UPDATE daily_usage SET n = n + 1 WHERE user_id = 7 AND day = ... AND n < 3; zero rows changed means over quota, and two tabs now collide on one row, which read committed handles (section 1's atomic update). Lock a row both must touch: SELECT ... FROM users WHERE id = 7 FOR UPDATE first (the chip marked fix). Use serializable and retry, which caught it on Postgres measured. MySQL's gap locks, its answer to phantoms, protect only locking reads; the plain SELECT count(*) took none, so MySQL's repeatable read let the fourth message through too.
The subtlest one, found by Fekete, O'Neil and O'Neil in 2004 ("A Read-Only Transaction Anomaly Under Snapshot Isolation") and used on the PostgreSQL wiki as the "deposit report" (PostgreSQL wiki, SSI). Credit purchases are filed under the open billing batch. A, a purchase, reads "batch 1 is open". B closes batch 1 and commits. C, a report, sees batch 1 closed and totals it: 100. A then files its purchase in batch 1 and commits: batch 1 now totals 150, after a report on the closed batch said 100. Remove the report and the history is fine; the read-only transaction is what makes it impossible.
A serialization anomaly is the general name for any result that no one-at-a-time order could produce; write skew is the common case. Only serializable prevents all of them: Postgres aborted the purchase A (SQLSTATE 40001), so its retry files under batch 2 measured.
The SQL standard (1992) defines four levels by which of three phenomena they forbid: dirty reads, non-repeatable reads and phantoms. Those definitions miss lost update, read skew and write skew, so a level's name tells you little; what matters is which anomalies a given database lets through at it. Every scenario of section 3 at every level, on both databases measured; click any cell to open that run in the Isolation lab:
Recorded 2026-10-04 on PostgreSQL 16.2 (pgserver wheel, deadlock_timeout 1s) and MySQL 9.7.2 (InnoDB, conda-forge build; innodb_lock_wait_timeout 50 s), each run from freshly created tables. "Not seen" means the transaction read a snapshot that hid the other change; "waited for a lock" means a lock made the second transaction wait until the first finished. Scripts: src/measure/run_matrix.py and scenarios.py.
SELECT becomes SELECT ... FOR SHARE when autocommit is off (MySQL 8.4, isolation levels), so conflicting transactions wait for each other, and the lost update and both write skews ended in a deadlock (error 1213) that killed one transaction.Three years after the standard, Berenson, Bernstein, Gray and colleagues showed that its definitions are ambiguous and miss whole classes of anomaly, including lost update, read skew and write skew, and that the popular snapshot isolation fits none of the four levels (Berenson et al., 1995). Adya's 1999 thesis restated every level as which cycles of dependencies between transactions are allowed (Adya, MIT, 1999), and that is how testers such as Kleppmann's Hermitage suite (2014, github.com/ept/hermitage) and Jepsen describe databases today.
On MySQL, Jepsen's analysis of 8.0.34 (2023-12-19) found lost updates, read skew and non-repeatable reads at repeatable read and concluded "it isn't clear what MySQL Repeatable Read actually is" (Jepsen, MySQL 8.0.34). Our read skew run was prevented because B only read; Hermitage records MySQL's repeatable read as preventing read skew in read-only transactions only.
These results agree with Hermitage's published table for both databases. Other databases, from the same table: Oracle's default is read committed and its "serializable" is snapshot isolation, so it allows write skew; SQL Server defaults to a locking read committed; CockroachDB and FoundationDB default to serializable (Hermitage; CockroachDB docs).
Since PostgreSQL 9.1 (2011), serializable is serializable snapshot isolation (SSI). Transactions still read snapshots and never wait for readers; in addition, Postgres records what each one read (in "SIREAD" locks, which block nobody) and watches for read-write dependencies: T1 read something T2 then wrote, so T1 must come first in any serial order. One such edge is harmless; two in a row, into and out of one transaction, is the "dangerous structure" every serialization anomaly under snapshot isolation contains (Cahill, Röhm and Fekete, SIGMOD 2008), and Postgres aborts a transaction in it.
Postgres can abort when no real anomaly would have followed (a false positive). Ports and Grittner, who built it, report that it performs "only slightly below that of snapshot isolation" and "significantly outperforms" classic two-phase locking on read-heavy workloads (Ports and Grittner, VLDB 2012).
The error messages in the recordings say which case fired: "could not serialize access due to concurrent update" is the simple first-updater-wins rule (you tried to change a row changed since your snapshot); "due to read/write dependencies among transactions", with "Reason code: Canceled on identification as a pivot", is SSI's dangerous structure. Reads are tracked by row, by page or by whole table, coarser when memory runs short, and "a sequential scan will always necessitate a relation-level predicate lock", so a missing index raises the failure rate (Postgres 16, transaction isolation).
Guarantees are only as good as the code: Jepsen's 2020 analysis found a bug that let a write skew through Postgres's serializable in 9.5 to 13 under normal operation, with a fix scheduled for the 13 August 2020 minor releases (same Jepsen report).
An arrow X to Y means "X must come before Y". C (the report) did not see A's purchase, so C before A; A read "batch 1 open" before B closed it, so A before B; C saw B's close, so B before C. The three arrows form a cycle: no serial order exists. Postgres's recorded error for A was "Canceled on identification as a pivot". Write skew (the rota) is the two-transaction case: each read the row the other wrote, an edge each way.
UPDATE ... WHERE, constraints, FOR UPDATE where needed).pg_dump takes one snapshot for this reason).READ ONLY (they then cause fewer aborts), keep the retry loop in one place, and keep the transactions short. It does not protect against transactions running at lower levels: every transaction that touches the rule must be serializable.The simplest isolation locks everything a transaction reads or writes until it commits (two-phase locking), so a long report blocks every writer it touches. Postgres, MySQL's InnoDB, Oracle and most modern databases instead keep several versions of a row, so a reader sees an older version while a writer prepares a newer one: multi-version concurrency control (MVCC). In the Postgres documentation's words, "reading never blocks writing and writing never blocks reading" (Postgres 16, MVCC introduction).
Every transaction that writes gets a transaction id (xid) from a counter. Every row version (a tuple) carries two hidden fields: xmin, the xid that created it, and xmax, the xid that deleted or replaced it (0 if none). An UPDATE sets xmax on the old version and writes a new one with xmin = its own xid; SELECT xmin, xmax, * FROM credits shows them. A snapshot, written xmin:xmax:list, says which transactions had finished at one moment: every xid below the first number had finished, every xid from the second on had not started, and the list names those in between still running. A version is visible if its creator had committed by the snapshot and its deleter had not.
Real values from the serializable run below (PostgreSQL 16.15, pageinspect): after A (xid 744) committed, the page holds balance 30 (xmin 743, xmax 744) and balance 20 (xmin 744). For B's snapshot, 743 is in the past and committed, 744 is in the future, so the deleter of 30 and the creator of 20 are both invisible: B reads 30. At read committed each statement takes a new snapshot; at repeatable read and serializable the first statement's snapshot serves the whole transaction.
Fig. 3 replays the lost update of section 1 three ways, with the real heap page read after every step (the pageinspect extension) and each session's real snapshot (pg_current_snapshot() inside the same statement). Each box is one version of Ines's row, its height the balance, with its xmin and xmax under it; green is current, gold is not yet committed, faded is dead. Predict where B's write reads its 30 or its 20 from, then watch.
SELECT balance FROM credits WHERE user_id = 7. A's snapshot is 734:734:: every transaction below 734 has finished and none is running. A has no transaction id yet, because it has not written anything.UPDATE credits SET balance = 20 WHERE user_id = 7. A gets transaction id 734. It does not overwrite: it stamps xmax = 734 on the old version and writes a new version with xmin = 734. Until A commits, everyone else still sees 30.UPDATE takes a fresh snapshot (735:735:), finds the current version (20), and replaces it with the number B computed from its old read: 30 - 5 = 25. The database did what it was told.SELECT ... FOR UPDATE.744:744:; at serializable it keeps it for the whole transaction.744:744:, and keeps it.COMMIT is answered with ROLLBACK.746:746:, sees A's commit.What to take from it: at read committed B's UPDATE took a fresh snapshot and wrote a value computed from an old read; with FOR UPDATE A's lock is written into the row itself (xmax = A's xid, marked lock-only) and B waits on A's transaction; under serializable B's fixed snapshot sees a version already replaced by a transaction it cannot see, and Postgres refuses.
Recorded 2026-10-04 on PostgreSQL 16.15 (the conda-forge build, used here because it ships pageinspect; every other run on this page used 16.2 from the pgserver wheel). Transaction ids differ between the three runs because each run is a new transaction on the same server. Script: src/measure/mvcc_trace.py.
Old versions are not removed when they stop being current, because a transaction with an old snapshot might still need them. Once no running transaction can see a dead version, VACUUM makes its space reusable (run automatically by autovacuum), but does not give it back to the operating system: the table stays large, which is called bloat. VACUUM also freezes very old versions so the 32-bit transaction counter can wrap around safely; skipping that for about 2 billion transactions makes Postgres refuse writes, which took Sentry's writes down for hours in July 2015 (Postgres 16, routine vacuuming; Sentry, 2015). Tuning autovacuum, freezing and fixing bloat belong to Running Postgres in production; the part about transactions, a long transaction stopping clean-up, is measured in section 10.
An update that stays within its page and changes no indexed column is a HOT update (heap-only tuple): no index entry is added, and later readers prune the dead versions on that page without waiting for VACUUM. That is why section 10's control run updated one row 20,000 times and the table never grew past one page.
| PostgreSQL | MySQL InnoDB | |
|---|---|---|
| Where the new version goes | A new tuple in the table, old one left in place | Written in place in the table; the old values go to the undo log |
| Reading an old version | Read the old tuple directly | Start from the current row and apply undo records backwards (DB_ROLL_PTR points to them) |
| Rollback | Mark the transaction aborted: instant | Apply the undo log: proportional to the work done |
| Clean-up | VACUUM removes dead tuples from tables and indexes | The purge thread discards undo records no snapshot needs |
| What a long transaction does | Dead tuples pile up in the tables (bloat) | The undo log ("history list") grows; reads of hot rows walk longer undo chains |
InnoDB side from the MySQL 8.4 manual, which recommends committing "regularly, including transactions that issue only consistent reads. Otherwise, InnoDB cannot discard data from the update undo logs" (InnoDB multi-versioning). Page layout, the WAL and index structures are on Storage engines and indexes.
A lock is a claim a transaction holds on something (a row, a table, a number) that makes conflicting claims wait until it commits or rolls back. MVCC removed locks from plain reads; writes and explicit locking reads still take them, in two families: row locks and table locks (Postgres 16, explicit locking).
Every UPDATE and DELETE locks the rows it changes until the end of the transaction; that is why, in section 3, the second atomic UPDATE of Ines's balance waited for the first. You can take the same lock on a read:
| Clause | What it does | Use it for |
|---|---|---|
SELECT ... FOR UPDATE | Exclusive row lock: blocks other FOR UPDATE, UPDATE, DELETE on those rows (plain reads still pass) | Read-then-write on the rows you read (the lost update fix) |
... NOWAIT | Fail at once with SQLSTATE 55P03 instead of waiting | Interactive actions where waiting is worse than "try again" |
... SKIP LOCKED | Silently skip rows another transaction has locked | Many workers taking jobs from one queue table |
| Clause | What it does | Use it for |
|---|---|---|
FOR NO KEY UPDATE | Weaker: does not block FOR KEY SHARE, which foreign-key checks take. A plain UPDATE that changes no key column takes this one | Mostly automatic |
FOR SHARE / FOR KEY SHARE | Shared: others may also share-lock, nobody may change | "This row must not change until I commit" (a parent row while you insert children) |
The job queue is the classic use. The chat product keeps a jobs table (summarise a chat, index an uploaded file); several workers each run SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE. Recorded on Postgres with two workers measured:
Recorded 2026-10-04 on PostgreSQL 16.2. Durations of waits are set by the script's pace (it waits about 2 s per step while something is blocked), not by the database.
With plain FOR UPDATE worker B waited for A's whole job, then got job 2: the workers run one at a time. With SKIP LOCKED B took job 2 at once. The documentation's warning is the reason it is for queues only: "skipping locked rows provides an inconsistent view of the data, so this is not suitable for general purpose work" (Postgres 16, the locking clause). Job queues for Python built this way, their retries and dead letters are on Queues, streams and async work.
Every statement also takes a lock on each table it touches, in one of eight modes. Ordinary reads and writes take weak modes that never conflict with each other. Many ALTER TABLE forms, DROP, TRUNCATE and VACUUM FULL take ACCESS EXCLUSIVE, and "only an ACCESS EXCLUSIVE lock blocks a SELECT" (same explicit-locking page). The trap is the queue: a lock request that must wait queues, and every later request that conflicts with it queues behind it, even if it would not have conflicted with the holder. Recorded with three sessions measured; the recording itself is below the steps.
Fig. 4: the lock queue on one table, two recordings
SELECT count(*) FROM messages, left in an open transaction: it holds ACCESS SHARE on the table until it commits.ALTER TABLE messages ADD COLUMN flagged boolean needs ACCESS EXCLUSIVE, which conflicts with every mode, so it waits for A.SELECT count(*) FROM messages WHERE user_id = 7 needs only ACCESS SHARE, which conflicts only with ACCESS EXCLUSIVE and so with nothing A holds; but a conflicting request is already waiting, so C waits behind B.lock_timeout = 200ms the migration gives up instead. B waits 203 ms, fails with SQLSTATE 55P03 and leaves the queue, and C is granted at once.In production, C is every request of your API. This is how GoCardless had about 15 seconds of API downtime from a migration that should have been instant: "Set lock_timeout in your migration scripts to a pause your app can tolerate. It's better to abort a deploy than take your application down" (GoCardless engineering blog, Chris Sinjakli). In the second recording the migration gave up with SQLSTATE 55P03. Running migrations safely is on SQL and data modelling.
When the thing to protect is not a row ("only one summariser per user at a time"), Postgres lets you lock any 64-bit number whose meaning only your application knows: pg_advisory_xact_lock(7) waits for and holds the lock until the transaction ends, pg_try_advisory_lock(7) returns false at once if someone holds it. Session-level advisory locks survive ROLLBACK and must be released explicitly. Recorded: A's try returned true, B's returned false until A released it measured. A common production use is making sure only one instance of a scheduled job or migration runs.
COMMIT, not until the statement ends: whatever your code does between the locking statement and the commit (a model call, a network request) is time everyone else waits. And two transactions can each wait for the other, which is the next section.A deadlock is a cycle of waits: A holds a lock B needs while waiting for a lock B holds. Neither can move. It needs nothing unusual, just two transactions touching the same rows in opposite orders: A transfers 5 credits from Ines (7) to Quinn (12), B transfers 3 from Quinn to Ines, at the same time measured:
Fig. 5: a deadlock, then the same transfers in one lock order
UPDATE credits SET balance = balance - 5 WHERE user_id = 7 and holds row 7's lock (blue); B runs ... balance - 3 WHERE user_id = 12 and holds row 12's (purple).... balance + 5 WHERE user_id = 12, waits on B's transaction.SELECT user_id FROM credits WHERE user_id IN (7, 12) ORDER BY user_id FOR UPDATE. A locks 7, then 12; B asks for 7 first and simply waits, holding nothing, so B waits for A on row 7 and never holds 12 while A needs it: no cycle.Postgres checks for a cycle only after a lock wait has lasted deadlock_timeout (1 second by default), because the check is expensive and most waits end on their own. It then aborts one transaction with SQLSTATE 40P01 and a detail that names both processes; which one is chosen "is difficult to predict and should not be relied upon" (Postgres 16, deadlocks). In the recording B was killed after 1.0 s and A's update went through. MySQL detects deadlocks immediately by default (innodb_deadlock_detect) and returns error 1213, as in its serializable runs in section 4.
SELECT ... ORDER BY user_id FOR UPDATE: B simply waits, and both transfers complete.log_lock_waits = on logs every wait longer than deadlock_timeout, and pg_stat_database.deadlocks counts them.Locks are pessimistic: they assume a conflict and make others wait in advance. Optimistic concurrency control assumes there will be no conflict, lets everyone read freely, and checks at write time that nobody changed the row in between. The usual form is a version column and a compare-and-set: read the row with its version, then UPDATE ... SET ..., version = version + 1 WHERE id = ... AND version = <the version I read>. If someone else wrote first, the version moved and the update changes 0 rows; you re-read and try again. No transaction is held open between the read and the write. Recorded on Postgres measured:
B's first write reported UPDATE 0, so B re-read (20, version 2) and wrote 15. The final row is balance 15, version 3: both spends counted, nobody waited.
It is the tool when a person sits between the read and the write (a user edits a chat's title for a minute, then saves): no transaction or lock can be held that long, and the version column catches someone else's save in between. Over HTTP the same idea is the ETag header and a conditional If-Match request (HTTP, section 3). ORMs build it in: SQLAlchemy's version_id_col adds the version check to every UPDATE and raises StaleDataError when it matches zero rows (SQLAlchemy 2.0 docs); Rails does the same with a lock_version column.
UPDATE ... SET n = n + 1 wins. Always check the affected-row count: an optimistic update that ignores UPDATE 0 is just the lost update again.Serializable and repeatable read refuse a conflicting transaction with SQLSTATE 40001, a deadlock victim gets 40P01, and the Postgres documentation is direct about it: the application "should abort the current transaction and retry the whole transaction from the beginning" (Postgres 16, transaction isolation). The whole transaction, including its reads, because the decisions were made on data that has changed. This is the loop the benchmark below ran, unchanged, with psycopg 3:
import random, time
from psycopg import errors
RETRYABLE = (errors.SerializationFailure, errors.DeadlockDetected) # SQLSTATE 40001 and 40P01
def run_in_transaction(conn, work, max_attempts=10):
"""Run work(conn) in a transaction; on a serialization failure or deadlock, roll back and run it again."""
for attempt in range(1, max_attempts + 1):
try:
with conn.transaction(): # BEGIN ... COMMIT, or ROLLBACK if work raises
return work(conn), attempt
except RETRYABLE:
if attempt == max_attempts:
raise
time.sleep(random.uniform(0, min(0.05, 0.001 * 2 ** attempt))) # full jitter, capped
conn.isolation_level = psycopg.IsolationLevel.SERIALIZABLE
run_in_transaction(conn, lambda c: spend(c, user_id=7, cost=10))
Four rules make it safe. Everything inside work must be repeatable: no model call, no e-mail, no payment inside the transaction, because a retry would do it twice; do the slow or external part before or after, and keep only database work inside. Retry only the retryable codes; a constraint violation will fail again. Wait a random, growing time between attempts (exponential backoff with jitter) so that the colliding transactions do not collide again in lock-step. Cap the attempts and surface an error, because under a hot spot some transaction will keep losing.
When an external step must happen once (charge a card, then record it), the retry belongs to the whole request and the tool is an idempotency key: the server stores the client's key and the result in the same transaction as the work, and a repeated key returns the stored result. The pattern, with "atomic phases" between external calls, is Brandur Leach's "Implementing Stripe-like Idempotency Keys in Postgres" (brandur.org, 2017-10-27), and it is taught in full on Service APIs (section 4).
The chat product's "spend one credit and save the message" transaction, run by 2, 8 and 32 concurrent clients for 8 seconds each on Postgres 16.2, four ways: read committed with the naive read-then-write (section 1's code), read committed with one atomic UPDATE, read committed with FOR UPDATE, and serializable running the naive code inside the retry loop above. Two contention levels: every client spends from one of 4 hot users, or from 10,000 users measured.
Predict first: on 4 hot users at 32 clients, which correct way commits most per second, and does serializable stay within a factor of two of it? Then switch between the two pools.
With the load spread over 10,000 users, correctness was free: all four ways ran at about the same speed, and serializable retried about one transaction in a hundred or fewer. On 4 hot users it was not: at 32 clients serializable ran 2,207 commits a second against the atomic UPDATE's 5,761, with 1.277 retries per commit and 923 transactions that lost ten times in a row, while the naive code was fast and lost 50,384 updates. The atomic UPDATE was fastest-correct under contention because the row lock is held only from the UPDATE to the COMMIT, and nothing is computed in between. Even with only 2 clients, dozens of serializable transactions failed ten attempts in a row.
A debugging rerun logged the errors: most were SSI's "Canceled on identification as a pivot", not the simple concurrent-update case. With only four users, every read lands on one index page, and Postgres may track reads by page rather than by row, so transactions can look dependent when they are not; this run did not separate that from genuine conflicts on the same user.
One 32-client serializable run (10,000 users) on Postgres 16.2 stalled for over nine minutes: every session waited on an internal lock named SerializableFinishedList while one backend used CPU at COMMIT. Two reruns on 16.2 and one on 16.15 did not stall, so the cause is unconfirmed; the benchmark now has a watchdog and the figures shown are from a complete rerun. It is a reminder that serializable's bookkeeping is real work inside the server.
Measured 2026-10-04 on PostgreSQL 16.2, Apple M1 Pro laptop (10 cores), macOS 27.0.1; each client is its own Python process with its own connection, 8 s per run, one run per cell (a rerun of the same grid differed by up to about 30% in commits per second, so read the shape, not the third digit). Serializable transactions that failed 10 attempts and were given up, 4 hot users: 39, 241, 923 at 2, 8, 32 clients. Script: src/measure/bench.py.
A transaction that stays open costs the whole database, not just its own session, in three ways: it holds its locks (section 6), it holds back clean-up of old row versions, and in Postgres it can hold back transaction-id freezing. The second is invisible until it is large, so it was measured: one session opened a repeatable read transaction, read one row and then did nothing (a forgotten BEGIN, a notebook left open, a request stuck on a model call), while another session updated Ines's balance 20,000 times. Then the same 20,000 updates with no transaction left open, as the control measured:
With nothing held open, each old version was pruned on the spot (section 5's HOT updates). With one idle transaction holding an old snapshot, not one of the 20,000 dead versions could be removed (VACUUM VERBOSE: "dead but not yet removable"), the same updates took more than twice as long, and every read of Ines's row walked a chain of dead versions. After it ended, VACUUM removed all 20,000, but the file stayed the same size: the space is reusable, not returned. The same thing on a live server, with autovacuum on: Running Postgres in production (section 5) ran 1,500 updates a second against a 100,000-row table and left one session idle in a transaction; autovacuum kept firing every time its trigger was passed and removed nothing, so dead rows and table size climbed in a straight line until the session ended measured there.
idle_in_transaction_session_timeout: ends a session that sits idle inside an open transaction; the documentation notes it is for exactly this, because "an open transaction prevents vacuuming away recently-dead tuples" (Postgres 17, client settings).transaction_timeout (new in PostgreSQL 17, 2024) ends any transaction longer than the limit, busy or idle; statement_timeout caps one statement, lock_timeout one lock wait. All default to 0 (off); the documentation advises setting statement_timeout, lock_timeout and transaction_timeout per role, session or transaction rather than in postgresql.conf, "because it would affect all sessions".SELECT pid, state, now() - xact_start AS age, left(query, 60) FROM pg_stat_activity WHERE xact_start IS NOT NULL ORDER BY age DESC LIMIT 5. Alert when the oldest is minutes old.Replicas add a twist: a long query on a read replica either gets cancelled ("canceling statement due to conflict with recovery") or, with hot_standby_feedback = on, holds back clean-up on the primary as if it ran there. That trade-off is on Running Postgres in production and Scaling a database.
Measured 2026-10-04 on PostgreSQL 16.2 with autovacuum turned off for the table so that only the effect of the open transaction shows. Table size 8,192 B (1 page) with nothing held open against 892,928 B (109 pages) with one idle transaction; VACUUM while it was open removed 0 and reported 20,000 dead but not yet removable; after it ended VACUUM removed 20,000 and the file stayed 892,928 B. The 20,000 updates took 4.91 s against 2.05 s; reading Ines's one row took a median 351 µs against 51 µs, and 89 µs after VACUUM (300 primary-key reads from Python over TCP loopback). Script: src/measure/extras.py.
The chat product soon writes to more than one place: Postgres for credits, a search index for messages, a queue for background jobs, a payment provider. No single COMMIT covers them. The answer at the database level is the transactional outbox: write the business change and a row in an outbox table in one local transaction; a separate process publishes the outbox rows to the queue afterwards, at least once. "Write to two systems" becomes "write to one database".
A coordinator asks every participant to prepare (do everything but the final commit, and promise to be able to commit), then tells all of them to commit. Postgres supports it with PREPARE TRANSACTION and COMMIT PREPARED, off by default (max_prepared_transactions = 0) (Postgres 16, PREPARE TRANSACTION). Its cost is blocking: a participant that has prepared holds its locks until it hears from the coordinator, and if the coordinator dies, it waits. A forgotten prepared transaction also holds back VACUUM like section 10's idle session.
Give up atomicity across systems: run a sequence of local transactions, and if a later step fails, run compensating transactions that undo the earlier ones (refund the credits). Each step is short and local; the price is that other requests can see the in-between states, and every step needs an undo.
All three, with measured crash and redelivery behaviour on a real Postgres, are taught on Queues, streams and async work (sections on the outbox and on sagas against two-phase commit). Databases that spread one logical database over many machines and still offer serializable transactions (Spanner, CockroachDB) use consensus and careful clocks under the hood: see Distributed systems fundamentals and Scaling a database.
The relay claims unsent rows with FOR UPDATE SKIP LOCKED (section 6), publishes them and marks them sent. A crash between publishing and marking sends the event again, so consumers must be idempotent. If the transaction rolls back, no event exists: nothing to undo.
Most Postgres applications run the default, read committed, with the five habits at the top: checks folded into writes, constraints for every declarable rule, FOR UPDATE where a read must not go stale, and serializable for the few transactions that guard multi-row rules. Teams that choose serializable everywhere (CockroachDB's default, for instance) accept the retry loop as part of every data access path; many MySQL shops run read committed for its simpler locking, with atomic updates or FOR UPDATE because MySQL's repeatable read does not stop lost updates. Short transactions are enforced by settings (idle_in_transaction_session_timeout on application roles, lock_timeout on migrations, a statement timeout per endpoint, an alert on the oldest open transaction); migrations go in small steps and it is the migration that retries, not the app. One retry helper for 40001 and 40P01 serves every transaction, idempotency keys guard the API edge, and job queues live in the database with FOR UPDATE SKIP LOCKED until throughput says otherwise, with an advisory lock for a job that must run once at a time.
Pick an anomaly, a database and an isolation level, and step through the real recording, one statement at a time. Nothing here is simulated: each run is two or three live sessions on PostgreSQL 16.2 or MySQL 9.7.2, recorded on this page's laptop by src/measure/, with the statements, the results, the errors and the lock waits exactly as they happened.
The anomalies are explained in the Reading tab, section 3, and the matrix of all of them in section 4. The lock scenarios (deadlocks, the lock queue, job queues, optimistic updates, advisory locks) are from sections 6 to 8 and exist for Postgres only.
Every link opens in a new tab; times are estimates for a careful first read. Links checked on 2026-10-04.
Every recorded run: eight anomalies at four levels on Postgres and MySQL, with fixes, plus the deadlock, lock-queue, job-queue, optimistic and advisory-lock recordings, one statement at a time. About 20 minutes.
The root: one chat product's data from a file to a fleet. Its Reading tab, section 3, introduces transactions with Ben's last credit; its SQL playground tab, lesson 10, runs a transfer on SQLite and Postgres; Query plans shows real EXPLAIN output on 10 million messages. About 27 minutes, plus the tabs.
Constraints that make the database refuse bad data, schema design, and migrations that do not lock out the app. Child page, about 48 minutes.
Pages, B-trees, LSM-trees and the WAL that durability (section 2) and MVCC (section 5) are built on. Child page, about 42 minutes.
Autovacuum tuning, freezing and wraparound, bloat repair, replication and synchronous commit to replicas, connection pooling. Child page, about 43 minutes.
Read replicas (and what they do to long queries), sharding, distributed SQL with serializable transactions across machines. Child page, about 45 minutes.
Why a missing index turns a serializable transaction's tracked reads into a whole-table lock (section 4) and how to find slow queries. Child page, about 45 minutes.
Every cache layer, Redis eviction measured on real traffic, invalidation, and the KV, prompt and semantic caches. Child page, about 43 minutes.
Column stores, Parquet, DuckDB, ClickHouse, cloud warehouses, Iceberg and the lakehouse, and point-in-time joins for ML. Child page, about 46 minutes.
Redis, DynamoDB, MongoDB, Cassandra, time series and graph databases, measured against Postgres. Child page, about 46 minutes.
Inverted indexes, BM25, embeddings, ANN indexes measured in pgvector, filtered and hybrid search. Child page, about 33 minutes.
Idempotency keys and retries across services in full (section 4). About 52 minutes.
The data layer around a transaction (section 5): pools, one transaction per request, round trips. About 32 minutes.
The transactional outbox, sagas against two-phase commit, job queues on Postgres, idempotent consumers, measured on a real Postgres. About 40 minutes.
Consistency models across machines (linearizability against serializability), replication, consensus, clocks. About 46 minutes.
Retries, backoff and timeouts as a system-wide discipline. About 40 minutes.
The official account of MVCC, the isolation levels, explicit locking and serializable's rules, with examples. Read first, sections 13.1 to 13.4. About 1 hour.
Martin Kleppmann and Chris Riccomini, O'Reilly, 2026. The transactions chapter is the clearest book treatment of every anomaly on this page, including the on-call doctors. About 2 hours for the chapter.
Kleppmann's test suite (2014 onward): every anomaly as a two-session script, run against Postgres, MySQL, Oracle, SQL Server, CockroachDB and others. The model for this page's recordings. About 30 minutes.
Worked serializable examples, including the deposit report of section 3. About 30 minutes.
Brandur Leach, 2017: atomic phases, recovery points and serializable transactions in a real API design. About 40 minutes.
GoCardless engineering blog: the lock queue incident of section 6 and lock_timeout. About 15 minutes.
Record, gap and next-key locks, consistent reads, the four levels as InnoDB implements them. About 1 hour.
2020-06-12 and 2023-12-19: how professionals test isolation claims, and what they found. About 45 minutes each.
Berenson, Bernstein, Gray, Melton, O'Neil and O'Neil, SIGMOD 1995: lost update, read skew, write skew and snapshot isolation named. About 1 hour.
Atul Adya's MIT thesis, 1999: isolation levels as forbidden dependency cycles (G0, G1, G2). Skim chapters 3 and 4, about 1.5 hours.
Fekete, O'Neil and O'Neil, SIGMOD Record 2004: the anomaly of section 3, card 8. About 30 minutes.
Cahill, Röhm and Fekete, SIGMOD 2008: the dangerous-structure test that SSI is built on. About 1 hour.
Ports and Grittner, VLDB 2012: how Postgres implemented SSI, its read-only optimisations and its measured cost. About 1 hour.