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 serviceOrders serviceOrders databaseOrders databaseRelayRelayMessage brokerMessage broker
  • Orders service — healthy
  • Orders database — healthy
  • Relay — healthy
  • Message broker — healthy
  1. Two writes, one risk. Saving an order and telling other services are two separate writes; a crash between them loses the message.
  2. Save both together. So the order and an outbox row, the message to send, are saved in one database transaction.
  3. A relay sends it. A relay reads new outbox rows and publishes them, retrying until it works, so receivers must ignore repeats.
  4. A saga of steps. The order then runs as a saga: charge the card, reserve stock, book delivery, each in its own service.
  5. A late step fails. If the step "Book delivery" fails, nothing rolls back by itself, since no transaction spans the services.
  6. Undo in reverse. Instead the saga runs undo steps in reverse: release the stock, refund the card and cancel the order.
  7. 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

  1. Write the change and an outbox row in one local transaction, so both happen or neither does.
  2. A relay publishes outbox rows and retries, so receivers must safely ignore repeats.
  3. A saga is a chain of local steps across services, each with its own undo step.
  4. When a step fails, the saga runs the undo steps in reverse, such as a refund.

Go deeper in the Transactional outbox & saga lab →

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

Guided walkthroughOpen the full lab →

Transactional outbox & saga

Save an order and its message in one transaction, so a crash cannot leave an order with no message. Then run the order as a saga, and undo the finished steps when a later one fails.

Save an order and tell Payments

The Orders service saves order 17 for $40, and Payments must hear about it to charge the card. Pick how the order is saved and where a crash lands, then press Next step.

How the order is saved
Where a crash lands

With these settings: The order and its event committed together, so the crash lost nothing. Payments charged the $40 once.

Orders service, saves ordersOrders servicesaves ordersOrders database, orders, outbox, NOWOrders databaseorders, outboxorder + outbox rowNOWRelay, reads outboxRelayreads outboxPayments, charges cardsPaymentscharges cardsBroker, eventsBrokerevents
  • Orders service — saves orders — healthy
  • Orders database — orders, outbox — healthy — NOW — order + outbox row
  • Relay — reads outbox — healthy
  • Payments — charges cards — healthy
  • Broker — events — healthy
  • Local transaction
  • Outbox row
  • OrderPlaced event
Step 1 of 6

Step 1 of 6 · Orders database

Done: The order and an outbox row commit together

What happens
Orders saves order 17 for $40 and an OrderPlaced row, in one local transaction.
Why
One transaction means both rows commit, or neither does.
Next
The Orders service crashes

Event log

5 more to go. Press a line to go back to that step.

Order 17 saved
yes
Outbox row
not sent
Times the event was sent
0
Times $40 was charged
0

Step 1 of 6: Orders database. The order and an outbox row commit together. Orders saves order 17 for $40 and an OrderPlaced row, in one local transaction.

What this simplifies. This follows one order through whole steps. A real relay reads many rows at a time, and how often it checks the table is a setting. Payments keeps its list of handled event ids in its own database.

Step through one saga

One order needs three services, each with its own database. Pick which one fails, then press Next step. Back takes you to the step before.

Which step fails?

On: the order service has to ask for the refund twice.

With these settings: Cancelled and undone. The one finished step was compensated, newest first, so no service is left holding half an order.

CustomerCustomerOrder service, runs the saga, NOWOrder serviceruns the sagaORD-200: pendingNOWPayment service, its own databasePayment serviceits own databaseInventory service, its own databaseInventory serviceits own databaseShipping service, its own databaseShipping serviceits own database
  • Customer — healthy
  • Order service — runs the saga — healthy — NOW — ORD-200: pending
  • Payment service — its own database — healthy
  • Inventory service — its own database — healthy
  • Shipping service — its own database — healthy
  • Do a step
  • Failed or refused
  • Undo a step (compensation)
Step 1 of 6

Step 1 of 6 · Order service

Done: The customer places an order

What happens
The customer orders one jacket for $120. The order service saves the order as pending and starts the saga.
Why
Three other services each keep their own database. No single transaction can cover all of them, so the work is done as a chain of local steps.
What changes
Order ORD-200 is saved with the status pending.
Next
The payment service commits: charged $120

Event log

5 more to go. Press a line to go back to that step.

Order status
pending
Steps committed
0
Steps undone
0
Held from the customer
$0

Step 1 of 6: Order service. The customer places an order. The customer orders one jacket for $120. The order service saves the order as pending and starts the saga.

What this simplifies. This is one order with no other requests beside it, and a failure is a setting, not chance. Here the order service calls each service and waits. Real sagas often pass these steps as messages through a queue, and store the saga's own progress so it can carry on after a crash. A real compensation can also fail for good, and then a person has to step in.

Two-phase commit: the alternative to a saga

One order must charge $30 and reserve a shoe in two databases, all or nothing. Step through how two-phase commit does it, and what happens when the coordinator fails.

Scenario
Order service, workingOrder serviceworkingorder 42Payments DB, workingPayments DBworkingcharge $30, not finalInventory DB, workingInventory DBworkingreserve 1 shoe, not final
  • Order service — working — healthy — order 42
  • Payments DB — working — healthy — charge $30, not final
  • Inventory DB — working — healthy — reserve 1 shoe, not final

Step 1 of 7: Begin.

The order service is the coordinator: it runs one transaction that must charge $30 in Payments and reserve one shoe in Inventory.

Locks held. Payments: yes. Inventory: yes. Other orders that need a locked row must wait.

Also try: Kafka: partitions, replication & delivery

Mechanics

How it works

The pictures follow one order, order 17, for $40. It touches three services: Orders, Payments and Stock.

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

  2. Write an outbox row in the same transaction

    Pick a case to follow below

    With this case: Order 17 was saved, but its event was lost in the crash. Payments never charged the $40.

    Orders service, saves ordersOrders servicesaves ordersOrders database, orders, outbox, NOWOrders databaseorders, outboxorder 17NOWRelay, reads outboxRelayreads outboxPayments, charges cardsPaymentscharges cardsBroker, eventsBrokerevents
    • 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 3

    Step 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 saved
    yes
    Event saved or sent
    no
    Watch: a message is owed
    $40 charged
    no

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

  3. Relay it to the broker

    A relay publishes each outbox row to the message . 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 , so consumers must be .

  4. Split the workflow into a saga

    Pick a case to follow below

    With this case: All three steps committed, so order 17 is confirmed and paid.

    Orchestrator, runs the sagaOrchestratorruns the sagaOrders, own database, NOWOrdersown databasependingNOWPayments, undo: refundPaymentsundo: refundStock, undo: releaseStockundo: 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 4

    Step 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 17
    pending
    Money taken
    $0
    Item
    free

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

  5. 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 or a : 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

What does a saga do when step 3 of 4 fails?

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 servicePayment serviceLedgerLedgerCard company reportCard company reportNightly checkNightly check
  • Payment service — healthy
  • Ledger — healthy
  • Card company report — healthy
  • Nightly check — healthy
Ledger rows
PaymentAccountChange ($)
pay-1 (highlighted)Alice-30
pay-1 (highlighted)Shop+30
Sum of all rows ($)
not shown yet
Problems found
not shown yet
  1. Two rows per payment. Alice pays the shop $30, so the ledger writes two rows: Alice -30 and Shop +30.
  2. Each payment sums to zero. Bob and Cara pay too, and each payment's two rows add up to zero.
  3. Balances come from rows. The shop's balance is the sum of its rows, +60, so every cent can be traced to a payment.
  4. A row goes missing. A bug, or a write split across two services, saves Shop +20 but not Bob -20.
  5. The nightly check. Each night a job adds up every payment and matches the ledger against the card company's report.
  6. Fix with a new row. It never edits old rows; it adds a correcting row, so the full history stays.
  7. 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

  1. Every payment writes two rows: money out of one account, into another.
  2. Each payment's rows sum to zero, so money is moved, never made.
  3. A balance is the sum of an account's rows, so every cent has a reason.
  4. 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

Why do many systems avoid two-phase commit across services?

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?

A service saves an order to its database, then publishes an "order placed" event to Kafka. It crashes between the two steps. What does the outbox pattern change?

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

An outbox relay publishes 2 million rows a day, and nothing ever deletes the rows it has sent. What happens after a month?

Apply it

In an order saga, the card is charged, then stock runs out, and the refund has not run yet. The user opens the order page. What should it show?

Judge a design

An order flow of 9 steps across 7 services uses choreography: each service reacts to the others' events. Nobody can tell where a stuck order is. What is better?

Next: multi-region architecture, how a system survives the loss of a whole region.

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.