Key takeaways
- ✓A saga runs one local step at a time, each in its own database, and every step has a compensating undo: in the lab's order, reserve stock, charge the card, confirm; if the fraud check fails after the charge, refund the card, then release the stock.
- ✓With each step saved as one transaction together with its next message (the outbox), both sagas ended with 0 inconsistent orders out of 1,000, through 129 choreography crashes and 100 orchestration crashes, and their final states matched order for order. Two-phase commit also ended with 0, through 18 crashes.
- ✓Two-phase commit's zero had a price: 413 of its 1,000 orders got no answer while its coordinator restarted, and 12 customers saw an error for an order that was saved anyway. The sagas answered all 1,000 but left orders half-done for 10.4 s at the median, and an order cancelled later held its stock for 0.9 s at the median.
- ✓A dual write, which commits the change and then sends the next message as a second step, left 31 choreography orders and 33 orchestration orders stuck forever across 106 and 144 crashes. Four choreography orders and 13 orchestration orders still held stock, and 2 orchestration orders still held a customer's money.
- ✓In the same dual-write runs, the totals check found nothing: every product's stock and every account's balance still added up, because each change that was saved was correct. What was lost was the next message, so only the order-by-order check, which flags orders unfinished for more than 15 s, found the 64 stuck orders.
A saga places an order across three services, each with its own database, with a sequence of local steps and an undo for each. The lab in this chapter ran 1,000 orders per pattern, crashed the processes on purpose, and then checked every order. Both sagas ended with zero inconsistent orders when each step was saved as one transaction with its next message. A dual write, the simpler design that commits the change and then sends the next message, left 31 orders stuck forever while every total still added up. This chapter explains how a saga's steps and undos work, why a saga can leave an order stuck in the middle, and what reconciliation is for.
The examples come from Lab 13 (Distributed Transactions and Event Patterns) of the system design labs, scripts 02_failures.py (the failure test) and saga.py (the orchestrator's state table), with the reconciliation job in reconcile.py. The setup is the earlier chapters' laptop: an Apple M4 Max with Docker Desktop and 16 virtual CPUs, Postgres 17.11, Kafka 4.1.1, and three services (the orders service, inventory and payments), each with its own Postgres database, all in Docker. Each run is one recording, and the numbers below come from the lab's results file, 02_failures.json.
One order, three databases
Placing an order takes three things. Inventory reserves the stock. Payments charges the card. Orders runs a fraud check and confirms. No single transaction can span three databases, but the order must still end one of two ways: confirmed, with the stock reserved and the money taken; or rejected or cancelled, with nothing kept.
A saga makes this work with a chain of local steps, each committed in its own database, and a compensating step for each one that undoes its effect when a later step fails. The lab's chain is:
reserve stock → charge the card → confirm the order
↑ release stock ← refund the card ← (if the fraud check fails)
A compensation is new business logic, not a rollback. By the time the card is refused or the fraud check fails, the stock reservation has already been committed and other shoppers may have seen less stock. A refund is a new payment record that reverses the charge; the charge stays in the history. Think of a restaurant: the pantry sets the ingredients aside, the till takes the money, and if the order falls through, someone puts the ingredients back and gives the money back.
Each state in the lab's orchestrator (the saga's own coordinator, here inside the orders service) is named after what it is waiting for: RESERVING, CHARGING, REFUNDING and RELEASING. An unfinished order shows PENDING while the forward steps run and CANCELLING once a compensation has started. The lab's saga is an orchestrator, one coordinator that sends each command and moves to the next state when the reply comes back. In choreography, the other pattern in the test, no one is in charge: each service reacts to the others' messages, and the flow exists only as the sum of their handlers.
Pick what goes wrong
- 1order: PENDINGRESERVING · got StockReservedsends Charge
- 2order: CONFIRMEDCHARGING · got PaymentCapturedno command: the saga is over
Nothing to undo. The order is CONFIRMED with its stock reserved and the card charged.
PENDING and CANCELLING are the two statuses an unfinished order shows: CANCELLING means a compensation is running. In the dual-write runs, a crash can drop the next message in this chain, and the order then sits in PENDING or CANCELLING with nothing left to move it on.
Why a saga can leave an order stuck
A saga is a chain of messages, and each message is a handoff. If the handoff is lost, the chain stops, and nothing in the saga itself notices.
The lab's fix for that is one rule per step: the step's change, a record that its message was handled (the lab calls it processed), and the next message written to the outbox all happen in one database transaction, as Chapter 25 explains for the outbox. A crash before the commit undoes all three, so the message is simply delivered again. A crash after the commit leaves the change and the outbox row in place, so the next message is still sent. When a message arrives again, the processed row says it was handled, and the step is skipped. Doing a step twice changes nothing.
A dual write breaks that rule. It commits the change, and then, in a second step, sends the next message. A crash between the two loses the message. The change is saved, the handoff never happens, and when the original message is delivered again (it was never acknowledged), the processed row says the step is done and skips it. The next message is never sent. The order sits in PENDING or CANCELLING, forever, because nothing will ever move it on. That is why a dual write can leave an order stuck even though each individual change was correct.
Reconciliation: the check that finds what no step reported
Reconciliation is a batch job that reads all the systems and compares what they say. It does not trust the saga, because the saga is the thing that failed. The lab's reconcile.py runs two checks on the three databases after the system has settled.
- Totals. Every product's stock and every account's balance must equal its starting value minus what the active reservations and captured payments account for. A saved change that is wrong, or a missing one, shows up here.
- Order by order. For each order, the reservation and the payment must agree with the order's status. A CONFIRMED order must have its stock reserved and its payment captured; a REJECTED or CANCELLED order must hold no stock and no money, or have released and refunded them. An order that is still PENDING or CANCELLING is not yet a problem. It becomes stuck when it is older than the threshold, which the test sets to 15 seconds after nothing had changed for 15 seconds.
The totals check can't see a missing step, because a missing step leaves each saved change correct. The order-by-order check can. It is the last line of defense for every pattern in this lab, and it is the only one of the two that found anything in the dual-write runs.
The workflow and the results
The test sent 1,000 orders per pattern, at 50 a second for 20 seconds. Each order had a business outcome picked at random: 40% went through, and 20% each failed on purpose for being out of stock, a declined card, or a failed fraud check after the card was charged (which needs a refund). At every crash point, the process had a 2% chance of exiting on the spot, and it restarted within about a second. The crash points were before and after each step's commit, and after the relay (the process that copies outbox rows to Kafka) sent a batch; for two-phase commit, they were in its coordinator, after its prepare, after its decision, and between the two commits.
Exercise 1: with the outbox. Every step was one transaction with its outbox row, as above.
| Pattern | Orders sent | No answer | Orders that exist | Confirmed / rejected / cancelled | Crashes | Inconsistent orders | Stock or balances off |
|---|---|---|---|---|---|---|---|
| Two-phase commit | 1,000 | 413 | 599 | 238 / 113 / 248 | 18 | 0 | 0 |
| Choreography | 1,000 | 0 | 1,000 | 420 / 176 / 404 | 129 | 0 | 0 |
| Orchestration | 1,000 | 0 | 1,000 | 420 / 176 / 404 | 100 | 0 | 0 |
The two sagas got the same 1,000 orders and ended the same way, to the order. Their crashes were in the workers behind the queue, so the orders service never went down and answered every request. For a saga, the time from placing an order to its final state was 10.4 s at the median and 21.4 s at the 99th percentile in choreography, and 10.6 s and 21.2 s in orchestration. An order cancelled after its stock was reserved held that stock for 0.9 s at the median and 21.3 s at the 99th percentile (choreography). Without crashes, the same sagas finished in about 22 to 29 ms, the figure from Lab 1's happy-path runs in the same lab.
Two-phase commit had no half-done state for readers, because nobody saw an order until its commit. But its coordinator lived inside the orders service, and every one of its 18 crashes took the requests in flight with it. Of the 1,000 orders, 413 got no answer: 375 could not connect while the service restarted, and 38 were cut off mid-request. Of the 599 orders that exist, 587 got an answer, so 12 customers saw an error for an order that was saved anyway.
Exercise 2: the dual write. The same test, with each step committing and then sending its next message.
| Pattern | Orders that exist | Crashes | Crashes between commit and publish | Stuck orders | Stuck, holding stock | Stuck, holding money |
|---|---|---|---|---|---|---|
| Choreography | 643 | 106 | 19 | 31 | 4 | 0 |
| Orchestration | 762 | 144 | 18 | 33 | 13 | 2 |
Both runs had a totals check that found nothing: zero products and zero accounts off. The order-by-order check found 31 and 33 stuck orders, 64 in all, each one PENDING or CANCELLING and older than 15 seconds. The stuck orders held stock or money for orders that would never complete. The video's count from the crash log attributes about 17 and 12 of them to the orders service: it saved an order, crashed before announcing it, and the messages of other requests in flight went with it. The results file records 19 and 18 crashes between commit and publish in those runs. The rest came from worker crashes after a commit, where the next message was never sent and the redelivered message was skipped.
Crashes: 55 after a commit, 19 between commit and publish, 32 before a commit.
Totals: stock and balances add up
All add up
Every product's stock and every account's balance, against what the active orders hold. It found nothing in either run, because a dual write never lost a change, only the message after it.
Order by order: unfinished for over 15 s
31 stuck
Reads all three databases after nothing had changed for 15 s, then flags each order still PENDING or CANCELLING that was placed more than 15 s earlier.
376 of 1,000 callers got no answer, because the orders service crashed or was restarted for them.
Outbox run ends, for comparison: choreography 420 confirmed, 176 rejected, 404 cancelled; orchestration 420 / 176 / 404, the same orders to the order.
The price of consistency
Each design paid differently for its zero. Two-phase commit's zero came from prepare, commit and recovery, and it cost customers: its coordinator's restarts turned away 413 of 1,000 orders while they lasted. The sagas' zero came from one transaction per step, and it cost time: half-done orders for about 10 seconds at the median, and stock held for a second or more by orders that were later cancelled. The dual write cost the most, because it had no way to find the message it lost; its only defense was the order-by-order check, after the fact.
These numbers depend on how long a restart takes and how often crashes happen. In a real system, measure the same two things, the no-answer count and the half-done time, under your own failure rate.
Caveats
- One recorded run per pattern and design. The results come from single runs, so the exact counts (31 and 33, 413, 12) are the scale of the effect, not a rate with a confidence interval.
- Crashes are injected. Each crash is an exit at a chosen point with a 2% chance, followed by a restart within about a second. Real crashes, longer outages and a broken network were not tested.
- The lab reports stuck orders but does not repair them. No step has a timeout that resends its message or starts a compensation, so the stuck orders stayed stuck. The lab's own exercises suggest exactly that timeout, and a repair pass for reconciliation.
- Compensations never failed. A refund or release that itself fails, and has to be retried until it works, was not tested. The lab's checklist says compensations must be idempotent and must not fail for business reasons.
- The 15-second thresholds were one choice. The quiet period and the stuck age were not varied, so the 64 stuck orders depend on that setting. The 21 s 99th-percentile times are close to the 20 s sending window, so part of that number is the test's length.
- Coordinator placement. The 413 no-answer orders depend on the coordinator living inside the orders service. Moving it to its own process, which the lab suggests as an exercise, was not run.
- Shared laptop. Every service, broker and database ran on one machine, so the millisecond values are for the shape of the result.
The checklist
- Write each saga step as one transaction. The change, its "already done" record and its next message must commit together, or a crash will drop the handoff.
- Design the undo steps as carefully as the forward steps. A compensation runs after a real, committed change, so it must be idempotent, and it must be retried until it succeeds.
- Watch the half-done time. In the lab, an order sat in the middle of its saga for about 10 seconds at the median under crashes, and stock was held for about a second by orders later cancelled.
- Reconcile order by order, not only in totals. The totals were right in both dual-write runs, and the 64 stuck orders were found only by the check that reads each order's three records.
- Give stuck orders a rule. Reconciliation finds them; a timeout that resends the last message, or starts a compensation, is what moves them on.
Quiz
1.A saga's fraud check fails after the card was already charged. Which undo steps run?
2.In the dual-write run with choreography, 31 orders were stuck, and the totals check found nothing. Why did the totals still add up?
3.Two-phase commit's run reports 413 of 1,000 orders with no answer. What does that mean?
Check your understanding
Try each question before opening its answer.
A saga's fraud check fails after the card was charged. Why isn't the undo simply a rollback, and what does each undo do?
The charge was a committed payment in the payments database, and the stock reservation was committed in the inventory database. A rollback can't reach into committed changes, so the undo is new business logic. The card is refunded, which creates a refund record beside the charge, and then the stock is released. Both undos run in reverse order.
In the dual-write choreography run, 31 orders were stuck and the totals check found nothing. Why did the totals still add up?
Every change that was saved was correct: the stock was reserved, the payment was taken, and the balances matched what the orders held. What was lost was a message, the next step of the saga. Totals only check the amounts and counts, so a missing step doesn't change them. The order-by-order check is what found the 31, by comparing each order's status with its reservation and payment.
Why did the dual write leave orders stuck "forever" instead of just late?
After a crash between the commit and the publish, the next message is never sent, and nothing else will send it. When the original message is delivered again, the processed record says it was handled and the step is skipped, so the message is never resent. The order sits in PENDING or CANCELLING with no one to move it on. In the lab's runs, the stuck orders held stock for 4 and 13 orders and money for 0 and 2.
Two-phase commit ended with zero inconsistent orders. What did that zero cost?
Customers. The coordinator runs inside the orders service, so each restart turned away requests in flight: 413 of 1,000 orders got no answer, 375 because they couldn't connect and 38 because they were cut off. Twelve customers saw an error for an order that was saved anyway, because the order exists in the database even though the customer was told it failed.
Both sagas had zero inconsistent orders. What does the sagas' zero cost instead?
Time. Under the test's crashes, an order took about 10 seconds to finish at the median, and about 21 seconds at the 99th percentile. An order later cancelled held its stock for about 0.9 seconds at the median. Without crashes the same sagas finish in about 22 to 29 milliseconds, so the cost is the window during which the order is visibly in progress.
Next up: Chapter 31, event sourcing and CQRS, and changing an event's schema. Sagas keep the current state of an order and recover by moving it on; the next chapter keeps every event that happened, rebuilds the current state from them, and covers how an old event's shape changes without breaking the consumers that read it.