Lesson 16 of 38Distributed systems
Sagas, Outbox, and Two-Phase Commit
Keep data correct when one business action spans several databases and services: dual writes, 2PC, the outbox and inbox, sagas, and durable execution.
A customer clicks "Place order". The order service writes a row to its Postgres, the payment service charges the card through a provider, the inventory service reserves two units in its own database, and an OrderPlaced event goes to Kafka so email and analytics can react. Four systems, one business action, and no single transaction that covers them all. Somewhere in that chain a process will crash, a network call will time out, or a deploy will kill a pod mid-request. This lesson is about what your data looks like afterwards, and the patterns teams use so the answer is "correct" rather than "it depends". You met the outbox and sagas briefly in Event-Driven Architecture. Here you go underneath them: the failure cases, the trade-offs, and the questions interviewers keep for senior candidates.
The dual-write problem, crash by crash
The bug starts with two innocent lines:
db.save(order) # write 1: Postgres
kafka.publish("orders", OrderPlaced(order)) # write 2: KafkaTwo writes to two systems cannot be atomic. Walk each crash point and see what you lose.
| Code order | Crash point | Result |
|---|---|---|
| save, then publish | After save, before publish | Order exists, nobody hears about it. No email, stock never reserved. Silent. |
| save, then publish | Publish times out but actually succeeded, you retry | Event published twice. Consumers see a duplicate. |
| publish, then save | After publish, before save | Downstream reacts to an order that does not exist. Email sent for nothing. |
| publish inside the DB transaction | Publish succeeds, then COMMIT fails (deadlock, constraint) | Same phantom event. The transaction rolled back, but Kafka cannot un-send. |
save, then publish in a try/except that deletes the order | The delete itself fails | You are now writing a distributed rollback by hand. It will have bugs. |
The last two rows are the ones people reach for under pressure, and both are traps. The honest conclusion: you need one atomic write, and then a way to turn that write into everything else, reliably and repeatably. That is the outbox. Before it, look at the classic answer and why most teams avoid it.
Two-phase commit and why services avoid it
Two-phase commit (2PC) makes several participants commit or abort together. A coordinator runs two rounds:
- Prepare. The coordinator asks every participant "can you commit?". Each one writes the change durably, holds its locks, and votes yes or no. A yes is a promise: "I can commit this even if I crash and restart."
- Commit. If every vote is yes, the coordinator logs its decision and tells everyone to commit. One no, or a timeout, and everyone aborts.
The orders database writes the change to its log and keeps the row locks. It has not committed.
2PC is correct, but in a microservice world it costs too much:
- It blocks. Locks are held across a network round trip, and indefinitely if the coordinator dies after prepare.
- Availability multiplies down. Every participant must be up for any transaction to commit. Five services at 99.9% each give roughly 99.5% for the combined operation.
- Most of your participants cannot take part. The standard protocol for this is XA. Postgres and MySQL support it, but Kafka, Redis, a payment provider's HTTP API, and an email service do not. You cannot "prepare" a Stripe charge.
- It couples services to each other's lock lifetimes and release schedules.
2PC has not gone away. It moved inside databases, where the coordinator itself is replicated by consensus, so a single crash does not block. Spanner runs 2PC across Paxos groups; CockroachDB runs a 2PC variant across Raft ranges, so the problems you saw in Consensus and Leader Election are solved underneath it. Kafka's own transactions use a coordinator and commit markers in the same spirit. Postgres exposes the raw building block as PREPARE TRANSACTION 'tx-81' and COMMIT PREPARED 'tx-81', disabled by default (max_prepared_transactions = 0) because a forgotten prepared transaction holds locks and blocks vacuum until someone notices.
The rule of thumb: use 2PC when a database gives it to you for free. Do not build it across services.
The transactional outbox, in depth
The outbox turns two writes into one. In the same local transaction as the business change, insert the event into an outbox table. A relay then moves rows from the table to the broker.
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
aggregate_id text NOT NULL, -- e.g. the order id; becomes the Kafka key
type text NOT NULL, -- 'OrderPlaced'
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
sent_at timestamptz
);
CREATE INDEX outbox_unsent ON outbox (id) WHERE sent_at IS NULL;
-- Relay, one batch. Several relay workers can run this without stepping on each other.
BEGIN;
SELECT id, aggregate_id, type, payload
FROM outbox
WHERE sent_at IS NULL
ORDER BY id
LIMIT 100
FOR UPDATE SKIP LOCKED;
-- publish each row to Kafka with key = aggregate_id, wait for the acks
UPDATE outbox SET sent_at = now() WHERE id = ANY(:published_ids);
COMMIT;There are two ways to run the relay, and the details are where teams get burned.
Polling. Query unsent rows on a short interval. FOR UPDATE SKIP LOCKED lets several relay instances share the work: each skips rows another has locked. It is simple and needs nothing but SQL. Watch three things:
- Do not poll with a "last id seen" cursor. IDs are assigned when a row is inserted, but transactions commit in a different order. A transaction holding id 7 can commit after one holding id 8. A relay that remembers "I am past 8" never sees 7. Track a
sent_atflag (as above), or read the write-ahead log, which is in commit order. - Ordering. Parallel relays can publish two events for the same order out of order. If order matters per aggregate, use the
aggregate_idas the Kafka key (so one partition keeps them in sequence, as Stream Processing explains) and have consumers check a version number. A single relay per shard of aggregates also works. - Cleanup. The table grows forever if you let it. Delete sent rows after a few days, or partition the table by day and drop old partitions, which is cheaper than mass deletes in Postgres.
Change data capture (CDC). Debezium reads the database's write-ahead log through a logical replication slot and turns each outbox insert into a Kafka message. Its outbox event router routes rows to topics by type and keys them by aggregate_id. No polling load, lower latency, and the log is in commit order. The catch: a replication slot keeps WAL on disk until its reader confirms it. If Debezium is down for a day, the primary's disk fills with WAL. Set max_slot_wal_keep_size (Postgres 13 and later) and alert on slot lag.
A relay polls with a 'last id seen' cursor. Transaction A got id 7, transaction B got id 8, and B commits first. What has been published after both polls?
committed = [] last_seen = 6 published = [] committed.append(8) # tx B commits first published += [i for i in sorted(committed) if i > last_seen] last_seen = max(published) committed.append(7) # tx A, which got id 7 earlier, commits now published += [i for i in sorted(committed) if i > last_seen] print(published)
The inbox: idempotent consumers, properly
The relay can publish a row and crash before marking it sent, so it publishes again. Kafka consumers can process a batch and crash before committing offsets. Duplicates are not an edge case; they are the contract. "Exactly-once" in practice means at-least-once delivery plus deduplication.
The receiving side keeps an inbox (or "processed messages") table, and inserts the message id in the same transaction as the effect. If the insert hits the primary key, the message was already handled.
Run this. It places two orders, crashes the relay once between publishing and marking sent, and shows the consumer absorbing the duplicate.
Press Run (⌘ Enter) to see what happens.Three details make the inbox work in production. The dedupe key must be stable across retries (the outbox row id or an event UUID, never a timestamp the relay generates). The inbox row and the effect must share one transaction, or you are back to a dual write. And the table needs a retention window longer than any realistic redelivery, often a week. When the effect lives outside your database (sending an email, calling a payment API), you cannot share a transaction with it, so pass the message id as the downstream's idempotency key instead, as Payments shows.
Sagas: orchestration, choreography, and the pivot
A saga is a sequence of local transactions, each with a compensating action. Event-Driven Architecture showed the basic loop. Here is what changes when you design one for real.
Orchestration vs choreography.
| Orchestration | Choreography | |
|---|---|---|
| Who decides the next step | One orchestrator (a state machine) | Each service reacts to the previous event |
| Where the flow lives | One place you can read and test | Spread across every subscriber |
| Coupling | Orchestrator knows every step | Services only know events |
| Debugging "where is order 81?" | Query the orchestrator's state | Correlate events across services |
| Good for | Business-critical flows with 4 or more steps | Short, stable flows with 2 or 3 steps |
Most teams start with choreography because it needs no new component, then move checkout-style flows to orchestration once nobody can answer "what happens if step 4 fails?" without reading five codebases.
Compensation is not rollback. A database rollback makes it as if the change never happened. A compensation is a new forward action that other people may see. A refund is a new ledger entry, not a deleted charge; the customer sees both on their statement. Between the action and its compensation, the world saw the intermediate state: stock looked reserved, an email may have gone out. Some steps cannot be compensated at all. You cannot unsend an email or un-ship a parcel.
That leads to the most useful design rule for sagas. Classify each step:
- Compensatable: can be undone (reserve stock, authorise a card).
- Pivot: the point of no return. Once it succeeds, the saga must complete (capture the payment, hand the parcel to the courier).
- Retriable: after the pivot, steps that must eventually succeed, so you retry them until they do (send the confirmation email, update analytics).
Order the saga as compensatable steps, then the pivot, then retriable steps. Put anything irreversible as late as you can.
Sagas have no isolation. A saga gives you atomicity (eventually all or nothing) but not the "I" in ACID. Another request can read the half-finished state. The standard countermeasure is a semantic lock: the order sits in PENDING while the saga runs, and other operations respect that flag (a second checkout for the same cart is refused, the order page says "processing"). Other countermeasures: make updates commutative (stock = stock - 2 rather than stock = 3), and re-read and check a version before the pivot.
Order these checkout steps the way a well-designed saga runs them.
- Tap the steps below in the right order.
A checkout orchestrator you can break
This orchestrator keeps a saga log (in production, a durable table or a workflow engine's history), fails at step 3, and runs compensations in reverse. The refund API is flaky, so the compensation itself has to be retried.
Press Run (⌘ Enter) to see what happens.Try flaky_refund=9. The saga gives up with STUCK: page a human. That outcome is real and you must design for it: a compensation that keeps failing is not something code can resolve. It goes to an operations queue with the saga id and full history.
The failure table interviewers probe
| Failure | What goes wrong | Defence |
|---|---|---|
| A step times out, but it actually succeeded | You do not know whether the card was charged | Every step call carries an idempotency key (saga_id + step). Retry the same call, or query its status by key. Never assume a timeout means failure. |
| A compensation fails | Money charged for an order you cancelled | Retry with backoff; compensations must be idempotent; after N attempts, escalate to a human queue. |
| Compensation arrives before the action | A CancelReservation reaches inventory before ReserveStock (retries, reordering) | Record the cancel as a tombstone; when the late reserve arrives, see the tombstone and refuse it. |
| A step runs twice | Stock reserved twice for one order | Idempotency key on every step, enforced by a unique constraint downstream. |
| The orchestrator crashes mid-saga | Saga half done, nobody driving it | Saga state is durable; on restart, resume from the log. This is what workflow engines do for you. |
| Events arrive out of order (choreography) | OrderShipped processed before OrderPaid | Version numbers per aggregate, plus a state machine that rejects illegal transitions. |
Match each failure to the defence that handles it.
Durable execution: the 2026 default for long workflows
Writing that orchestrator well means a durable state table, timers, retries with backoff, idempotency keys, and recovery after crashes. Durable execution engines give you all of it so the saga reads like ordinary code. Temporal, Restate, AWS Step Functions, and Azure Durable Functions are the common choices.
The idea in Temporal, as an example: a workflow is code whose every step is recorded in an event history. Activities are the side-effecting calls (charge the card), retried by the engine with the policy you set. If the worker running the workflow dies, another worker replays the history to rebuild the exact state and carries on. This is why workflow code must be deterministic: no direct clock reads, random numbers, or network calls in the workflow itself, only through the SDK.
from datetime import timedelta
from temporalio import workflow
@workflow.defn
class Checkout:
@workflow.run
async def run(self, order: dict) -> str:
opts = {"start_to_close_timeout": timedelta(seconds=30)}
undo = []
try:
await workflow.execute_activity("reserve_stock", order, **opts)
undo.append("release_stock")
await workflow.execute_activity("authorise_card", order, **opts)
undo.append("void_authorisation")
await workflow.execute_activity("capture_payment", order, **opts) # pivot
undo.clear()
except Exception:
for step in reversed(undo):
await workflow.execute_activity(step, order, **opts)
return "cancelled"
await workflow.execute_activity("send_confirmation", order, **opts) # retried until it works
return "completed"Treat this as a sketch of the shape, and check the SDK docs for current signatures and retry options. Step Functions expresses the same flow as a JSON state machine with Catch blocks; Durable Functions replays orchestrator code much like Temporal. The trade-off is a new piece of infrastructure to run or pay for, and a programming model your team must learn. For one two-step flow, an outbox and a state column are enough. For checkout, onboarding, or anything with timers ("cancel if unpaid after 30 minutes"), a workflow engine usually pays for itself quickly.
- dual write
- Writing to two systems (say a database and a broker) with no shared transaction, so a crash between them leaves them inconsistent.
- two-phase commit (2PC)
- A protocol where a coordinator asks participants to prepare, then tells them all to commit or abort. Correct, but blocks if the coordinator fails after prepare.
- transactional outbox
- Writing an event to an outbox table in the same local transaction as the change, then publishing it with a relay or CDC.
- inbox table
- A consumer-side table of processed message ids, inserted in the same transaction as the effect, so duplicates are skipped.
- saga
- A sequence of local transactions with compensating actions, giving eventual all-or-nothing without a distributed lock.
- pivot transaction
- The saga step after which the saga can no longer be undone and must run to completion.
- durable execution
- An engine (Temporal, Restate, Step Functions) that records workflow progress so it survives crashes and resumes where it stopped.