Systemsfor Aravinda
0 / 78 core
Week 5 · Messaging

The outbox pattern and sagas

2.5 hours · core path

Read first: Transactions and isolation, Queues and logs, Idempotency and the exactly-once myth

In one sitting

A crash between the database commit and the bus publish either loses the order or invents one that never committed. The transactional outbox writes the intent to publish in the same transaction as the business row, and the consumer still has to be idempotent because the publisher can send twice. Across order, payment, and inventory a saga is local transactions plus compensations, and the refund itself can fail.

The crash that hurts is the one between two systems that both think they might have succeeded. Your database and the bus are two systems. Order, inventory, and payment are three more. A single commit cannot cover them. You can still be precise about what is atomic, and you can still be honest about what is only a compensation.

Core concepts

The dual-write hole. The handler needs to do two things that do not share a transaction: commit a business row, and publish a message so another service can react. Order the two operations either way and a crash sits in the gap.

Commit the order, then publish. The process dies after the commit. The user got a success, or at least the row exists. The bus never hears about it. Inventory stays put. Payment never runs. Restarting the process does not retry, because the code path that publishes already finished in the only sense that matters: it is not running, and nothing recorded that it still needed to run.

Publish, then commit. The bus delivers OrderPlaced. The insert then rolls back on a conflict. Payment saw an order that does not exist and may have captured the card. There is no row to reconcile against unless the payment service is careful enough to notice the ghost.

Retries do not close this if the intent to retry is only in memory. A retry needs a durable record that the message is still owed. That record is the outbox.

The transactional outbox. In the same database transaction as the business row, insert an outbox row: an event id, a type, a payload, a status of unpublished. Commit. The fact “order 501 exists” and the fact “we owe the bus a message about 501” are now one Transactions and isolation outcome. You may return success to the caller after that commit. A publisher, a separate process, reads unpublished rows and puts them on the bus. This is a log or a queue in the sense of Queues and logs. The publisher then marks the row published.

The mark is a second write. If the publisher sends and dies before the mark, it will send again when it restarts. The hole where the message never existed is closed. The hole where the message exists twice is not. The consumer must still be idempotent. Idempotency and the exactly-once myth is the other half of the pattern, and Delivery guarantees is why: the publisher is an at-least-once producer by construction. An outbox without an idempotent consumer is a duplicate machine. A consumer that dedupes without an outbox still loses the crash where you never published.

Do not put the outbox in a second database “because the bus team owns publishing.” That reopens the hole between two commits. Do not mark the row published before the broker has accepted the record. A crash after the mark and before the publish looks like success and is a loss. The unpublished row is the intent. The published flag is a bookmark the publisher is allowed to move late.

A poller is the simple publisher. Assume it runs once a second, and say that this interval is a choice. A round trip in the same datacenter, on the teaching list, is about 0.5 ms, so a 1 second poll is about 2,000 of those round trips. The poll dominates the latency from commit to publish. A tail of the database’s own log can publish sooner and is more machinery. Either way the contract is the same: at least once, consumer dedupes, the row and the outbox committed together.

A saga is what you do when one transaction cannot reach the whole action. Garcia-Molina and Salem, in 1987, described a long-running business action as a sequence of local transactions, each with a compensating action, because there is no global rollback. Step 3 failing does not undo step 1 by magic. You run step 1’s compensation, which is a new forward action. A refund is not a charge that never happened. A restock is not a reserve that never happened. An email that left is gone. Compensations can fail too. The paper’s point, for this course, is the sequence and the missing global undo. The two ways teams structure that sequence now are choreography and orchestration.

Choreography means the steps are events. The order service commits its row and its outbox. Inventory subscribes, reserves a unit in its own database, and publishes InventoryReserved or InventoryRejected. Payment subscribes to the reserved event and captures, then publishes the result. The order service subscribes and marks the order confirmed or cancelled. No single process is the saga. The behavior is the set of subscriptions. Adding a step is adding a subscriber, which is genuinely convenient, and it is also how a cycle gets built by accident. The failure path is a second set of events. If nobody drew it, it does not exist. A lost InventoryReserved leaves a unit reserved until something times out. Every step needs a clock: a reservation TTL, or a timeout that starts a compensation. Without it, choreography waits forever and the stock screen is wrong.

Orchestration means a coordinator stores the saga’s state and tells each participant to run the next local transaction. The state machine is one row you can read when a page fires. The coordinator is another service that can crash, so its state has to be durable, and the commands it sends have to go through its own outbox. An orchestrator that updates a row and then calls payment over HTTP, with no outbox, has moved the dual-write hole into the coordinator and named it a saga. The coordinator does not hold a lock on inventory while it talks to the card network. If you need to keep a unit off the shelf during that call, that is a reservation with a timeout, a local decision inventory made, not a distributed lock.

Collapse it when you still have one database. If the order row and the inventory row live in one database, one transaction should reserve the unit and insert the order. A saga across tables that could have shared a commit is how you invent partial failure. The outbox is only justified when some other process must hear about the commit. The card network is not your database, so a charge is still a step outside the transaction even when everything else is local. Then the saga has one remote step, not three services. Split a database when a real boundary forces it. Do not split it to match a picture of three boxes.

Two-phase commit is the alternative people reach for because it sounds like one decision. It coordinates a commit across participants, and it blocks if the coordinator dies after they have prepared. The full sequence of that failure is below. The short version, which is enough to refuse it on a checkout path: prepared participants hold their locks and cannot safely finish on their own. A saga never enters that wait. Each local transaction has already committed or aborted. The price is the window where the world is only partly compensated.

A worked example

Order 501 is one hat. The price is 40. The inventory row for the hat shows 4 units. Payment will capture with an idempotency key of order-501, and a refund, if one is needed, will use order-501-refund. Those keys are chosen when the operation is created and stored. They are not minted again on a timeout.

Assumptions, all sketches:

  • 1 million orders a day.
  • Without an outbox, the publish fails after a successful commit on 0.05 percent of orders, and the commit fails after a successful publish on 0.05 percent. An illustration, not a measured error rate. The same fraction is applied to both orders of operations so you can see they are the same hole facing opposite directions.
  • 0.2 percent of orders capture a payment and then fail a later step, so they need a refund. An assumption.
  • Of those refunds, 1 percent still have no success after the bounded retries you allow. An assumption.
  • The publisher polls once a second. An assumption about this design.
  • A reservation lives 15 minutes if no later saga step arrives. A product rule you would write down, not a default.
orders per second
  1,000,000 / 86,400 = 11.6
  shortcut: 1,000,000 / 100,000 = 10

dual-write, 0.05 percent, either order of operations
  0.0005 * 1,000,000 = 500 orders a day

refunds after a capture, 0.2 percent
  0.002 * 1,000,000 = 2,000 a day

refunds still stuck after bounded retries, 1 percent of those
  0.01 * 2,000 = 20 a day

poll versus a datacenter round trip
  1 second / 0.0005 second = 2,000 round trips of delay

Five hundred ghosts a day is enough to staff a queue. Eleven orders a second felt too small to worry about. The fraction in the gap, not the QPS, is the incident rate. A day has 86,400 seconds, and the shortcut gets you to “about 10 a second,” which is the right size and the wrong tool for deciding whether 500 holes matter. They matter.

The outbox path for the happy order:

one transaction
  insert order 501, status pending
  insert outbox evt-501-placed, unpublished
commit
return success to the caller

publisher
  read evt-501-placed
  publish
  mark published

Crash after the commit and before the publisher runs: the row is unpublished, so the next poll sends it. The 500 lost publishes become lag, visible as outbox rows aging past your poll interval. Crash after publish and before the mark: the message goes out twice. Payment must treat evt-501-placed, or the order id, as a key it has seen. The second delivery returns the stored capture. It does not capture 40 again.

Now the saga, with three local transactions and one failure at the end. Happy path first, so the compensation has something to undo.

  1. Order service, one transaction: order 501 pending, outbox OrderPlaced.
  2. Inventory service, one transaction: hat count 4 becomes 3, outbox InventoryReserved. If the count is already 0, it publishes a rejection and reserves nothing.
  3. Payment service: capture 40 under key order-501, record charge ch_9, outbox PaymentCaptured. The call to the card network sits between recovery points. Record that you are about to capture, capture, record that you did. A timeout resumes. It does not create order-501-try-2.
  4. Order service: status confirmed.

Suppose step 4 cannot be finished. A migration holds the order row, the confirm transaction fails for longer than the saga is willing to wait, and the coordinator decides to abort. There is no global rollback. The charge exists. The hat is reserved. The order is not confirmed. Compensations run as new local transactions, and the order you run them in is part of the design.

The refund is the one that fails. The coordinator calls the refund under order-501-refund. The call times out. The card network may have refunded ch_9 and lost the response, or it may have done nothing. The saga row must say refund unknown, not refund failed, forget it. A retry uses the same key. If the first call had succeeded, the processor returns the stored refund and you mark the step done. If you generate a new key because the code treats a timeout as “start over,” the processor sees a second refund of 40. The customer receives 80 on a 40 hat. That is the compensation bug. It looks like a retry policy. It is a second payment operation.

Keys at the processor are a short-term tool, on the order of 24 hours in the published Stripe guidance. A saga stuck over a weekend cannot ask the processor “did we refund?” and treat a forgotten key as a no. Your saga row is the memory. The vendor cache is not.

Inventory’s compensation is the restock, 3 back to 4. If you restock while the refund is unknown, the hat can sell to someone else while customer 501 is still charged and has no order. You might still restock, because you are not going to ship, and keep the stuck state on the money rather than on the shelf. Say which resource you release and which one you hold. The window is visible either way: charged and unrefunded, or a unit held for a cancelled order. Hiding the window is how it becomes a support ticket with no row to point at.

Twenty of these a day, under the assumptions, is a queue a person can look at each morning. It is not a cosmic ray. Build the stuck-saga view before you build another subscriber. Each row shows order 501, charge ch_9, state compensating, step refund, attempt count, last error timeout. A human can retry the same key or can record a manual refund. What they must not have is a system that already minted a new key and moved on.

flowchart LR
  txn[One database transaction] --> orderRow[Order 501 pending]
  txn --> outboxRow[Outbox row unpublished]
  outboxRow --> publisher[Publisher]
  publisher --> bus[Bus]
  bus --> payment[Payment consumer]
flowchart TD
  placed[Order 501 placed] --> reserved[Hat reserved 4 to 3]
  reserved --> captured[Charge captured]
  captured --> refund[Refund with the same key]
  refund --> stuck[Refund timed out]
  stuck --> human[Reconciler shows the charge]

The first diagram is one database being honest. The second is three services after the charge has succeeded and the undo has not. Both can be true of the same checkout. The outbox gets the message out. The saga decides what to do when a later step refuses. Neither one makes the refund atomic with the original capture.

Choreography of this same failure is harder to read at 3am. Inventory reserved because it heard OrderPlaced. Payment captured because it heard InventoryReserved. The confirm failed, and now someone must publish a compensation event that both inventory and payment understand. If that event is lost, the hat stays at 3 and the charge stays captured, and no single row says “saga 501 is stuck.” You can add a timeout watcher, which is a coordinator you grew anyway. Orchestration starts with the row. Its cost is that you operate that coordinator, including its outbox. For a flow with a real failure path and money, the row is worth it. For a single optional side effect, a subscriber and an outbox are enough, and a coordinator is a service you do not yet need.

Retries, backoff, and circuit breakers bound the refund attempts. Bounded retries, backoff, jitter. When the budget is spent, the state stays stuck. An unbounded retry of a compensation that calls a dying processor is how the incident spreads. The stuck row is the successful outcome of a retry budget. It is not a crash of the saga framework.

Tradeoffs

Choice What you gain What you spend
Single database transaction All-or-nothing for every row it covers It cannot include the card network or a second service’s database
Dual-write, commit then publish Simple code on the happy path A crash drops the message. 500 silent orders a day under the sketch
Dual-write, publish then commit The bus hears about attempts quickly A rollback leaves a ghost event, and payment may capture for a missing order
Transactional outbox The intent to publish commits with the row A poll or a log tail, duplicate publishes, and consumers that must dedupe
Choreography No central waiter, a new subscriber is a new step The saga is not one row, lost events stall reservations, the failure path hides
Orchestration One state machine you can query and resume A coordinator to operate, and it needs its own durable outbox
Two-phase commit One commit decision across participants Blocks if the coordinator dies after prepare. Locks sit held

Five hundred lost orders against twenty stuck refunds is the tradeoff those labeled assumptions produce. The outbox moves the first number toward zero, measured as aging unpublished rows rather than as missing ones. The saga does not move the second number to zero. It gives the twenty a state, a key, and a person. If you needed zero, you needed the charge and the order in one system that can roll back, and you do not have that system.

Pitfalls

  • An outbox table in a different database from the order. Symptom: the order commits, the outbox commit fails, and you are back to 500 silent orders with a more complicated schema. Same transaction, same database.
  • Marking the outbox published before the broker accepts. Symptom: rows look drained, consumers never saw them, and a replay of the outbox will not help because you threw away the unpublished state. Mark after the accept, and accept duplicates.
  • A consumer that applies payment twice because “the outbox is transactional.” Symptom: two captures for order 501, both with different processor ids, because the publisher retried and the consumer treated the second message as new. The outbox transaction does not extend to the consumer. Dedup on the event id.
  • A compensation that mints a new idempotency key per attempt. Symptom: a timeout that had actually refunded, followed by a second refund. Store one key for the life of that compensation, and store the outcome yourself past the day or so the processor remembers keys.
  • Choreography with no timeout. Symptom: inventory stuck at 3 for an order nobody is confirming, forever, and no alert, because each service looks healthy. A reservation TTL or a saga timeout is part of the protocol.
  • An orchestrator that calls three services inside the web request and keeps the state in a local variable. Symptom: the process dies after the capture and there is no row that knows a refund is owed. That was a dual-write with extra network calls. The state row commits first.
  • A saga across three tables in one database. Symptom: orders that exist without inventory reservations, which a single transaction would have forbidden. Collapse the local work. Leave the saga at the boundary with the card network.
  • Unbounded refunds against a sick processor. Symptom: the compensation path becomes the incident. Bound the retries, then leave a stuck row.

In the interview

Say the atomic unit in the first five minutes. “The order row and the outbox row commit together. A publisher sends at least once. Payment dedupes on the order id. Inventory, payment, and the order confirmation are a saga: each step commits locally, and each has a compensation. I assume the refund can fail. The saga row stays in compensating until a retry with the same key succeeds or a person records what they did. If inventory and the order lived in one database, I would not saga those two. I would commit them in one transaction and saga only the charge.”

The number is the hole, not the average QPS. A million orders a day is about 12 a second. A twentieth of a percent of dual-writes failing is hundreds of broken orders a day. The bottleneck is the external call you cannot roll back, which is the card network, not the poller. The tradeoff: the outbox spends a bit of lag and a duplicate delivery to delete the lost-message hole, and the saga spends a visible partial state to avoid a lock that blocks when a coordinator dies.

Skip a framework. Skip a claim that the outbox is exactly-once. The question that follows is “what if the refund times out?” Same key, stored outcome, bounded retries, then a stuck row a human can see. If they ask about two-phase commit, give the prepare-and-die blocking story and say why you do not want those locks on a hat during a card-network call.

Check yourself

The order row commits and the process dies before it publishes. What is missing, and what does an outbox change about that crash?

The bus has no message, and nothing in the database says one is still owed, so a restart will not send it. The order exists and the rest of the system never hears. An outbox row inserted in the same transaction is the owed message. The publisher finds it on the next poll. The crash becomes delay, which you can see as an old unpublished row, rather than a silent skip.

The publisher sends the outbox row and crashes before marking it published. What must the consumer assume?

The restart will send the same event again. The consumer has to treat the second delivery as the same operation, keyed by the event id or the order id, and return the stored result. The outbox made the message durable. It did not make the consumer run once. At-least-once plus an idempotent handler is still the contract.

A refund of charge ch_9 times out, and the retry uses a newly generated idempotency key. What can the customer receive?

Eighty on a forty-dollar order, if the timed-out call had actually refunded and the new key starts a second refund. The processor is correct to honor both keys. They are different operations. One key, chosen before the first attempt and stored on the saga, makes the retry a resume. A forgotten key at the processor, which may be gone after about a day, is why the saga row has to remember the outcome too.

Order, inventory, and payment rows all live in one database you control. Why is a saga the wrong tool for those three writes?

One transaction can insert the order and reserve the unit together, so a crash cannot leave one without the other. A saga would replace that atomic commit with compensations you then have to operate. Use the transaction. Keep a saga, and an outbox, for the step that leaves the database, which is the card capture, if that capture is an external system.

The refund compensation has failed its retry budget. What state is the order in, and what do you show a person?

The order is not confirmed, the charge may or may not have been refunded, and the saga is stuck in compensating on the refund step. You show the order id, the charge id, the key you will keep using, the attempt count, and the last timeout. A person retries that same key or records a manual outcome. What you do not do is mark the saga complete and let the next tick invent a new refund.

Based on: Garcia-Molina and Salem, 1987; Designing Data-Intensive Applications, Kleppmann and Riccomini; Brandur Leach, Stripe idempotency.