Distributed Transactions

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.

Move $100 across two databases

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

The Money Problem

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.

Crash the transfer

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.

2

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.

  1. ACID: four promises, and the log that keeps two of them.
  2. Anomalies: five schedules that break, and the cycle each leaves.
  3. Isolation levels: every anomaly run under four levels.
  4. Snapshots: row versions that let readers and writers pass.
  5. Two-phase commit: collect promises, then decide.
  6. Coordinator crash: the in-doubt window and its repairs.
  7. Sagas: commit each step, undo in reverse on failure.
  8. Outbox: never lose the event, never apply it twice.
  9. Showcase: a saga orchestrator you can break.
  10. The field guide: numbers, decisions, code and links.
Alice and Bob each hold $500 on separate databases. The app debits Alice $100, then crashes before it credits Bob. There is no protocol. How much money does the bank hold?

Chapter 1

Four Promises

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.

Crash a write-ahead log

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.

6

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.

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

Chapter 2

Five Ways Concurrency Breaks

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.

Step a schedule

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

Say it aloud

H is serializable if G of H has no cycle.

H
H the history: every read, write and commit of the committed transactions, in the order they ran.
⇐
if the right side is enough to make the left side true.
G(H)
G of H the dependency graph: one dot per transaction, one arrow per "must come after".
no cycle
no cycle no path of arrows that leads back to where it started.
In plain words

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.

With numbers

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.

Two transactions each read "2 doctors on call", and each sets a different doctor off call. Both commit. Which anomaly is it, and what does the graph show?

Chapter 3

The Isolation Menu

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.

Run the grid

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.

DatabaseDefault levelWhat its levels are
PostgreSQLRead committedRead uncommitted acts as read committed; repeatable read is snapshot isolation; serializable is serializable snapshot isolation
MySQL InnoDBRepeatable readA 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.

PostgreSQL at read committed. Two calls each read a balance of 150, check that it is at least 100, then run UPDATE … SET balance = balance − 100. What happens?

Chapter 4

Snapshots and Versions

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.

Say it aloud

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.

v visible to s
v visible to s the reader with snapshot s sees this version of the row.
⇔
if and only if both sides are true together or false together.
c(v)
c of v the transaction that created version v.
∈
is in belongs to the set.
Cs
C-s the transactions that had committed when the reader took snapshot s.
∧
and both conditions must hold.
d(v)
d of v the transaction that deleted or replaced v; none if v is live.
∉
is not in does not belong to the set. "None" is never in it.
In plain words

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.

With numbers

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.

Move the snapshot

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.

5

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.

T100 commits $500 at time 1, T201 commits $400 at time 6, T202 commits $350 at time 9. What does a snapshot taken at time 7 see?

Chapter 5

Two-Phase Commit

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.

  1. Prepare. The coordinator sends PREPARE to each participant. Each one writes its changes and a "prepared" record to its log, keeps its locks, and votes YES or NO.
  2. Decide. All YES means COMMIT; any NO means ABORT. The coordinator forces the decision to its own log.
  3. Tell. The coordinator sends the decision. Each participant applies it, releases its locks and acknowledges.

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.

Say it aloud

T equals r-max plus d-p plus d-c.

T
T the time from sending PREPARE until the decision is safe on disk, in milliseconds. Each participant also holds its locks this long after PREPARE arrives.
rmax
r-max the round trip between the coordinator and its slowest participant.
dp
d-p the time a participant takes to force its prepared record to disk.
dc
d-c the time the coordinator takes to force its decision to disk.
In plain words

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 numbers

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 one commit

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.

80 ms
5 ms

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.

A participant has voted YES. Then it notices its disk is nearly full and wants to abort. May it?

Chapter 6

When the Coordinator Dies

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.

Say it aloud

N equals lambda times D.

N
N the requests that pile up behind the held locks during the outage.
λ
lambda the arrival rate of requests that touch the locked rows, per second.
·
times multiply.
D
D how long the participants stay in doubt, in seconds: the coordinator's downtime.
In plain words

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 numbers

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.

Crash the coordinator

The yellow bar is the downtime. Pink dots are requests stuck behind held locks. Pick the crash point, then turn on a replicated decision.

20
30 s

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.

The coordinator logs COMMIT, then crashes before it tells anyone. What does it do when it restarts?

Chapter 7

Sagas: Undo Instead of Lock

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.

Say it aloud

C equals k minus one.

C
C how many compensating transactions run.
k
k the position of the step that fails, counting from 1.
− 1
minus one the failed step itself: its local transaction rolled back, so it needs no undo.
In plain words

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.

With numbers

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.

Fail a step

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.

A saga has 5 steps. Step 4 fails. How many compensating transactions run, and in what order?

Chapter 8

The Outbox

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.

Say it aloud

f of f of s equals f of s.

s
s the consumer's state before the event: here, the stock count and the set of event ids it has seen.
f( )
f of apply the event once.
f(s)
f of s the state after one delivery.
f(f(s))
f of f of s the state after the same event arrives a second time.
In plain words

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.

With numbers

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.

Lose or repeat an event

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.

The relay publishes an event, then crashes before it marks the outbox row as sent. What happens when it restarts?

Chapter 9

A Live Saga Orchestrator

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.

Run an order saga

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:

  1. Let shipping refuse. Watch three compensations run: release the stock, refund $50, cancel the order.
  2. Let payment refuse instead. Only the order needs cancelling, so one compensation runs.
  3. Turn on the crash with nothing refusing. The orchestrator restarts, sends step 3 again, and inventory reserves only once.
  4. Watch the bottom line during a run: for a while other readers see stock 8 and a $50 charge on an order that later cancels.

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.

The orchestrator crashes after sending "reserve 2 items" and restarts. It replays its log and sends the command again. What keeps the stock right?

Chapter 10

The Field Guide

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.

Terms and numbers

TermWhat it isThis lesson's number
Lost $100two writes, crash between400 + 500 = 900 of 1,000
WAL recoveryredo committed, discard the restcrash after record 6: A 400, B 600
SerializableG(H) has no cyclelost update: T1 → T2 → T1, ends 11 not 12
Snapshot rulec(v) ∈ Cs ∧ d(v) ∉ Cssnapshot at 5 sees $500; at 7 sees $400
2PC timeT = rmax + dp + dc80 + 5 + 5 = 90 ms; 4n = 8 messages
Blocked pileN = λ · D20 × 30 = 600; with failover 40
Saga undoC = k − 1card fails at 4: 3 compensations
Idempotent consumerf(f(s)) = f(s)stock 10: naive 6, deduped 8

Which tool for which job

If you needUseWhat you pay
Several rows in one databaseOne local transactionPick the isolation level on purpose
Rules across rows (write skew)Serializable, or lock what you readAborts to retry, or lock waits
Atomicity across databases you controlTwo-phase commit (XA)Locks held for T; blocks on coordinator loss
Non-blocking atomic commit2PC over replicated groups (Spanner), Paxos CommitMore messages and replicas
A long flow across servicesSaga with an orchestratorNo isolation; a compensation per step
Reliable events from a serviceOutbox, or change data captureAt-least-once; consumers must skip repeats

In production

Checklist

  1. Draw the service boundaries so that rows that change together share a database.
  2. Write down each rule (no negative balance, one doctor on call) and the isolation level that protects it.
  3. Retry every transaction that fails with a serialization error.
  4. If you use 2PC, replicate the coordinator's log and alert on old prepared transactions.
  5. For a saga, give every step a compensation, put irreversible steps last, and log each step before acting.
  6. Publish through an outbox, and give every event an id that consumers record.

The core as code

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)

Keep going

The takeaway. Keep data that must change together in one database, and pick its isolation level on purpose. When a change must span databases, choose your price: two-phase commit pays in held locks and blocking, a saga pays in visible half-done states and compensations.

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.

Distributed Transactions
Isolation Levels 1995 · Paxos Commit 2006 · Sagas 1987 · Back to Gleams