Transactions

120 transactions edit one hospital roster, 300 a second. At read committed each takes 2.1 ms, but 23 of 30 shifts end with nobody on call and 17 of 60 page counts vanish. Every serializable engine keeps all 30 shifts covered. It pays in aborts, waiting or a queue.

Pick an isolation level and watch the roster. Then we build each part from zero: what ACID means, read committed, snapshots, lost updates, write skew, and three ways to get serializability.

You need a little SQL and a little Python. We build the rest from zero.

Choose the isolation level

Illustrative and seeded. 30 shifts with 2 doctors on call. Every doctor asks to go off call, and goes only if the count of the shift's doctors on call is at least 2. The second doctor of a shift asks about 2 ms after the first. Mixed in are 60 page-counter increments, written as read, then write. Each statement is a 1 ms round trip; an aborted transaction retries.

Chapter 0

Two Writes, Two Users

Count how often two requests touch the same row at the same moment

A flight has one seat left. Two customers press Book in the same second. Each request reads "1 seat left", then writes a booking. Both succeed, and the airline sold one seat twice.

A bank transfer has a different problem. It takes $100 from Alice, then adds $100 to Bob. If the server crashes between the two writes, $100 vanishes.

A transaction groups reads and writes into one unit. It either commits, and all its writes stay, or it aborts, and none stay. The database also controls what it sees of other transactions while it runs.

How often do two requests overlap? Call the rate of bookings for one flight λ (lambda), in bookings a second. Call the time from a request's read to its write d. A booking is at risk when another one arrives less than d before or after it.

Count overlapping bookings

Each bar is one booking, from its read to its write, on a time line. Red bars overlap another booking. Move the rate and the time.

5
50 ms

Illustrative and seeded: 20,000 bookings arrive at random times (a Poisson process) at the chosen rate.

Call the chance that a booking overlaps at least one other Poverlap.

Say it aloud

P-overlap equals one minus e to the minus two lambda d.

Poverlap
P-overlap the chance that a booking shares its time with at least one other booking.
e
e to the minus the number 2.718 raised to a negative power: the chance of zero arrivals in a window.
2λd
two lambda d the expected number of other bookings in the risky window, d before and d after this one.
In plain words

The risky window is d before and d after a booking, so it is 2d wide. Bookings arrive at random at rate lambda, so the window holds 2-lambda-d of them on average. The chance it holds none is e to the minus 2-lambda-d. One minus that is P-overlap.

With numbers

With made-up numbers: lambda = 5 bookings a second for a popular flight and d = 50 ms = 0.05 s. 2-lambda-d = 0.5, so P-overlap = 1 − e−0.5 = 39.3%. Our 20,000 seeded bookings gave 39.6%. A test with one user at a time has lambda near 0, so it never sees a race.

This lesson follows Chapter 8 of Designing Data-Intensive Applications, 2nd edition, by Martin Kleppmann and Chris Riccomini (O'Reilly, 2026). We explain its ideas in our own words, with our own examples and simulations. Distributed Transactions steps through anomaly schedules, version visibility, two-phase commit and sagas. We link to it and go deeper on one machine.

Failure. Symptom: rare double bookings in production that no test reproduces. Measure: the request rate on the hottest row and the time from read to write. Cause: two requests read the same state before either writes. Fix: a transaction at the right isolation level, or one statement that checks and writes together.

  1. ACID: what each letter promises on one machine, and what durability costs.
  2. Read committed: no dirty reads and no dirty writes.
  3. Snapshots: a report that adds up while transfers run.
  4. Lost updates: read, modify, write, and four fixes.
  5. Write skew: two rows, one rule, and phantoms.
  6. Serial: one thread and no locks, with stored procedures.
  7. Two-phase locking: readers block writers.
  8. SSI: run on snapshots, check at the end.
  9. The showcase: the hero's roster with every knob.
  10. The field guide: numbers, checklist, code and links.
Bookings for one flight arrive 5 a second, and each holds 50 ms between its read and its write. About how often does a booking overlap another?

Chapter 1

What the Four Letters Promise

Separate the four promises, and measure what a durable commit costs

ACID names four promises. Vendors use the word loosely, so read each letter as a specific guarantee.

Durability has a price. Forcing the log to disk, an fsync, takes milliseconds, and each commit waits for one. Group commit lets many commits share one flush: the database writes every commit record that arrived during the last flush, then forces them together.

Share one flush

The lines are commits a second against the number of clients, one flush at a time and with group commit. The dot is your setting. Move the clients and the flush time.

16
2 ms

Illustrative and seeded: each client works about 1 ms, then commits and waits for its flush. One flush takes tf, a made-up figure; measure your own disk.

How many commits a second can one log take? Call the time of one flush tf and the commits that share it, the batch, b. Call commits a second X.

Say it aloud

X equals b over t-f.

X
X durable commits a second, when the log is always flushing.
b
b the batch: commits that wait for the same flush. 1 without group commit.
tf
t-f the time of one flush to disk, in seconds.
In plain words

The log flushes back to back. Each flush takes t-f and makes b commits durable. So the log finishes b commits every t-f seconds.

With numbers

With made-up numbers: t-f = 2 ms. One commit per flush: X = 1 / 0.002 = 500 a second, whatever the client count. 64 clients with group commit: the seeded batch was 31.9, so X = 31.9 / 0.002 = 16,000 a second, and each commit waited 3 ms.

Some systems trade durability for speed. PostgreSQL's synchronous_commit = off returns before the flush, so a crash can lose the last few commits. That is a choice to make per table, not by accident.

Failure. Symptom: a write the client saw commit is gone after a power cut. Measure: whether the commit returns before the log reaches disk. Cause: an asynchronous commit setting, or a disk cache that loses data on power loss. Fix: flush before you acknowledge, use group commit for speed, and copy to a second machine for more.

Which ACID promise does the application keep, rather than the database?

Chapter 2

No Dirty Reads, No Dirty Writes

Interleave two writers and see which orders leave the rows disagreeing

One row is easy. Storage engines make a single-row write atomic, and they offer one-statement operations such as an increment. The hard cases touch several rows: a message and its channel's unread counter, a ticket and its receipt, a row and its index entries. These are multi-object transactions.

Read committed is the weakest level most databases use. It makes two promises:

Why do dirty writes matter? Two buyers want the last concert ticket. Each transaction writes the ticket's owner, then the receipt's owner. If their statements interleave, the ticket can name Bea while the receipt names Ali.

Interleave two buyers

Each row is one order of the four writes: blue for Ali's transaction, warm for Bea's. The mark says whether the ticket and receipt agree. Turn on row locks, then raise the rows each buyer writes.

2

Exact enumeration. Both buyers write the same rows in the same order. With locks, a writer that reaches a row the other holds waits until that one commits.

How many orders must a tester try? Call the statements in the two transactions m and n. Call the number of interleavings I.

Say it aloud

I equals m plus n factorial, over m factorial times n factorial.

I
I the number of different orders the two transactions' statements can run in.
(m + n)!
m plus n factorial the orders of all m + n statements if every statement were different: 1 × 2 × … × (m + n).
m! · n!
m factorial times n factorial divide these out, because each transaction keeps its own statements in order.
In plain words

Lay out m + n slots. Choose which m slots belong to the first transaction; the second takes the rest. I counts those choices.

With numbers

m = n = 2: I = 24 / (2 × 2) = 6. Two of the 6 leave the rows naming different buyers. m = n = 5: I = 252, and 168 disagree. Without locks, your test runs one order; production runs them all.

Databases prevent dirty writes with row locks: a writer locks the row until it commits, so the second buyer waits. For reads, most engines do not lock. They keep the old committed value and give it to readers until the writer commits, so a long write never blocks a read.

Failure. Symptom: a ticket and its receipt name different buyers. Measure: rows whose related rows disagree, after concurrent writes. Cause: no row locks, so two transactions overwrote each other's uncommitted writes. Fix: run both writes in one transaction at read committed or above; PostgreSQL, MySQL and SQL Server all lock rows on write.

Under read committed, Ali's transaction has written a row but not committed. Bea's transaction reads that row. What does Bea see in PostgreSQL?

Chapter 3

A Report That Adds Up

Sum the accounts while transfers commit, and see a snapshot fix the total

A bank keeps 100 accounts of $1,000 each, so the total is $100,000. A report reads the accounts one by one, which takes 10 seconds. Meanwhile, transfers move money between accounts and commit.

Under read committed, each read sees the latest committed value. A transfer can commit after the report read the source but before it reads the target. The report then counts the money twice. The reverse order misses it. This is read skew, also called a non-repeatable read: one transaction sees the database at more than one moment.

Run the report

Each cell is an account; the yellow cursor is the report reading them in order. A red link is a transfer that commits between the reads of its two accounts. Choose a level and play.

30

Illustrative and seeded: transfers of $10 to $200 between two random accounts, at random times. The report reads account i at time (i + 0.5)/100 of the 10 s scan.

How many transfers fool the report? Call the transfer rate λ, the scan time T, and the transfers that commit between the reads of their two accounts E.

Say it aloud

E equals lambda times T, over three.

E
E the expected number of transfers the report sees half of.
λ
lambda transfers a second.
T
T the scan time in seconds: 10 here.
/ 3
over three the average chance that a transfer splits the scanned and unscanned parts.
In plain words

During the scan, lambda-T transfers commit. One that commits when a fraction u of the accounts is read splits its pair with chance 2u(1 − u): one account read, one not. Averaged over the scan, that chance is one third.

With numbers

lambda = 30 and T = 10 s: E = 300 / 3 = 100. Our seeded run had 321 transfers, and 116 of them fooled the report, which came out $858 too high. Under a snapshot it reads $100,000.

Snapshot isolation gives each transaction one frozen view: the database as it was when the transaction started. The engine keeps old row versions and picks the one current at the snapshot, which is multi-version concurrency control (MVCC). Snapshots and Versions steps through the visibility rule. Readers never block writers, and writers never block readers. Backups use it; PostgreSQL's pg_dump reads from one snapshot.

Names are a trap. PostgreSQL calls snapshot isolation REPEATABLE READ. MySQL InnoDB's REPEATABLE READ also reads from a snapshot, but its updates and locking reads see the newest row. SQLite in WAL mode gives readers a snapshot. Test what your database does, not what the level is called.

Failure. Symptom: a nightly report or backup that does not add up, by a different amount each night. Measure: run it twice on a quiet copy and compare. Cause: each read saw a different moment. Fix: run the whole report in one snapshot transaction, or on a replica.

A report scans for 10 s while 30 transfers a second commit. About how many transfers does read committed show half of?

Chapter 4

Read, Modify, Write

Increment one counter from many clients, and compare four ways to keep every increment

The roster's page counter starts at 10. Two transactions read 10, each adds 1, and each writes 11. One increment is gone. This is a lost update. It happens whenever a transaction reads a value, computes a new one in the application, and writes it back.

We ran it in SQLite with two connections. Two separate read-then-write steps ended at 11; two UPDATE c SET v = v + 1 statements ended at 12. Snapshot isolation alone does not save you either, since both snapshots hold 10. Four fixes work:

  1. An atomic operation. Let the database read and write in one statement: UPDATE … SET v = v + 1. The row lock makes the second statement wait and then use the new value.
  2. An explicit lock. SELECT … FOR UPDATE locks the row when you read it, so a second reader waits until you commit.
  3. Automatic detection. Under snapshot isolation, PostgreSQL aborts the second updater with "could not serialize access due to concurrent update". You retry.
  4. Compare-and-set. Write only if the row still has the version you read: UPDATE … WHERE id = 1 AND ver = 7. Zero rows changed means retry. In SQLite the second writer changed 0 rows.

Keep every increment

Each row is one method. The purple bar is the final count out of 100; red is lost. Pink is time spent waiting for a lock; the number is retries. Raise the rate.

250

Illustrative and seeded: 100 increments arrive at random; each statement is a 1 ms round trip. "No protection" reads, then writes, at read committed. Automatic detection runs at snapshot isolation; the others at read committed.

The worked number, at 250 increments a second: no protection keeps 68 of 100. The atomic statement keeps all 100 with no retries. FOR UPDATE keeps 100 but holds each reader for a round trip: 95 ms of waiting in total. Detection and compare-and-set keep 100 with 117 retries. Retries cost work; locks cost waiting.

Failure. Symptom: a like counter or stock level drifts below the true count under load. Measure: compare the counter with a COUNT(*) of the events behind it. Cause: read, modify, write in two statements. Fix: one atomic statement where it fits; otherwise FOR UPDATE or a version check with a retry loop.

Two transactions at PostgreSQL's REPEATABLE READ both read a counter of 10 and write 11. What happens?

Chapter 5

Two Rows, One Rule

Break a rule that spans rows, then fix it with locks, slot rows or serializability

Ana and Ben are on call for the night shift. The rule: at least one doctor stays on call. Both feel ill and ask to go off at the same moment. Each transaction counts the shift's doctors on call, sees 2, and sets its own row to off.

Each transaction wrote a different row, so nothing conflicts and both commit. The shift has nobody. This is write skew: two transactions read the same rows, decide from what they read, then write different rows. Each check passed; together they break the rule. Snapshot isolation does not catch it, because it only compares writes.

We ran both doctors in SQLite. As two separate statements each, the count ended at 0. Inside two transactions in WAL mode, the second write failed with SQLITE_BUSY_SNAPSHOT, and one doctor stayed. SQLite lets one writer go at a time (Chapter 6).

Now a meeting room. A booking checks "no booking for room 3 at 2 pm", then inserts one. The check finds zero rows, so FOR UPDATE has nothing to lock. The other booking inserts a row the first check would have found. A write that changes the result of another transaction's search is a phantom.

Break the rule, then fix it

Each tile is one pair of concurrent requests. Green kept the rule; red broke it: a shift with nobody, or a room booked twice. Pick a scene and a fix.

Illustrative and seeded: 40 pairs; the second request follows the first by about 2.5 ms; each statement is a 1 ms round trip. Fixes run at read committed; Serializable is the SSI engine of Chapter 8.

The worked number, 40 pairs. With no fix, 11 shifts end with nobody, and 11 rooms get two bookings. FOR UPDATE on the two doctor rows fixes the doctors. The second request waits, then counts 1. It fixes no room, because it locked no row. Materializing the conflict does: create one slot row per room and hour, and lock it first. Serializable fixes both, with 11 aborts and retries.

Prefer the simplest tool that states the rule. A unique constraint on (room, hour) makes the database refuse the second booking. Slot rows work, but they put a concurrency trick into your data model. Serializable isolation catches cases you did not think of.

Failure. Symptom: a rule that spans rows, such as "one doctor on call", is broken after two people acted at once. Measure: run a query for the rule after load tests with concurrent requests. Cause: write skew; each check read data the other was about to change. Fix: lock the rows the check reads, add a constraint, or use serializable isolation.

Two bookings each check "no booking for room 3 at 2 pm" with SELECT … FOR UPDATE, then insert. Why can both succeed?

Chapter 6

One Thread, No Locks

Run transactions one after another, and count what round trips and cross-partition work cost

The simplest way to avoid concurrency bugs is to have no concurrency. Run each transaction on one thread, start to finish, then the next. This actual serial execution is serializable by construction.

Real systems do it. VoltDB, which grew from the H-Store research system, runs each partition's transactions one at a time on one thread. Redis runs a MULTI/EXEC block with no other client's command in the middle. SQLite lets one writer at a time change the database.

The catch is the client. An interactive transaction sends a statement and waits for the reply before the next, and the one thread sits idle meanwhile. So these systems take the whole transaction at once, as a stored procedure: Java classes in VoltDB, Lua scripts in Redis.

Call the thread's work per transaction t, the round trips it waits for r, and one round trip RTT. Call transactions a second on one thread X.

Say it aloud

X equals one over t plus r times RTT.

X
X transactions a second that one serial thread can finish.
t
t the thread's own work per transaction, in seconds.
r
r round trips to the client inside the transaction: 0 for a stored procedure.
RTT
R-T-T one round trip between client and database, in seconds.
In plain words

The thread holds each transaction for its work t plus r round trips of RTT. It does nothing else meanwhile. So X is one over that time.

With numbers

With made-up numbers: t = 0.05 ms in memory, RTT = 0.5 ms, r = 4. X = 1 / 2.05 ms = 488 a second. As a stored procedure, r = 0 and X = 1 / 0.05 ms = 20,000 a second, 41 times more.

To use more cores, split the data into P partitions, each with its own thread. A transaction that touches several partitions must hold them all. Call that share f, and a transaction's time on a thread s.

Say it aloud

X-P equals P over s times the quantity one minus f, plus f times P.

XP
X-P transactions a second on P partitions, at best.
P
P the number of partitions, one thread each.
s
s the time one transaction holds a thread.
f
f the share of transactions that touch every partition.
In plain words

P threads supply P thread-seconds a second. A local transaction uses s of them; a cross-partition one uses s times P. Divide supply by the average use.

With numbers

P = 8 and s = 0.05 ms. With f = 0: X-P = 160,000 a second. With f = 10%: X-P = 8 / (0.05 ms × 1.7) = 94,118. Our seeded queue gave 55,672: threads idle while a cross-partition transaction waits for the slowest queue.

Feed a serial thread

Left: one thread's transactions a second against round trips; the highlighted bar is yours. Right: P partitions, the formula's best case against the seeded queue. Move both sliders.

4
10%

Illustrative, made-up figures: t = 0.05 ms and RTT = 0.5 ms. Left bars use a square-root scale so small values stay visible. The queue simulation runs 4,000 seeded stored-procedure transactions; a cross-partition one starts when every partition is free.

Failure. Symptom: throughput halves when a new feature ships. Measure: the share of transactions that touch several partitions. Cause: the feature reads across partitions. Fix: a partition key that keeps each transaction local; see Sharding.

Why do serial-execution databases require stored procedures?

Chapter 7

Readers Block Writers

Hold shared and exclusive locks to the end, and watch waits and deadlocks grow with contention

For about 30 years, two-phase locking (2PL) was the main way to get serializability. Its rules:

  1. To read a row, take a shared lock. Many readers can share one.
  2. To write a row, take an exclusive lock. Nobody else may read or write it.
  3. If another transaction holds a conflicting lock, wait.
  4. Hold every lock until the transaction commits or aborts.

The two phases are taking locks while the transaction runs, then releasing all of them at the end. Readers now block writers, and writers block readers. Ana and Ben each take shared locks on both doctor rows, then each wants an exclusive lock on their own row. Each waits for the other: a deadlock. The database finds the cycle, aborts one, and the retry counts 1 doctor and stays.

Phantoms need more. A predicate lock covers every row that matches a condition, including rows not inserted yet. Checking predicates is slow, so engines lock a range of an index instead. That locks a bit more than needed but checks fast. InnoDB calls these next-key locks, and SQL Server's SERIALIZABLE places key-range locks.

How often does a transaction wait? Call the concurrent transactions n, the rows each locks k, and the rows they choose from R.

Say it aloud

P-wait is about n minus one times k squared, over two R.

Pwait
P-wait the chance that one transaction waits for a lock at least once. Valid while it is small.
n − 1
n minus one the other transactions running at the same time.
k2
k squared k lock requests, each facing about k/2 locks held per other transaction.
2R
two R R rows to choose from; the 2 comes from the half-finished average.
In plain words

A transaction caught half way holds about k/2 locks, so the n − 1 others hold about (n − 1) k/2 rows. Each of our k requests hits one of them with chance (n − 1) k / 2R. Add up the k requests.

With numbers

With made-up numbers: n = 16, k = 4, R = 1,000. P-wait ≈ 15 × 16 / 2,000 = 12%; our seeded clients waited 10.5% of the time. Shrink to R = 100 hot rows and the estimate passes 1: the clients waited 68%, and 4 deadlocks came per 100 commits.

Crowd the locks

The line is commits per tick against the number of clients; the dot is yours. The bars compare the seeded chance of waiting with the estimate. Add clients, then shrink the hot rows.

16

Illustrative and seeded: each client locks 4 random rows, one per tick, holds them to commit, then starts again. A deadlock aborts the youngest transaction in the cycle. 3,000 commits per point.

Failure. Symptom: latency spikes and "deadlock detected" errors when traffic grows. Measure: lock waits and deadlocks per second. Cause: long transactions holding locks on hot rows. Fix: shorter transactions, lock rows in one fixed order, spread hot rows, or move to SSI.

Under two-phase locking, Ana and Ben both read both doctor rows, then each writes their own row. What happens?

Chapter 8

Run on Snapshots, Check at the End

Let readers run without blocking, then abort the transactions whose reads went stale

Two-phase locking is pessimistic: it blocks anything that might go wrong. Serializable snapshot isolation (SSI) is optimistic: every transaction runs on its own snapshot, readers never wait for writers, and the database aborts the ones that could break serializability. Cahill, Röhm and Fekete published it at SIGMOD 2008. PostgreSQL's SERIALIZABLE has used it since version 9.1, described by Ports and Grittner in 2012.

The idea is the stale read. Ana's transaction counted 2 doctors. If Ben's write later changes what Ana counted, Ana decided on an old premise. SSI watches for that with two checks:

Each note is a read-write arrow from the reader to the writer: the reader must come first. Fekete and colleagues showed in 2005 that every non-serializable snapshot history has a pivot. A pivot has a read-write arrow in and another out, both to concurrent transactions. SSI aborts when a pivot forms. The doctors make one at once: Ana → Ben and Ben → Ana. One aborts with SQLSTATE 40001 and retries.

A pivot is a warning, not proof of a cycle. So SSI also aborts some transactions that would have been fine. PostgreSQL adds refinements that cut these false aborts. Ports and Grittner report performance only slightly below snapshot isolation, and well ahead of 2PL on read-heavy work.

Count what each engine pays

The same 300 transactions run on three engines. Red counts transactions caught in a cycle that slipped through; the bars count aborts and lock waiting. Shrink the table to raise the contention.

Illustrative and seeded: each transaction reads two random rows and writes one, with 1 ms per statement. Cycles come from the dependency graph of the snapshot run. Our SSI uses Cahill's basic pivot rule, without PostgreSQL's refinements, so it aborts more than PostgreSQL would.

The worked number, 20 rows. Snapshot isolation retries 84 transactions for write conflicts and still lets 4 cycles through, involving 8 transactions. SSI lets none through. It aborts 180: 105 for write conflicts and 75 for pivots. Two-phase locking lets none through, with 67 deadlock aborts and 175 ms of waiting. At 50 rows nothing slips through SI, yet SSI still aborts 10 for pivots: all false alarms.

Failure. Symptom: many "could not serialize access" errors after switching to SERIALIZABLE. Measure: aborts per commit, and which tables they name. Cause: long transactions that read wide ranges and overlap many writers. Fix: a retry loop for SQLSTATE 40001, shorter transactions, and declaring read-only transactions READ ONLY.

What makes SSI abort a transaction?

Chapter 9

Run the Roster

Push the load and the round trip, and see which engine stays correct and which stays fast

Back to the hero's hospital, with every knob. 30 shifts with 2 doctors each, 60 page-counter increments, and five engines. Every row runs the same seeded arrivals. Two questions: did the roster stay correct, and how long did each transaction take?

Run the roster on five engines

Each row is one engine. The bar is the mean time per transaction; the columns count empty shifts, lost increments and retries. Push the rate, then lengthen the round trip.

300
1.0 ms
2 ms

Illustrative and seeded, same engine as the hero. Latency runs from a transaction's arrival to its commit, retries and queueing included.

At the hero's settings of 300 a second and 1 ms round trips, read committed takes 2.1 ms per transaction. It leaves 23 shifts empty and loses 17 increments. Snapshot isolation keeps the counter with 32 retries but leaves the same 23 shifts empty. Two-phase locking (2.9 ms, 28 deadlocks), SSI (3.5 ms, 59 aborts) and serial execution (5.5 ms) keep everything.

Push to 500 a second. Serial execution's queue grows to 28 ms per transaction, because each transaction holds the thread for two 1 ms round trips. SSI takes 4.7 ms with 101 aborts; two-phase locking 3.8 ms with 55 deadlocks. Halve the round trip and serial execution drops to 1.9 ms: the round trip, not the work, sets its pace.

Spread a shift's two requests 20 ms apart and the weak levels look almost safe: 2 empty shifts instead of 23. That is the test that passes on Monday and fails on the busy Friday.

Failure. Symptom: an engine that tested correct and fast slows sharply or breaks a rule at the peak. Measure: replay peak load with realistic gaps between related requests. Cause: tests with low concurrency hide both the anomalies and the cost of preventing them. Fix: load test at peak rates, and choose the level per transaction.

Chapter 10

The Field Guide

Keep the numbers, the rules and the code for the next transaction you write

A transaction turns many writes into one, so a crash or an abort leaves nothing half done. Isolation decides what concurrent transactions see. Read committed stops dirty reads and writes; snapshots stop read skew. Lost updates need an atomic statement, a lock or a check, and write skew needs a lock on what the check read, or serializability. Serializability comes from one thread, from locks held to the end, or from snapshots with a check at commit.

Terms and numbers

IdeaRuleThis lesson's number
RacesPoverlap = 1 − e−2λd5 a second, 50 ms: 39.3%
Group commitX = b / tf2 ms flush: 500 a second alone; 16,000 with batches of 32
InterleavingsI = (m + n)! / (m! · n!)2 + 2 statements: 6, 2 mixed; 5 + 5: 252
Read skewE = λ · T / 330 a second, 10 s scan: 100 transfers seen half
Lost updatesread, modify, write loses250 a second: 68 of 100 kept; fixes keep 100
Serial threadX = 1 / (t + r · RTT)4 round trips: 488 a second; stored procedure: 20,000
PartitionsXP = P / (s((1 − f) + fP))8 partitions: 160,000; 10% cross: 94,118 at best
Lock waitsPwait ≈ (n − 1)k2 / 2R16 clients, 4 locks, 1,000 rows: 12% (seeded 10.5%)

Which level stops what

AnomalyRead committedSnapshotSerializable
Dirty read and writestoppedstoppedstopped
Read skewallowedstoppedstopped
Lost updateallowedPostgreSQL aborts one; InnoDB allows itstopped
Write skew, phantomsallowedallowedstopped

Checklist

  1. Know your database's default level: PostgreSQL and SQL Server use read committed, InnoDB repeatable read.
  2. Put related writes in one transaction, and keep it short.
  3. Run reports and backups in one snapshot.
  4. Write increments as one statement; otherwise lock the row or check its version.
  5. For a rule across rows, lock what the check reads, add a constraint, or use serializable.
  6. Retry on SQLSTATE 40001 and on deadlocks, with a limit and a little random delay.
  7. Make retries safe: a transaction that commits but loses its reply must not run twice. Store a request ID with the write.
  8. Load test at peak concurrency, with realistic gaps between related requests.

Beyond one machine

A transaction across two databases needs two-phase commit: a coordinator asks every participant to prepare, then tells all of them to commit. A participant that voted yes must wait, holding its locks, if the coordinator dies. Two-Phase Commit and When the Coordinator Dies simulate both. Exactly-once message processing is at-least-once delivery plus an idempotent write, such as the message ID stored in the same transaction; see The Outbox.

The core as code

pythonfrom math import exp, comb

def p_overlap(lam, d):                # bookings a second, seconds read-to-write
    return 1 - exp(-2 * lam * d)

def group_commit(batch, t_flush):       # durable commits a second
    return batch / t_flush

def read_skew(lam, t_scan):            # transfers a report sees half of
    return lam * t_scan / 3

def serial_rate(t, trips, rtt):        # one thread, seconds
    return 1 / (t + trips * rtt)

def partitioned(p, f, s):
    return p / (s * ((1 - f) + f * p))

def p_wait(n, k, rows):                 # two-phase locking, rough
    return (n - 1) * k * k / (2 * rows)

print(round(p_overlap(5, .05), 3), group_commit(32, .002), comb(4, 2))   # 0.393 16000.0 6
print(read_skew(30, 10), round(serial_rate(5e-5, 4, 5e-4)))            # 100.0 488
print(round(partitioned(8, .1, 5e-5)), p_wait(16, 4, 1000))            # 94118 0.12

# the retry loop every serializable client needs (psycopg)
def run(conn, work, tries=5):
    for i in range(tries):
        try:
            with conn.transaction():
                return work(conn)
        except psycopg.errors.SerializationFailure:
            time.sleep(random.uniform(0, 0.01) * 2 ** i)
    raise RuntimeError("gave up after retries")

Keep going

The takeaway. Name the rule your transaction protects, then pick the cheapest tool that enforces it: one statement, a lock on what you read, a constraint, or serializable with a retry loop.

Now press Present or Teach and explain four things from memory. Why does snapshot isolation stop read skew but not write skew? Why does FOR UPDATE fail against phantoms? Why does serial execution need stored procedures? What does SSI pay that two-phase locking does not? Then go back to the hero and find the cheapest engine that leaves no shift empty.

Database Transactions · following Designing Data-Intensive Applications, 2nd edition, Chapter 8
Previous: Sharding · Next: The Trouble with Distributed Systems · Back to Gleams