Move $100 from a database in US-East to one in EU-West, and one crash in the middle can lose it. Two-phase commit keeps all $1,000 but holds locks while it waits; a saga keeps it by undoing steps, and other readers see the gap.
Pick a protocol and a fault, then press Run. Watch the total, the locks and what other readers see. Then we build, piece by piece, the promises of one database, isolation, two-phase commit, sagas and the outbox.
You need a little SQL and what a round trip is. Consensus and Replication helps. We build the rest from zero.
Illustrative toy. Balances start at $500 each. In two-phase commit the coordinator crashes after it logs COMMIT and stays down an illustrative 30 s. Chapter 0 works the lost $100, Chapter 6 the crash, Chapter 7 the saga.
Chapter 0
Watch one crash lose $100 when a transfer spans two databases
Alice sends Bob $100. Alice's account lives in a database in US-East. Bob's account lives in a different database in EU-West. The transfer needs two writes: take 100 from Alice, then add 100 to Bob.
On one database this is easy. You wrap both writes in one transaction: a group of reads and writes that the database applies completely or not at all. Across two databases, no single engine owns both writes.
Now crash the app between the two writes. The debit has committed in US-East. The credit never reached EU-West. Alice has 400 and Bob has 500, so the bank holds $900 where it held $1,000.
The track shows the four steps; the red mark is the crash. Purple bars are the balances after the crash and any recovery. Move the crash, then switch between one database and two.
Illustrative. Steps: 1 begin, 2 debit Alice 100, 3 credit Bob 100, 4 commit. On one database a crash before step 4 rolls the whole transaction back.
Getting several independent databases to agree on one yes-or-no outcome is the atomic commit problem. A crash is not the only threat. Two transfers that run at the same time can both read Alice's 500 and both spend it. That is a problem of isolation, and it exists even on one machine.
This lesson builds both halves. First one database: what its promises mean, which concurrent mistakes each isolation level allows, and how snapshots work. Then many databases: two-phase commit, what happens when its coordinator dies, sagas, and the outbox.
Failure. Symptom: the sum of all balances drifts after crashes or deploys. Measure: a nightly job that sums every balance and compares it with the ledger. Cause: a change of several steps committed piece by piece. Fix: one transaction where the data shares a database; two-phase commit or a saga where it does not.
Chapter 1
Separate what each letter of ACID promises, and build atomicity from a log
ACID names four promises a database transaction makes. They are not equal, and two of them mean less than their names suggest.
Atomicity is all or nothing in the face of a crash. A better name is abortability: the database can throw away a half-done transaction. It says nothing about other transactions running at the same time.
Consistency means your rules hold: no negative balance, the same total money. The database cannot know those rules. It gives you constraints and atomicity, and your transaction code keeps the rule. So the C belongs to the application.
Isolation means concurrent transactions do not see each other's half-done work. Its strongest form, serializability, means the result equals some one-at-a-time order. Chapters 2 to 4 build it.
Durability means a committed transaction survives a crash. The database gets it from a write-ahead log (WAL). It appends each change to a log file, and it forces the log to disk before it says "committed".
The same log gives atomicity. After a crash, recovery reads the log. It redoes every change of a transaction whose commit record reached the disk, and it discards every change of a transaction without one.
Each row is one log record on disk. Green rows belong to a transaction whose commit record survived; pink rows recovery discards; grey rows never reached the disk. Move the crash.
Illustrative log. T1 moves $100 from A to B; T2 moves another $100. Each change record keeps the old and the new value, so recovery can undo or redo it.
The worked number: crash after record 6. T1's commit record sits at position 4, so recovery keeps A = 400 and B = 600. T2 wrote A = 300 at record 6 but never committed, so recovery discards it. The total stays 1,000.
Failure. Symptom: a write the client saw as committed is gone after a power cut. Measure: check whether the database acknowledges before the log reaches disk; PostgreSQL's synchronous_commit = off does this on purpose and can lose the last few commits. Cause: the commit record sat in a buffer that the crash erased. Fix: force the log before you acknowledge, and use group commit to share one disk flush among many transactions.
Chapter 2
Step through dirty reads, lost updates and write skew, and find the cycle each one leaves
Isolation failures are easiest to see as a schedule: the order in which two transactions' reads and writes interleave. Call the transactions T1 and T2. Five schedules cover the classic failures.
How do you tell a bad schedule from a harmless one? Draw a graph. Put one dot per committed transaction. Draw an arrow from Ti to Tj when Tj must come after Ti. That holds when Tj read what Ti wrote, overwrote what Ti wrote, or overwrote what Ti read. The last kind is a read-write arrow.
Blue chips are reads and writes in time order; the purple box is the committed data. Arrows between T1 and T2 appear as the schedule creates them: wr means it read the other's write, ww overwrote it, rw overwrote what the other read. Pick an anomaly, then step.
Illustrative schedules. The dirty read runs at read uncommitted; the other four run at read committed, the PostgreSQL default. The same engine fills the grid in Chapter 3.
Name the parts. Call the schedule of committed transactions H, for history. Call its graph of arrows G(H).
H is serializable if G of H has no cycle.
For each pair of operations on the same row, draw an arrow from the transaction that must come first. If the arrows never loop, sort the dots along them: that order is a serial order with the same result as H.
Lost update: T2 overwrote the 10 that T1 read, so T1 → T2. T1 overwrote the 10 that T2 read, so T2 → T1. That is a cycle of 2. Any serial order ends at 12, and this schedule ends at 11.
The dirty read is different. Its writer aborted, so the reader saw data from a transaction that never happened. Adya's 1999 thesis defines each isolation level by which of these graph patterns it forbids.
Failure. Symptom: two people hold the same meeting room. Measure: log reads and writes with transaction ids, and look for two transactions that each overwrote what the other read. Cause: write skew; each booking checked the rule against data the other was about to change. Fix: serializable isolation, a lock on the rows the check reads (SELECT … FOR UPDATE), or a unique constraint that states the rule.
Chapter 3
Run every anomaly under four isolation levels and see which one each level stops
An isolation level is a promise about which schedules the database may let through. A weaker level blocks and aborts less, so it runs faster when transactions collide. The SQL standard names four levels by the anomalies they forbid.
Berenson, Bernstein, Gray and colleagues showed in 1995 that the standard's wording is ambiguous, and they added snapshot isolation to the list. The device runs each schedule from Chapter 2 under four levels.
Each cell is one schedule run under one level: red means the anomaly happened, green means it did not. Choose a level and an anomaly to see the run below the grid.
Illustrative engine, close to PostgreSQL: snapshot isolation aborts the second updater of a row, and serializable adds a check for read-write cycles. The verdicts match Table 4 of Berenson et al. 1995 for the strict form of each anomaly.
Read the rows as a ladder. Read committed lets a read see only committed data, so dirty reads stop and the rest get through. Snapshot isolation gives each transaction one frozen view, so repeated reads and counts agree. It also aborts the second of two transactions that update the same row, so a lost update becomes an abort and a retry. Serializable catches write skew too.
The worked number: under snapshot isolation, T2's write of 11 fails with PostgreSQL's "could not serialize access due to concurrent update". The retry reads 11 and writes 12, the right answer.
| Database | Default level | What its levels are |
|---|---|---|
| PostgreSQL | Read committed | Read uncommitted acts as read committed; repeatable read is snapshot isolation; serializable is serializable snapshot isolation |
| MySQL InnoDB | Repeatable read | A plain SELECT reads a snapshot, but UPDATE and locking reads use the newest row, so the lost update above gets through |
Snapshot isolation is not the standard's repeatable read. A locking repeatable read stops write skew on the rows it read but lets phantoms in. Snapshot isolation does the opposite (Berenson et al., Remark 9).
Serializable has three common engines. In two-phase locking, readers lock what they read, so write skew becomes a deadlock. Serializable snapshot isolation watches read-write arrows and aborts a transaction when a dangerous pattern forms. The third runs transactions one at a time per partition.
Failure. Symptom: rare double charges or oversold stock that tests never show. Measure: the level each connection runs (SHOW transaction_isolation). Cause: read committed allows lost updates and write skew. Fix: raise the level for that transaction and retry on serialization errors (SQLSTATE 40001), or write the change as one statement such as SET c = c + 1.
UPDATE … SET balance = balance − 100. What happens?Chapter 4
Keep old versions so a reader sees one moment of the database without blocking writers
How does snapshot isolation give each transaction a frozen view without stopping writers? It never overwrites a row in place. Multi-version concurrency control (MVCC) keeps several versions of each row. Each version records the transaction that created it and the one that deleted it.
An update deletes the old version and creates a new one. A reader picks the version that was current at its snapshot. So readers never block writers, and writers never block readers.
Name the parts. A snapshot s records which transactions had committed at the moment the reader took it. Call that set Cs. For a version v, call its creator c(v) and its deleter d(v). A live version has no deleter.
v is visible to s if and only if c of v is in C-s and d of v is not in C-s.
For each version v, ask two questions. Had its creator c(v) committed when the reader took the snapshot? Had its deleter d(v) not committed yet? If both answers are yes, the reader sees v. Exactly one version passes.
T100 committed $500 at time 1. T201 replaced it with $400 and committed at time 6. A snapshot at time 5 has C-s = {T100}. The $500 version passes: T100 is in, T201 is not. The $400 version fails: T201 is not in. The reader sees $500.
The yellow line is the snapshot time. Warm bars are transactions, from start to commit. Purple boxes are versions of Alice's row; the green one is visible. Drag the snapshot.
Illustrative. Real engines add one more rule: a transaction always sees its own writes. PostgreSQL keeps these creator and deleter ids in every row header.
Old versions cost space. A version can go only when no running snapshot can still see it. PostgreSQL's VACUUM does this cleanup, and one transaction left open for hours keeps every version since it began.
Failure. Symptom: a table grows and scans slow down while the row count stays flat. Measure: the age of the oldest open transaction, and the dead versions per table. Cause: one long transaction pins old versions. Fix: end idle transactions with a timeout, and run long reports on a replica.
Chapter 5
Ask every database for a promise, then tell them all one decision
Back to the two databases. Neither may commit alone, and neither may wait forever for the other. Two-phase commit (2PC) adds a coordinator: a process that collects votes and records the decision. Each database is a participant.
A YES vote is a promise. After it votes YES, a participant may not abort on its own, even if it waits an hour. That promise makes 2PC correct, and it also makes 2PC block.
What does it cost? Call the round trip from the coordinator to its slowest participant rmax. Call the time a participant takes to force its log dp, and the coordinator's time dc.
T equals r-max plus d-p plus d-c.
The coordinator cannot decide until the slowest vote is back: that costs r-max plus d-p. Then it forces the decision, d-c. A participant's lock wait runs from PREPARE arriving to the decision arriving, and the two half-trips cancel, so it is the same T.
With illustrative numbers: the coordinator sits 2 ms from Alice's database and 80 ms from Bob's. Each log force takes 5 ms. T = 80 + 5 + 5 = 90 ms. Both rows stay locked 90 ms, even Alice's, 2 ms away.
Time runs down. Blue arrows are PREPARE and the decision, teal arrows are votes and acks, yellow ticks are log forces, and pink bars show locks a participant holds. Move the sliders.
Illustrative timings; the diagram draws two participants and the count changes only the messages. The near participant's round trip is fixed at 2 ms.
Count the messages too. Each participant gets one PREPARE, sends one vote, gets one decision and sends one acknowledgement: 4n messages for n participants, so 8 for our transfer. Gray and Lamport count 3N − 1 for the variant where one participant starts the protocol, without acknowledgements.
Failure. Symptom: tail latency on a busy row jumps when one region slows down. Measure: lock wait time per row, and the time from prepare to commit per participant. Cause: every participant holds its locks until the slowest one has voted. Fix: keep a transaction's participants in one region, or keep hot rows out of distributed transactions.
Chapter 6
Find the window where participants must wait, and count the requests that pile up
The coordinator is one process with one log. Where it crashes decides what the participants can do.
Under presumed abort, from IBM's R* system (Mohan, Lindsay and Obermarck, 1986), a restarted coordinator that finds no decision answers ABORT. That is safe, because it never tells anyone COMMIT before logging it.
While participants are in doubt, every request that needs a locked row waits. Call the rate of such requests λ and the coordinator's downtime D.
N equals lambda times D.
Requests keep arriving at rate lambda, and none of them can finish while the participants hold the locks. Multiply the rate by the downtime D to get the pile N. Each one waits, or times out and fails.
With illustrative numbers: 20 requests per second touch the locked rows, and the coordinator is down 30 s. N = 20 × 30 = 600 requests stuck. A replicated decision with a 2 s failover cuts it to 20 × 2 = 40.
The yellow bar is the downtime. Pink dots are requests stuck behind held locks. Pick the crash point, then turn on a replicated decision.
Illustrative. A participant that has not voted aborts after its own 1 s timeout. The replicated decision assumes an illustrative 2 s failover to a new leader.
Three repairs exist. In cooperative termination, an in-doubt participant asks the others. It learns the outcome if any of them saw the decision or never voted YES. If all are in doubt, it still waits. Three-phase commit (Skeen, 1981) adds a pre-commit round, but it avoids blocking only if the network never splits and timeouts never lie. Gray and Lamport wrote in 2006 that they knew of no such protocol with a complete, proven algorithm.
Their answer is Paxos Commit. It stores the decision on 2F + 1 acceptors instead of one log, so it keeps going while any F + 1 of them work. With F = 0 it is two-phase commit. With 5 participants and F = 1 it sends 17 messages where 2PC sends 12. Spanner does something similar: it runs 2PC between groups that each replicate their state with Paxos.
Failure. Symptom: rows stay locked after a coordinator outage, and prepared transactions pile up (pg_prepared_xacts in PostgreSQL). Measure: the count and age of prepared transactions. Cause: participants in doubt after the coordinator died. Fix: restart or fail over the coordinator with its log; never guess an outcome by hand without it.
Chapter 7
Commit each step locally, and run compensations in reverse when one fails
Two-phase commit keeps rows locked until the slowest participant answers. For a flow that spans services and minutes, such as booking a trip, that is too long. Garcia-Molina and Salem proposed the saga in 1987. A saga is a long transaction split into steps T1 to Tn, each a local transaction that commits at once.
Each step Ti has a compensating transaction Ci that undoes it in meaning. If a step fails, the saga runs the compensations of the steps that committed, newest first. Their guarantee: the system runs either T1 to Tn, or T1 to Tj followed by Cj back to C1.
Call the step that fails k, and the number of compensations it needs C.
C equals k minus one.
Steps 1 to k minus 1 committed, so each needs its compensation. Step k rolled back by itself. Run the C compensations from step k minus 1 back to step 1.
A trip saga: flight, hotel, car, charge card, send tickets. The bank declines the card at step k = 4. C = 4 − 1 = 3: cancel the car, then the hotel, then the flight.
Blue arrows run the steps forward. A red step failed. Teal arrows run the compensations back. Choose the failing step, then run the saga.
Illustrative saga. "Send tickets" comes last because an email cannot be unsent; if it fails, the saga retries it instead of undoing it.
A compensation is not a rollback. In the paper's airline example, C cancels a seat by subtracting one reservation. It cannot restore the old seat count, because other bookings ran in between. And a saga gives up isolation: other transactions see the partial work, and nothing tells them when a compensation runs.
Two styles run a saga. An orchestrator is one service that drives the steps as a state machine and logs each one. In choreography, each service reacts to the previous service's event, so no single log shows the whole flow.
Failure. Symptom: a customer sees a charge and a refund for an order that never shipped, or a seat that never frees. Measure: sagas stuck in a compensating state, and compensations that failed. Cause: a compensation that stopped after one error. Fix: make every compensation safe to run twice, retry it until it succeeds, and alert on sagas past their deadline.
Chapter 8
Write the event in the same local transaction, then deliver it at least once to a consumer that ignores repeats
Each saga step must change its database and tell the next service. That is two writes to two systems: the database and a message broker such as Kafka. Write the database first and crash, and the event is lost. Publish first and crash, and the event describes a change that never happened. This is the dual write problem.
The outbox pattern writes the event into an outbox table in the same local transaction as the change, so both commit or neither does. A separate relay reads unsent outbox rows, publishes them, then marks them sent. Change data capture tools such as Debezium read the database's log instead of polling the table.
The relay can crash after it publishes and before it marks the row. On restart it publishes the same event again. So the outbox gives at-least-once delivery, and the consumer must be idempotent: applying an event twice must equal applying it once.
Call the consumer's state s and the effect of one event f.
f of f of s equals f of s.
Apply the event to s once. Apply it again to the result. If you land on the same state, the consumer f is idempotent and a duplicate does no harm.
Stock is 10, and event ev-17 says "reserve 2". A naive consumer applies it twice: 10 − 2 − 2 = 6. A consumer that records ev-17 and skips ids it has seen gives 10 − 2 = 8 after one delivery and still 8 after two.
Purple rows are orders and outbox rows; a pink row is not yet sent. Blue dots are events. The consumer starts with 10 in stock, and each order reserves 2. Place orders, then break things.
Illustrative. Each crash toggle fires once, then turns itself off, as a real restart would. The consumer is correct when stock = 10 − 2 × orders.
The usual way to get idempotence is a processed-events table keyed by event id. The consumer updates it in the same local transaction as the effect, so a duplicate finds its id and does nothing.
Failure. Symptom: stock drops by twice the order, or a customer gets two emails. Measure: count deliveries per event id at the consumer. Cause: at-least-once delivery into a consumer that is not idempotent. Fix: skip seen event ids inside the consumer's own transaction.
Chapter 9
Fail any step, crash the orchestrator, and watch the order come out whole
An order runs as a saga of four steps: create the order, charge $50, reserve 2 items, schedule shipping. The orchestrator logs each step before it acts, and each service publishes through an outbox. Choose which steps fail, crash the orchestrator, and run.
The orchestrator's log fills on the left. Blue arrows are commands, teal arrows are replies and compensations, red marks a refused step. The bottom line is what other readers see.
Illustrative. Each step and each compensation is one command and one reply. After a crash, the orchestrator replays its log and sends step 3 again; inventory skips the repeat by its saga id.
Things to try:
The worked number: shipping refuses at step k = 4, so C = 3. Stock goes 10 → 8 → 10, and the card goes +$50 then −$50. The saga sends 4 steps and 3 compensations, each a command and a reply: 14 messages. With the crash, step 3 goes out twice: 16.
Failure. Symptom: an order sits in "compensating" for hours. Measure: sagas per state, and the age of the oldest. Cause: a compensation keeps failing, or the orchestrator lost its place. Fix: log every step before acting, replay the log on restart, and retry idempotent compensations until they succeed.
Chapter 10
Keep the numbers, the decision table and the code for the next write that spans two systems
One database gives atomicity and durability from its log, and isolation from locks or versions; most run below serializable by default. Across databases, two-phase commit gives true atomicity but holds locks for at least a round trip and blocks if its coordinator dies. A saga drops the locks, commits step by step, and undoes in reverse. The outbox carries each step's event at least once, and idempotent consumers make the repeats harmless.
| Term | What it is | This lesson's number |
|---|---|---|
| Lost $100 | two writes, crash between | 400 + 500 = 900 of 1,000 |
| WAL recovery | redo committed, discard the rest | crash after record 6: A 400, B 600 |
| Serializable | G(H) has no cycle | lost update: T1 → T2 → T1, ends 11 not 12 |
| Snapshot rule | c(v) ∈ Cs ∧ d(v) ∉ Cs | snapshot at 5 sees $500; at 7 sees $400 |
| 2PC time | T = rmax + dp + dc | 80 + 5 + 5 = 90 ms; 4n = 8 messages |
| Blocked pile | N = λ · D | 20 × 30 = 600; with failover 40 |
| Saga undo | C = k − 1 | card fails at 4: 3 compensations |
| Idempotent consumer | f(f(s)) = f(s) | stock 10: naive 6, deduped 8 |
| If you need | Use | What you pay |
|---|---|---|
| Several rows in one database | One local transaction | Pick the isolation level on purpose |
| Rules across rows (write skew) | Serializable, or lock what you read | Aborts to retry, or lock waits |
| Atomicity across databases you control | Two-phase commit (XA) | Locks held for T; blocks on coordinator loss |
| Non-blocking atomic commit | 2PC over replicated groups (Spanner), Paxos Commit | More messages and replicas |
| A long flow across services | Saga with an orchestrator | No isolation; a compensation per step |
| Reliable events from a service | Outbox, or change data capture | At-least-once; consumers must skip repeats |
PREPARE TRANSACTION and COMMIT PREPARED.python# two-phase commit, a saga runner and an idempotent consumer (sketches) def two_phase_commit(coord_log, participants, txn): votes = [p.prepare(txn) for p in participants] # each forces "prepared", keeps locks decision = "COMMIT" if all(votes) else "ABORT" coord_log.force(txn, decision) # the point of no return for p in participants: p.finish(txn, decision) # resent after a restart, from the log return decision def run_saga(saga_log, steps): # steps: [(do, undo), ...] done = [] for do, undo in steps: saga_log.append(("start", do.__name__)) if not do(): # the step's local txn rolled back for u in reversed(done): # C = k - 1 compensations retry_until_ok(u) return "compensated" done.append(undo) return "completed" def consume(db, event): # f(f(s)) == f(s) with db.transaction(): if db.seen(event.id): return db.mark_seen(event.id) db.apply(event)
Now press Present or Teach and explain five things from memory. Explain why the C in ACID is yours, why write skew leaves a cycle, and how a snapshot picks a version. Explain why a 2PC participant may not abort after YES, and why a saga needs k − 1 compensations. Then go back to the hero, crash the coordinator, and compare two-phase commit with the saga.