Stage 5 · Architecture patterns · Hard · 18 min
Distributed transactions: outbox, CDC and sagas
Keep several services in step without one big transaction. Send events safely with an outbox, and run multi-step work as a saga that can undo its steps.
What each interview level is expected to know
Learn first: Transactions and isolation levels, Message queues and Kafka
After this lesson you can:
- Explain why one transaction across services is avoided.
- Publish an event safely with an outbox written in the same transaction.
- Run multi-step work as a saga, with an undo step for each part.
Start here
See it in 60 seconds
Outbox first, then a saga
An outbox saves a change and its message together; a saga runs steps across services and undoes them in reverse if one fails.
Scene 1 of 6 · Two writes, one risk
Saving an order and telling other services are two separate writes; a crash between them loses the message.
- Orders service — healthy
- Orders database — healthy
- Relay — healthy
- Message broker — healthy
- Two writes, one risk. Saving an order and telling other services are two separate writes; a crash between them loses the message.
- Save both together. So the order and an outbox row, the message to send, are saved in one database transaction.
- A relay sends it. A relay reads new outbox rows and publishes them, retrying until it works, so receivers must ignore repeats.
- A saga of steps. The order then runs as a saga: charge the card, reserve stock, book delivery, each in its own service.
- A late step fails. If the step "Book delivery" fails, nothing rolls back by itself, since no transaction spans the services.
- Undo in reverse. Instead the saga runs undo steps in reverse: release the stock, refund the card and cancel the order.
- Now you try. Pick which step fails, and see which undo steps run. For example: The step "Reserve stock" fails, so the saga must refund the card and cancel the order, in that order. Undo steps are new actions, such as a refund, not a rewind, so the customer may see the charge briefly.
Scene 1 of 6: Two writes, one risk. Saving an order and telling other services are two separate writes; a crash between them loses the message.
Key points
- Write the change and an outbox row in one local transaction, so both happen or neither does.
- A relay publishes outbox rows and retries, so receivers must safely ignore repeats.
- A saga is a chain of local steps across services, each with its own undo step.
- When a step fails, the saga runs the undo steps in reverse, such as a refund.
In plain words
Say the orders service saves a new order and must tell other services about it. Those are two writes. If it crashes after the first and before the second, the message is never sent. With an outbox, the service saves the order and a row holding the message in one database (A group of database changes that succeed or fail together: either all of them are saved, or none are.). A relay reads that row later and publishes it. The rest of the order is a saga of three steps, each in its own service. The card is charged, stock is reserved, and delivery is booked. If booking delivery fails, nothing rolls back on its own. The saga then undoes the finished steps, newest first: it releases the stock and refunds the card.
Why not one transaction across all three services? Two-phase (Making a change final. A committed database write counts and will not be undone. In Git, a commit is one saved set of code changes.) does that: a coordinator asks each service to lock its part, then tells all of them to commit. If the coordinator fails in between, the others stay blocked, still holding their locks. The outbox and the saga avoid that wait, at a cost. The relay may publish a message twice, so receivers must ignore repeats, and other services can see the order half done.
The problem it solves
Writing to your database and publishing an event are two separate actions. If the service crashes between them, the order exists but nobody hears about it. Or the event goes out for an order that was (Undoing a change to return to the last good state. A release rollback puts the previous version back. A transaction rollback cancels its writes.). Two-phase commit, a protocol where a coordinator makes every database commit together, avoids this. But the databases hold their locks while they wait, and they stay blocked if the coordinator fails.
Why it matters
An order that charges a card, reserves stock and books a delivery touches several services, each with its own database. No single database transaction can cover them all. The outbox and the saga are the usual answers, and interviewers ask where each one breaks.
A worked example
A checkout saga has 3 steps: charge the card, reserve stock, book delivery, each taking about 100 ms. All 3 succeeding takes about 3 × 100 = 300 ms. If the delivery step fails, the system undoes the reservation and the charge. That adds roughly 2 × 100 = 200 ms of undo work before the saga reports failure.
Think of it like…
Think of booking a trip with three companies: a flight, a hotel and a hire car. No single company can book all three for you. If the car falls through, you cancel the hotel, then the flight.
Where this analogy stops working
Separate steps, each with its own undo, is the useful part. But a cancel is not a rewind. It is a new action that can fail, and some steps cannot be undone at all, such as an email already sent. Between the steps, other people can also see the half-done booking.
Try it
See it working
Mechanics
How it works
The pictures follow one order, order 17, for $40. It touches three services: Orders, Payments and Stock.
Avoid a global transaction
Two-phase commit asks every service to prepare, then tells them all to commit. Each one holds its locks from the first message to the second. If the coordinator fails in between, they wait with their locks held. So most systems built from services avoid it.
Write an outbox row in the same transaction
Pick a case to follow belowWith this case: Order 17 was saved, but its event was lost in the crash. Payments never charged the $40.
Orders service, saves orders Orders service saves orders Orders database, orders, outbox, NOW Orders database orders, outbox order 17 NOW Relay, reads outbox Relay reads outbox Payments, charges cards Payments charges cards Broker, events Broker events - Orders service — saves orders — healthy
- Orders database — orders, outbox — healthy — NOW — order 17
- Relay — reads outbox — healthy
- Payments — charges cards — healthy
- Broker — events — healthy
- Local transaction
Step 1 of 3Step 1 of 3 · Orders database
Done: The order is saved
- What happens
- Orders saves order 17 for $40 and commits.
- Why
- This is a normal local transaction in the orders database.
- What changes
- Next the service must send an event to the broker.
- Next
- The Orders service crashes
Order 17 savedyesEvent saved or sentnoWatch: a message is owed$40 chargednoStep 1 of 3: Orders database. The order is saved. Orders saves order 17 for $40 and commits.
Save the business change and a row holding the event in one local transaction. Both commit, or neither does. So an event exists for every committed change, and for no change that was rolled back.
In the picture, the Orders service crashes right after it commits order 17. If it saves the order and sends the event as two separate actions, the event is lost. Payments then never charges the $40. With an outbox row in the same transaction, the relay finds the row after the crash and sends it.
Relay it to the broker
A relay publishes each outbox row to the message (A server that receives messages and passes them on to the services that read them. In Kafka, each broker stores some partitions and serves their reads and writes.). It can poll the table every second or so. Or change data capture (CDC) can read the database's own log of changes, with a tool such as Debezium. Delivery is (A delivery guarantee where a message may be processed more than once, but is never silently lost.), so consumers must be (Safe to repeat. Doing it twice has the same effect as doing it once.).
Split the workflow into a saga
Pick a case to follow belowWith this case: All three steps committed, so order 17 is confirmed and paid.
Orchestrator, runs the saga Orchestrator runs the saga Orders, own database, NOW Orders own database pending NOW Payments, undo: refund Payments undo: refund Stock, undo: release Stock undo: release - Orchestrator — runs the saga — healthy
- Orders — own database — healthy — NOW — pending
- Payments — undo: refund — healthy
- Stock — undo: release — healthy
- Saga step
Step 1 of 4Step 1 of 4 · Orders
Done: Orders saves order 17 as pending
- What happens
- The orchestrator starts the saga, and Orders commits order 17 for $40.
- Why
- Each step of a saga is a local transaction in one service.
- What changes
- The order waits for the other steps.
- Next
- Payments charges $40
Order 17pendingMoney taken$0ItemfreeStep 1 of 4: Orders. Orders saves order 17 as pending. The orchestrator starts the saga, and Orders commits order 17 for $40.
What these pictures simplify. These pictures follow one order through whole steps. A real relay can send an event twice, and a real undo action can fail and must be retried. Other requests can also see the steps in between. The outbox and saga lab runs the same ideas with timing.
A saga is a chain of local transactions, one per service. Each step has an undo action, called a compensating action: charge the card and refund it, reserve stock and release it. If a step fails, the saga runs the undo actions of the finished steps in reverse order.
In the picture, an (A program that decides which machine runs each container, and keeps the number of copies you asked for running.) runs three steps for order 17: save it as pending, charge $40, then reserve the item. When Stock has none left, the saga refunds the $40 and then cancels the order, newest first. For a short time the customer was charged, because a saga does not hide the steps in between.
Orchestrate or choreograph
With an orchestrator, one service tells each of the others what to do next. That is easier to follow and debug. With choreography, each service reacts to the others' events, with nobody in charge. The services depend on each other less, but the whole flow is harder to trace.
Use it when
- A service that saves a change and must tell others about it: with an outbox, the event is sent whenever the change commits.
- A copy of the data in another system, such as a search (An extra structure, kept sorted or grouped, that lets a database find matching items without reading all of them.) or a (A small, fast store that keeps copies of popular data, so most reads skip the slower database.): CDC keeps it in step with the main database.
- A business process that crosses several services, such as checkout: a saga gives each step an undo action.
- A process that calls outside companies, such as booking a flight and a hotel: no shared transaction is possible, so plan the undo steps.
Skip it when
- All the tables are in one database: an ordinary transaction already keeps them together, with far less to build.
- A step that cannot be undone, such as sending an email or shipping a parcel: put it last, after every step that can fail.
- Two services that always change together: they may be one service split too early. Merging them removes the saga.
Check yourself
Also
More in 60 seconds
A ledger where every payment sums to zero
A ledger is a list of money rows that is only ever added to; each payment writes two rows that add up to zero.
Scene 1 of 6 · Two rows per payment
Alice pays the shop $30, so the ledger writes two rows: Alice -30 and Shop +30.
- Payment service — healthy
- Ledger — healthy
- Card company report — healthy
- Nightly check — healthy
| Payment | Account | Change ($) |
|---|---|---|
| pay-1 (highlighted) | Alice | -30 |
| pay-1 (highlighted) | Shop | +30 |
- Sum of all rows ($)
- not shown yet
- Problems found
- not shown yet
- Two rows per payment. Alice pays the shop $30, so the ledger writes two rows: Alice -30 and Shop +30.
- Each payment sums to zero. Bob and Cara pay too, and each payment's two rows add up to zero.
- Balances come from rows. The shop's balance is the sum of its rows, +60, so every cent can be traced to a payment.
- A row goes missing. A bug, or a write split across two services, saves Shop +20 but not Bob -20.
- The nightly check. Each night a job adds up every payment and matches the ledger against the card company's report.
- Fix with a new row. It never edits old rows; it adds a correcting row, so the full history stays.
- Now you try. Both rows of a payment go in one transaction. Pick what a bug loses anyway, and see which check finds it. For example: The rows sum to zero. The check finds that pay-3 is on the card report but not in the ledger. A whole missing payment leaves the sum at zero, so only matching an outside report finds it.
Scene 1 of 6: Two rows per payment. Alice pays the shop $30, so the ledger writes two rows: Alice -30 and Shop +30.
Key points
- Every payment writes two rows: money out of one account, into another.
- Each payment's rows sum to zero, so money is moved, never made.
- A balance is the sum of an account's rows, so every cent has a reason.
- Mistakes are fixed with new rows; old rows are never edited.
Judgement
Trade-offs and how it fails
What you give up
- Availability
- Each service commits on its own and holds no lock while it waits for another service. One slow or failed service delays that saga, but the other services keep serving their own requests.
- Isolation
- A saga has no isolation between its steps. Other requests can see the half-done state: a card charged for an order that is later cancelled. The design must say what users see in between, such as "order pending".
- Atomicity
- With an outbox, the event is saved in the same database transaction as the data change. So the event is recorded whenever the change commits, and no lock is held across services.
- Delivery
- Delivery is at-least-once: after a crash, the relay may send an event twice. So each consumer must be idempotent, which means a repeat has no extra effect.
Failure modes
- The outbox table keeps growing: nobody deletes rows that were already sent. The table reaches millions of rows, and the relay's queries slow down. Delete or archive sent rows.
- Duplicate messages: the relay publishes an event and crashes before it records that it did. After the restart it sends the event again.
- An undo step fails: the refund is rejected or the service is down. The saga must keep retrying it, and alert a person if it still fails.
- Choreography nobody can follow: many services react to each other's events, and no single place shows the whole flow. Events can even loop. Past a few steps, an orchestrator is easier to reason about.
- Out-of-order events: the relay publishes rows in parallel, and "order cancelled" reaches a consumer before "order placed". Publish each order's events in sequence.
In the real world
- Chris Richardson's pattern catalogue at microservices.io describes the transactional outbox. It gives two ways to relay it: polling the table, or reading the transaction log.
- Debezium is an open-source tool that reads the MySQL binlog or the PostgreSQL log and publishes each change to Kafka.
- Uber built Cadence, a workflow engine that runs long multi-step processes. Temporal grew out of it.
- AWS Step Functions is a managed orchestrator: you describe the steps and their undo actions, and it runs them.
- The saga comes from a 1987 paper by Hector Garcia-Molina and Kenneth Salem on long-running database transactions. Source: Garcia-Molina and Salem, "Sagas" (1987) (checked 14 October 2026)
Trade-offs to be ready to discuss: Outbox vs dual write · Orchestration vs choreography
Check yourself
Interview
What interviewers look for
- Name the problem first: "Saving to the database and publishing an event are two writes, and a crash between them loses one." This is the dual-write problem.
- Say what the relay promises: "It delivers at least once, so each consumer skips an event id it has already handled."
- For a saga, give each step with its undo: "Charge and refund. Reserve and release." Then say what the user sees in between, such as "order pending".
- Pick a style and give the reason: "An orchestrator, because one place then shows where each order stands."
Say it out loud: Why isn't it enough for a service to update its database and then publish an event?
Expected depth by interview level
Levels describe the depth interviewers probe, not years of experience. Choose a level on the learning path to highlight it.
- JuniorBeyond this level
- Not usually expected.
- MidUseful
- Why one database transaction does not normally span several services.
- SeniorCore
- Outbox, change data capture and sagas with compensation.
- StaffCore
- Consistency guarantees across service boundaries.
Practice
Apply it
Three harder questions
The first two use the idea on a new case. The last asks you to judge a design.
Apply it
Apply it
Judge a design
Go deeper
Sources and further reading
First-hand sources to check this page against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Research paperSagas (1987)Garcia-Molina and Salem, ACM SIGMODThe original idea: a long transaction as steps, each with an action that undoes it.
- Engineering guidePattern: Transactional outboxmicroservices.io (Chris Richardson)Writing the event in the same database transaction as the change, then sending it.
- Official docsDebezium documentationDebeziumChange data capture: reading a database’s log to publish every row change.