Sagas, outbox and CDC
When one order touches three services, there is no single "undo". Learn to undo step by step, and to send events that never get lost.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
A shop splits checkout into three services: Orders, Inventory and Payments. Each one has its own database.
A new engineer writes the order flow in the Orders service. It creates the order, calls Inventory to hold the item, and then calls Payments to charge the card. If the charge fails, it marks the order "failed".
It looks fine in testing. In production, cards fail every day. Each time, the order is marked "failed", but the held item stays held. Nobody tells Inventory to let it go.
After a month, popular items show "out of stock" on the site. The warehouse has them on the shelf. Hundreds of units are held for orders that will never ship.
A second bug hides in the same code. Orders saves an order, then sends an "OrderPlaced" event to Kafka. One night the service restarts between those two steps. Thirty orders exist, but the warehouse never hears about them. Customers wait for parcels that nobody packs.
The idea in simple words
Inside one database, a transaction gives you "all or nothing". Across three services with three databases, you do not get that for free.
The classic tool for "all or nothing" across databases is two-phase commit, or 2PC. A coordinator asks every database to prepare, then tells all of them to commit. AWS says 2PC is not an option in a database-per-service design. There is no single controller that can coordinate the services that way. 5 Message brokers add another gap. You cannot have one transaction that spans your database and Kafka. 7
So teams use a saga. A saga is a chain of small local transactions. Each step commits on its own. If a later step fails, the saga runs a compensating transaction for each earlier step, to undo its effect. 3 The idea comes from a 1987 paper by Garcia-Molina and Salem. They split long database transactions into short ones, with compensations that undo a partial run. 2
Each step must also tell the next service what happened. Writing to your database and to a broker in two calls is the dual-write problem. The transactional outbox fixes it. You save the event in your own database, in the same transaction as your data. A separate relay publishes it later. 4
The key idea. Across services, you cannot roll back. You can only move forward with new actions that undo old ones. And you never write to two systems at once: write to one, and copy from it.
How it works
Step through an order saga that fails at payment. Then see how the outbox sends each event. Use Next and Back, or the ← and → keys.
- Priya places order 42. The order saga saves it in the order database with the state pending. Each step from here is its own local transaction.
- The saga asks Inventory to hold one item. Inventory commits that in its own database. Nothing is locked across services.
- The saga asks Payments to charge ₹1,499. The card is declined. There is no global rollback, so the saga must undo the earlier steps itself.
- First compensating action: the saga tells Inventory to release the item. Inventory commits a new change. It does not erase history.
- Second compensating action: the saga marks the order cancelled. Steps are undone in reverse order. Priya sees a clear message, not a stuck order.
- How does each step send its event safely? The Order service writes the order row and an outbox row in the same database transaction. Both are saved, or neither is.
- A separate relay reads new outbox rows. A CDC tool like Debezium does this by reading the database's change log, not by polling the table.
- The relay publishes the event to a topic. If the transaction rolled back, there is no outbox row, so no event. The relay may send a row twice, so consumers skip duplicate event IDs.
Choreography or orchestration
There are two ways to run a saga. 3
- Choreography. No one is in charge. Each service listens for events and reacts. Orders emits "OrderPlaced". Inventory hears it, holds stock, and emits "StockReserved". Payments hears that, and so on.
- Orchestration. One component, the orchestrator, tells each service what to do next. It keeps the state of the whole saga in one place.
AWS lists the costs of each. Choreography has no central part to fail. But as services grow, the flow gets hard to follow, and services can end up depending on each other in a cycle. Timeouts and retries must be built into every service. 6 An orchestrator keeps the flow in one place, but it can become a single point of failure. 5 The AWS guide shows an orchestrator built on Step Functions. It undoes payment, inventory and the order when a step fails. 5
Writing good compensations
A compensation is not a database rollback. The first step already committed, and other people may have seen it. So the compensation is a new business action: "release the item", "refund the charge", "cancel the order".
Sagas also have no isolation. Two sagas can run at the same time and see each other's half-done work. 3 For example, a customer may see stock as held for a minute, then free again. Design for this. Show states like "pending" to users, and do the steps that are hard to undo, like shipping, last.
Compensations can fail and run twice too. Make every step and every compensation idempotent, so a retry does no harm. 5 See idempotency, retries and timeouts.
The outbox, step by step
In the same database transaction, you insert the order row and one outbox row. The outbox row holds the event: an ID, the aggregate type and ID (here, the order and its ID), an event type like "OrderCreated", and a payload. 10 If the transaction commits, both rows exist. If it rolls back, neither does. So the event is sent if and only if the data was saved. 4
A relay then moves outbox rows to the broker. There are two common ways. 4
- Polling. A job reads new rows from the outbox table every second or so, publishes them, and marks them as sent.
- Log tailing. A tool reads the database's own change log and publishes every new outbox row.
Change data capture
Log tailing is a kind of change data capture, or CDC. Most databases keep a log of changes so it can recover from a crash. In Postgres this is the WAL. The Debezium Postgres connector reads it through logical decoding and a replication slot. Logical decoding turns the WAL into plain row changes. A slot is a stream of those changes that Postgres keeps until the reader has them 1. After a restart, the connector carries on from where it stopped. 9
Debezium lists the benefits over polling. It captures every change, with very low delay. It needs no "last updated" column. It can also see deletes. 8 With CDC, you can even delete each outbox row right after you insert it. The insert is already in the log, so the table stays empty. 7
The inbox: dedup on the consumer side
The relay can publish a message more than once. For example, it might crash after it publishes but before it records that fact. 4 So every consumer must expect duplicates.
The fix is an inbox. The consumer keeps a table of event IDs it has already handled. In one transaction, it does the work and saves the ID. If the ID is already there, it skips the event. 7 This is at-least-once delivery plus an idempotent handler, the same pattern as in queues vs logs.
Order matters too. By default, Debezium uses the outbox row's aggregate ID as the Kafka message key, so events for one order stay in order inside a partition. 10
Trade-offs
| Option | One place to see the flow? | Main risk | Use when |
|---|---|---|---|
| 2PC across services | Yes | Every service must support it and wait on a coordinator. | Rarely. Only inside one system that supports it well. |
| Saga with choreography | No The flow is spread across services. | Hard to trace, cycles between services. | Two or three steps with a simple flow. |
| Saga with orchestration | Yes | The orchestrator is critical and must be reliable. | Many steps, timeouts, human steps, frequent changes. |
| Outbox with a polling relay | n/a | Delay and load from polling the table. | A simple start, with no CDC tooling. |
| Outbox with CDC (Debezium) | n/a | More systems to run and watch. | High volume, low delay, a team that can run Kafka Connect. |
| Dual write (DB, then broker) | n/a | Lost or phantom events after a crash. | Never for events that matter. |
Simple rule: start with an orchestrated saga and an outbox. Move to choreography only for short flows where each team owns its part.
At work: how a senior uses this
- For every multi-service flow, write the table: step, compensation, and "can this be undone?". Put steps that cannot be undone, like shipping or sending money out, last.
- Search the code for "save, then publish". Each one is a dual write. Replace it with an outbox.
- Give every event a unique ID, and make every consumer store the IDs it has handled.
- Make the saga's state visible. Store it in a table or a workflow engine, with a dashboard of stuck sagas older than, say, 15 minutes.
- Add a timeout to every saga step. A step that never answers must lead to a compensation, not a forever "pending".
- Watch the relay. Alert on outbox rows that are old and still unsent, or on CDC lag.
With AI
What to ask the agent
"Here is our checkout flow across Orders, Inventory and Payments. List each step, what commits where, and what compensation undoes it. Mark any step with no compensation."
"Find every place in this service where we write to the database and then publish to Kafka. Replace each one with an insert into an outbox table in the same transaction."
"Write a consumer for OrderCreated that stores the event ID and its result in one transaction, and skips IDs it has seen. Add a test that delivers the same event twice."
What to check yourself
- The outbox insert really is inside the same transaction as the business write. Check the transaction boundaries, not just the function name.
- Every compensation is idempotent. Run it twice in a test.
- Compensations run in reverse order, and a failure in a compensation is retried or raised to a person. It is not silently logged.
- The agent did not add a "publish directly if the outbox is slow" shortcut. That brings the dual write back.
- The consumer's dedup check and its work share one transaction.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 10 sources and related lessons
- PostgreSQL documentation, “Logical Decoding Concepts” (opens in a new tab)
What logical decoding and replication slots are, and how a slot keeps changes until the client has read them. - Hector Garcia-Molina and Kenneth Salem, “Sagas”, Princeton University technical report TR-070-87 (1987); also in the ACM SIGMOD 1987 proceedings (opens in a new tab)
The original paper. A long transaction is split into a chain of short ones, and compensating transactions undo a partial run. - Chris Richardson, “Pattern: Saga”, microservices.io (opens in a new tab)
Sagas across services, compensating transactions, choreography vs orchestration, and the lack of isolation. - Chris Richardson, “Pattern: Transactional outbox”, microservices.io (opens in a new tab)
The outbox table, the message relay, and why the relay can publish a message more than once. - AWS Prescriptive Guidance, “Saga orchestration pattern” (opens in a new tab)
Why 2PC does not fit a database-per-service design, an order-inventory-payment example, and a Step Functions version. - AWS Prescriptive Guidance, “Saga choreography pattern” (opens in a new tab)
Event-driven sagas, and their costs - harder tracking, cyclic dependencies and the dual-write issue. - Gunnar Morling, “Reliable Microservices Data Exchange With the Outbox Pattern”, Debezium blog (2019) (opens in a new tab)
The dual-write problem with Kafka, an outbox read by CDC, and a consumer that skips duplicate event IDs. - Debezium documentation, “Debezium Features” (opens in a new tab)
Log-based change data capture compared with polling, including low delay and capturing deletes. - Debezium documentation, “Debezium connector for PostgreSQL” (opens in a new tab)
How the connector uses logical decoding and a replication slot, and resumes reading the WAL after a restart. - Debezium documentation, “Outbox Event Router” (opens in a new tab)
The outbox table columns, how rows are routed to topics, and using the event id to remove duplicates.
Case studies: PhonePe: TStore: one store for every payment's history
Related: Queues vs logs and delivery guarantees · Idempotency, retries and timeouts · Transactions and isolation levels · Distributed transactions and two-phase commit · Checkout and the order state machine · Workflow engines and durable execution (coming soon)
Before this: queues vs logs and idempotency, retries and timeouts. Next: checkout and the order state machine. Related: event-driven architecture and event sourcing, exactly-once and effectively-once, and distributed transactions and two-phase commit, the approach sagas replace across services.