Transactions and concurrency: ACID, MVCC, isolation anomalies, locks

What happens when two requests touch the same data at the same moment, on the chat product's credits, quotas and on-call rota. Every anomaly was reproduced with live sessions on a real PostgreSQL 16.2 and MySQL 9.7.2; sources are linked inline. Child page of Topic: databases; data as of October 2026. Reading: 43 min, plus 5 in closed details.

The idea in one screen

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

  1. Ines has 30 credits and two tabs open. Tab A spends 10 and tab B spends 5 at the same moment, so the correct end is 15. Time runs left to right: tab A's statements sit on the front lane, tab B's on the back one, and the strip between them is the committed balance, its height the value.
  2. The collision: read, compute in Python, write back. At read committed both tabs read 30; A writes 20 and commits; B writes 30 - 5 = 25 over it. Final 25: A's 10 credits are lost, and every statement succeeded.
  3. Fix 1: fold the check into one UPDATE. With 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.
  4. Fix 2: lock what you read. With SELECT ... FOR UPDATE, B's read waits for A's whole transaction, then returns 20, and B writes 15.
  5. Fix 3: serializable refuses B, the application retries. B's write is refused with SQLSTATE 40001, because the row changed after B's snapshot; the application rolls back and runs B again, which reads 20 and writes 15. Final 15: B ran twice.

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/.

The five habits of a professional
  1. Write a check and the change it guards as one statement where you can: UPDATE credits SET balance = balance - 10 WHERE user_id = 7 AND balance >= 10, then read how many rows changed.
  2. Know your database's default isolation level and what it lets through. Postgres defaults to read committed; MySQL defaults to repeatable read, which on this laptop still lost an update that Postgres's repeatable read refused (section 4).
  3. When a rule spans several rows, use serializable (Postgres) and retry on SQLSTATE 40001, or lock one row that every competing transaction must lock first.
  4. Keep transactions short: never hold one open across a call to a language model, a payment provider or a user's think time.
  5. Make every retried operation idempotent, so running it twice does no harm.
Session
one connection to the database; its statements run in order, but statements of different sessions interleave.
Transaction
BEGIN ... COMMIT or ROLLBACK: statements treated as one unit.
Isolation level
the setting that decides which anomalies the database still allows.
Anomaly
an outcome no one-at-a-time order of the transactions could produce.
Snapshot
which transactions had committed at one moment; what a reader is allowed to see.
MVCC
multi-version concurrency control: readers see old row versions while writers make new ones.
Row lock
a claim on a row that makes conflicting writers wait until commit or rollback.
Serialization failure
SQLSTATE 40001: the database refused a transaction to keep the result serializable; retry it.
Version column
a counter checked and incremented by every update (optimistic concurrency).
Idempotency key
a client-chosen key that makes a repeated request return the first result instead of acting twice.
Every problem on this page, what prevents it and what that costs (reference)
The problemWhat prevents itWhat that costsSection
Half a change survives a crash or an error (credits taken, reply never saved)A transaction: BEGIN ... COMMIT, all or nothingYour code must roll back after any error1, 2
A committed change vanishes in a power cutDurability: the log is flushed to disk before COMMIT returnsOne disk flush per commit: 6.842 ms per commit on this laptop with the drive cache flushed2
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 retryWaiting on a lock, or a retry3, 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 touchRetries under contention; locks to design3, 4
A report sees half of a transfer (read skew)Repeatable read: one snapshot for the whole transactionOld row versions kept around3, 5
Two transactions wait for each other foreverDeadlock detection kills one; take locks in one orderA retry; a design rule7
A transaction left open for an hourTimeouts: idle_in_transaction_session_timeout, transaction_timeout, lock_timeoutSome work is cancelled10

1. Why transactions: two requests, one balance

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:

All or nothing (atomicity)

If anything fails half-way, none of the changes survive. This is about failures, and every relational database gives it in full.

As if alone (isolation)

Concurrent transactions should not see each other's half-done work or trample each other's decisions. How much of it you get depends on the isolation level. Wrapping Ines's code in 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).

2. ACID, one letter at a time, and what each costs

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.

Constraints checked at commit: DEFERRABLE (depth)

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.

On a Linux server (depth)

The default is fdatasync and honesty depends on the drive; datacentre SSDs with power-loss protection make honest flushes cheap.

Correction to the old storage page
The former "Storage engines, indexes, and the physics of a query" page said 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).
What professionals do with this
  • Never turn 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.
  • Durability across machines (waiting for a replica, synchronous_commit = remote_apply) is a replication question: Running Postgres in production and Distributed systems fundamentals.

A durable commit costs one honest flush: 0.125 ms when the drive cache absorbs it, 6.842 ms when it does not

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.

3. The anomalies: eight ways two transactions collide

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.

How the recordings were made (provenance)

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/.

1. Dirty read: reading what was never committed

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.

2. Non-repeatable read: the same row, two values

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.

3. Phantom: rows appear in a range

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.

4. Lost update: read, compute in the app, write back

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.

5. Read skew: two rows from two different moments

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.

6. Write skew: two valid decisions, one broken rule

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

  1. The rule and the rows. Ana and Raj are both on call (the green strips). The rule, at least one engineer on call, is not declared in the schema, so only the code enforces it.
  2. Both count 2. At repeatable read, A (Ana) and B (Raj) each run SELECT count(*) FROM oncall WHERE on_call: both snapshots honestly show 2.
  3. Each signs off their own row. A sets Ana off, B sets Raj off, and both commit. No row was written twice, so nothing waited and no update was lost, yet 0 engineers are on call.
  4. Serializable refuses B's COMMIT. The same statements: Postgres records a read-write dependency each way (each read the row the other then wrote: the red arcs) and refuses B at COMMIT with SQLSTATE 40001. Raj stays on call.
  5. Or lock the rows you read. At read committed with 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.

7. Write skew on a quota: the row that does not exist yet

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.

8. A serialization anomaly with a read-only transaction

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.

4. Isolation levels: what each one lets through, 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.

How to read it
  • Postgres read committed (the default) blocks only dirty reads. Everything else in the table got through, including the lost update.
  • Postgres repeatable read is snapshot isolation (snapshot isolation: each transaction reads one consistent snapshot, and a write fails if the row changed since). Jepsen's 2020 analysis agrees: "PostgreSQL's 'repeatable read' isolation level is actually snapshot isolation" (Jepsen, PostgreSQL 12.3, 2020-06-12). It stops the lost update with an error, but not write skew in either form, nor the read-only anomaly.
  • Postgres serializable stopped everything, in these runs always by aborting one transaction with SQLSTATE 40001 rather than by making anyone wait (two writes to the same row still wait for each other's row lock first). Your code must retry (section 9).
  • MySQL's default, repeatable read, lost the update that Postgres's repeatable read refused, and let both write skews through.
  • MySQL serializable works by locking instead: every plain 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.
Where the levels come from, and other databases (history and comparison)

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).

How Postgres's serializable works without locking everything

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).

Reading the error messages, read-tracking granularity and a Jepsen bug (depth)

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).

Section 3's read-only anomaly as SSI sees it: purchase A has a read-write edge in and a read-write edge out, so A is the pivot and is aborted

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.

Which level to use
  • Read committed (Postgres's default) is right for most single-statement work and for transactions whose every check is folded into its writes (atomic UPDATE ... WHERE, constraints, FOR UPDATE where needed).
  • Repeatable read for anything that reads many rows and needs them consistent: reports, exports, audits, a backup (pg_dump takes one snapshot for this reason).
  • Serializable when a business rule spans rows and you cannot or will not reason about every interleaving: quotas, rotas, inventory, double-booking. Declare read-only transactions 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.

5. MVCC: how a database isolates without stopping everyone

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).

Row versions and snapshots in Postgres

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.

B's snapshot 744:744: sees the version of 30 and not the version of 20, because transaction 744 had not started when the snapshot was taken

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.

The lost update three ways, on a real heap page

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.

  1. Start. Ines's row is one version on the page: balance 30, created by transaction 733 long ago. Both tabs run at read committed, Postgres's default.
  2. A reads 30. 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.
  3. B begins. B opens its transaction.
  4. B reads 30. B takes its own snapshot, the same one: it sees the same version, 30. Nothing blocks a read.
  5. A writes 20. 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.
  6. A commits. One bit in the commit log flips: 734 is committed. The old version is now dead and the new one is current.
  7. B writes 25. B's 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.
  8. Result: an update lost. Three versions on the page; the current one says 25. Both spends committed; Ines was charged for one of them. Nothing in the database was wrong; the read and the write were simply two separate statements.

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.

Why VACUUM exists

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.

The other design: InnoDB's undo log, side by side with Postgres (comparison)
PostgreSQLMySQL InnoDB
Where the new version goesA new tuple in the table, old one left in placeWritten in place in the table; the old values go to the undo log
Reading an old versionRead the old tuple directlyStart from the current row and apply undo records backwards (DB_ROLL_PTR points to them)
RollbackMark the transaction aborted: instantApply the undo log: proportional to the work done
Clean-upVACUUM removes dead tuples from tables and indexesThe purge thread discards undo records no snapshot needs
What a long transaction doesDead 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.

6. Locks: making the other transaction wait

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).

Row locks

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:

ClauseWhat it doesUse it for
SELECT ... FOR UPDATEExclusive 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)
... NOWAITFail at once with SQLSTATE 55P03 instead of waitingInteractive actions where waiting is worse than "try again"
... SKIP LOCKEDSilently skip rows another transaction has lockedMany workers taking jobs from one queue table
The weaker row-lock modes (reference)
ClauseWhat it doesUse it for
FOR NO KEY UPDATEWeaker: does not block FOR KEY SHARE, which foreign-key checks take. A plain UPDATE that changes no key column takes this oneMostly automatic
FOR SHARE / FOR KEY SHAREShared: 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.

Table locks and the lock queue

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

  1. A holds a weak lock and stays open. An analytics query, SELECT count(*) FROM messages, left in an open transaction: it holds ACCESS SHARE on the table until it commits.
  2. The migration queues. B's ALTER TABLE messages ADD COLUMN flagged boolean needs ACCESS EXCLUSIVE, which conflicts with every mode, so it waits for A.
  3. An ordinary read queues behind the migration. C's 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.
  4. A commits; the queue drains in order. B is granted and the ALTER runs, then C is granted and returns 2.
  5. With 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.

Advisory locks: a lock on a number

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.

What locks cost
Waiting. Every lock turns a conflict into latency for someone, and the lock is held until 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.

7. Deadlocks: waiting for each other forever

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

  1. Each transfer takes its first row. A runs 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).
  2. A needs row 12: it waits for B. A's second update, ... balance + 5 WHERE user_id = 12, waits on B's transaction.
  3. B needs row 7: it waits for A. A cycle. A locked Ines's row (7) and waits for Quinn's (12); B locked 12 and waits for 7. Each holds what the other needs, so neither can move.
  4. Postgres breaks the cycle. B was killed after 1.0 s with SQLSTATE 40P01, its lock on row 12 released; A's update went through and A committed. Rows 7 and 12 end at 25 and 25: only A's transfer happened, and B must retry.
  5. Same order: lowest id first. Both transfers start with 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.
  6. A commits; B runs. B gets both rows, and both transfers complete: 28 and 22.

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.

How professionals avoid them
  • Take locks in one global order. The documentation: "the best defense against deadlocks is generally to avoid them by being certain that all applications using a database acquire locks on multiple objects in a consistent order". The second recording locks both credit rows lowest id first with one SELECT ... ORDER BY user_id FOR UPDATE: B simply waits, and both transfers complete.
  • Keep transactions short, so the window for a cycle is small.
  • Retry on 40P01 like a serialization failure: a deadlock victim's transaction did nothing, so running it again is safe if the work is idempotent (section 9).
  • Watch for them: log_lock_waits = on logs every wait longer than deadlock_timeout, and pg_stat_database.deadlocks counts them.

8. Optimistic concurrency: check at write time instead of locking

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.

What it costs, and when not to use it
Wasted work under contention: every lost race is a re-read and a retry. It shines when conflicts are rare (a user editing their own settings) and does badly on a hot row that many writers hit at once (a shared counter, a team's credit pool), where a lock or one atomic 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.

9. Retries in application code, and what serializable costs

A real retry loop

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).

Measured: the price of correctness under contention

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.

Why the hot case retried so much, and one stalled run (depth)

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.

Spread over 10,000 users every correct way is as fast as the wrong one; on 4 hot users serializable pays in retries

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.

10. Long transactions and what they cost

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.

What professionals set (Postgres)
  • 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".
  • A dashboard query for the oldest open transactions: 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.
  • In application code: never call a language model, a payment provider or anything slow while a transaction is open. Read, commit, call the model, then write the result in a new short transaction (with the checks of sections 3 and 8 at write time).
Long queries on read replicas (depth)

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.

One idle transaction kept all 20,000 dead versions alive: 109 pages instead of 1, and every read of Ines's row walked the chain

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.

11. Transactions across more than one database

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".

Two-phase commit and sagas (the other two answers)

Two-phase commit (2PC)

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.

Sagas

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 outbox: one local COMMIT covers the credit, the message and the event; delivery to the queue happens afterwards, at least once

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.

In production (as of October 2026)

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.