Skip to content

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.

18 min read0/5 questions

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:

orders/service.py
db.save(order)                              # write 1: Postgres
kafka.publish("orders", OrderPlaced(order)) # write 2: Kafka

Two writes to two systems cannot be atomic. Walk each crash point and see what you lose.

Code orderCrash pointResult
save, then publishAfter save, before publishOrder exists, nobody hears about it. No email, stock never reserved. Silent.
save, then publishPublish times out but actually succeeded, you retryEvent published twice. Consumers see a duplicate.
publish, then saveAfter publish, before saveDownstream reacts to an order that does not exist. Email sent for nothing.
publish inside the DB transactionPublish 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 orderThe delete itself failsYou 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:

  1. 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."
  2. Commit. If every vote is yes, the coordinator logs its decision and tells everyone to commit. One no, or a timeout, and everyone aborts.
2PC, and the coordinator crash that blocks everyone
CoordinatorOrders DBInventory DBPREPARE tx-81vote YESPREPARE tx-81vote YEScrash before sending COMMITstill waiting, locks held

The orders database writes the change to its log and keeps the row locks. It has not committed.

1/6

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.

migrations/0042_outbox.sql
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_at flag (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_id as 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.

Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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.

Pythonoutbox_and_inbox.py
import sqlite3 db = sqlite3.connect(":memory:")db.executescript("""CREATE TABLE orders (id INTEGER PRIMARY KEY, total INTEGER);CREATE TABLE outbox (id INTEGER PRIMARY KEY, aggregate_id INTEGER, type TEXT, sent INTEGER DEFAULT 0);CREATE TABLE inbox (message_id INTEGER PRIMARY KEY); -- consumer sideCREATE TABLE points (customer TEXT PRIMARY KEY, total INTEGER);INSERT INTO points VALUES ('ada', 0);""") def place_order(order_id, total): with db: # one transaction: both rows or neither db.execute("INSERT INTO orders VALUES (?, ?)", (order_id, total)) db.execute("INSERT INTO outbox (aggregate_id, type) VALUES (?, 'OrderPlaced')", (order_id,)) broker = [] # what the relay has published def relay(crash_before_mark=False): rows = db.execute("SELECT id, aggregate_id, type FROM outbox WHERE sent = 0 ORDER BY id").fetchall() for msg_id, agg, typ in rows: broker.append((msg_id, agg, typ)) if crash_before_mark: print(f"relay published {msg_id} then crashed before marking it sent") return db.execute("UPDATE outbox SET sent = 1 WHERE id = ?", (msg_id,)) db.commit() def consume(msg_id, agg): with db: # dedupe row and the effect commit together cur = db.execute("INSERT OR IGNORE INTO inbox VALUES (?)", (msg_id,)) if cur.rowcount == 0: print(f"consumer: message {msg_id} already processed, skip") return db.execute("UPDATE points SET total = total + 10 WHERE customer = 'ada'") print(f"consumer: message {msg_id} applied") place_order(1, 4999)place_order(2, 1500)relay(crash_before_mark=True) # publishes message 1, never marks itrelay() # restart: message 1 is still unsent, so it goes againprint("broker log:", [m[0] for m in broker])for msg_id, agg, _ in broker: consume(msg_id, agg)print("points:", db.execute("SELECT total FROM points").fetchone()[0])
Output
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.

OrchestrationChoreography
Who decides the next stepOne orchestrator (a state machine)Each service reacts to the previous event
Where the flow livesOne place you can read and testSpread across every subscriber
CouplingOrchestrator knows every stepServices only know events
Debugging "where is order 81?"Query the orchestrator's stateCorrelate events across services
Good forBusiness-critical flows with 4 or more stepsShort, 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.

Put it in order5 steps

Order these checkout steps the way a well-designed saga runs them.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Pythoncheckout_saga.py
class StepFailed(Exception): pass class Services: def __init__(self, fail_at=None, flaky_refund=0): self.fail_at = fail_at self.flaky_refund = flaky_refund # refund fails this many times first self.stock, self.charged, self.shipped = 5, 0, False def reserve_stock(self, o): self.stock -= o["qty"] def release_stock(self, o): self.stock += o["qty"] def charge_card(self, o): self.charged += o["cents"] def refund_card(self, o): if self.flaky_refund: self.flaky_refund -= 1 raise StepFailed("payments API timed out") self.charged -= o["cents"] def book_courier(self, o): if self.fail_at == "book_courier": raise StepFailed("no courier for that postcode") self.shipped = True STEPS = [ ("reserve_stock", "release_stock"), ("charge_card", "refund_card"), ("book_courier", None),] def run_saga(svc, order, max_attempts=5): log = [] # in production: a durable table for action, undo in STEPS: try: getattr(svc, action)(order) log.append(("done", action, undo)) print(f" ok {action}") except StepFailed as e: print(f" FAIL {action}: {e}") for _, done_action, comp in reversed(log): if comp is None: continue for attempt in range(1, max_attempts + 1): try: getattr(svc, comp)(order) # must be idempotent print(f" undo {comp} (attempt {attempt})") break except StepFailed as e2: print(f" retry {comp}: {e2}") else: return "STUCK: page a human" return "CANCELLED" return "COMPLETED" order = {"qty": 2, "cents": 4999}for label, svc in [("happy path", Services()), ("courier fails, refund flaky", Services("book_courier", flaky_refund=2))]: print(label) status = run_saga(svc, order) print(f" -> {status} stock={svc.stock} charged={svc.charged}\n")
Output
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

FailureWhat goes wrongDefence
A step times out, but it actually succeededYou do not know whether the card was chargedEvery 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 failsMoney charged for an order you cancelledRetry with backoff; compensations must be idempotent; after N attempts, escalate to a human queue.
Compensation arrives before the actionA 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 twiceStock reserved twice for one orderIdempotency key on every step, enforced by a unique constraint downstream.
The orchestrator crashes mid-sagaSaga half done, nobody driving itSaga 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 OrderPaidVersion numbers per aggregate, plus a state machine that rejects illegal transitions.
Match the pairs0/5 matched

Match each failure to the defence that handles it.

Choose an item, then its match on the other side.

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.

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

Quick check
Your team proposes XA two-phase commit across the orders database, Kafka, and the payment provider. What is the strongest objection?
Need a nudge? A hint rules out a wrong answer.
Quick check
A service publishes to Kafka inside its open database transaction, then commits. Which failure can still happen?
Need a nudge? A hint rules out a wrong answer.
Key terms
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.