Sagas & the outbox pattern
Without distributed transactions, a saga chains local transactions and undoes completed steps with compensating actions on failure; the outbox makes each "update DB + publish event" atomic by writing both in one local transaction.
Analogy: Booking a trip yourself: flight first, then hotel. If the hotel is full you don't rewind time, you cancel the flight, maybe paying a fee. That cancellation is a compensation.
How it works
- 2PC is rarely available across services: brokers and SaaS APIs don't join an XA transaction.
- A compensating action undoes a step semantically: a refund, not a DELETE.
- Sagas have no isolation: mark in-between state as PENDING and put the irreversible step last.
- Orchestration (Temporal, Step Functions) keeps the flow explicit; choreography has no central brain, so the flow lives nowhere.
- The outbox relay publishes by polling or CDC, at least once, so consumers must be idempotent.
Check yourself
Answer to mark it learned; your answers aren't scored.
An orchestrated order saga runs: reserve stock → charge card → create shipment. Shipment creation fails permanently (the carrier can't serve the address). What should the orchestrator do?
Go deeper
Full explanation
A business action often spans services that each own their database: reserve stock, charge the card, create the shipment. Two-phase commit across them is rarely available (brokers and SaaS APIs don't join an XA transaction) and blocks participants if the coordinator dies. Instead:
Saga: a sequence of local transactions, each paired with a compensating action that semantically undoes it (a refund, not a DELETE). If step 3 fails, run the compensations for steps 2 and 1. Sagas have no isolation: others can see the in-between state, so mark it (status = PENDING) and put the irreversible step last.
- Orchestration: one coordinator (Temporal, AWS Step Functions) tells each service what to do. The flow is explicit and testable.
- Choreography: each service reacts to the previous one's event. No central brain, but the flow lives nowhere and cycles creep in.
Transactional outbox solves the dual-write problem inside every step: "update my DB, then publish an event" is two writes, and a crash in between leaves them disagreeing. Write the event to an outbox table in the same transaction as the business change; a relay publishes it by polling or by CDC (Debezium tailing the WAL). Delivery is at-least-once, so consumers must be idempotent (Idempotency).
Code Outbox write and a polling relay
import json, uuid
import psycopg
from psycopg.types.json import Jsonb
def place_order(conn: psycopg.Connection, user_id: int, total: int) -> int:
# Order row and its event commit together or not at all: no dual write
with conn.transaction():
order_id = conn.execute(
"INSERT INTO orders (user_id, total, status) "
"VALUES (%s, %s, 'PENDING') RETURNING id", (user_id, total)).fetchone()[0]
conn.execute(
"INSERT INTO outbox (id, aggregate_id, type, payload) VALUES (%s, %s, %s, %s)",
(uuid.uuid4(), order_id, "OrderPlaced",
Jsonb({"order_id": order_id, "total": total})))
return order_id
def relay_once(conn: psycopg.Connection, producer, batch: int = 100) -> None:
# Debezium would tail the WAL instead of polling. At-least-once: a crash
# after flush() but before DELETE re-publishes, so consumers dedupe by id.
with conn.transaction():
rows = conn.execute(
"SELECT id, aggregate_id, type, payload FROM outbox "
"ORDER BY created_at LIMIT %s FOR UPDATE", (batch,)).fetchall()
for id_, agg, type_, payload in rows:
producer.send("orders",
key=str(agg).encode(), # same key = same partition = ordered
value=json.dumps({"id": str(id_), "type": type_, **payload}).encode())
producer.flush()
conn.execute("DELETE FROM outbox WHERE id = ANY(%s)", ([r[0] for r in rows],))Real example
A travel agent (LLM) plans three tool calls: reserve a flight ($420), reserve a hotel ($310), charge the card. The hotel API returns sold out. The orchestrator (Temporal), not the model, runs the registered compensation cancel_flight(booking_id), retrying until it succeeds, and the agent replans with another hotel. Each tool's DB write and its ToolExecuted event go through an outbox, so billing never charges for a booking that was rolled back and never misses one that committed. Charging the card is the pivot: last, and behind user confirmation.
Trade-offs +3 · −4
+ You gain
- Cross-service consistency without 2PC or distributed locks; each service keeps its own database.
- Failures get an explicit, tested recovery path instead of manual cleanup.
- The outbox makes "state change + event" atomic with a plain local transaction.
− You pay
- No isolation: intermediate states are visible, so you need semantic locks and careful step order.
- Compensations must be designed, idempotent and retried; some actions (a sent email) can't be undone.
- The outbox adds relay lag and at-least-once duplicates.
- Choreographed sagas are hard to trace and debug across services.
Use it when
An operation spans services or external APIs that each own their data and you need all-or-compensated outcomes: orders, payments, bookings, multi-step agent actions. Outbox: whenever a DB change must reliably emit an event.
Avoid it when
When everything lives in one database: use a plain transaction. Don't split a service just to end up needing a saga; steps that must be strictly isolated belong in one DB.
Numbers to know 3
- Sagas were introduced by Garcia-Molina and Salem in 1987, for long-lived transactions in a single database.
- 2PC: two round trips with locks held throughout; a coordinator crash after PREPARE leaves participants blocked.
- Postgres keeps WAL for an unconsumed replication slot indefinitely unless
max_slot_wal_keep_size(PG 13+) caps it.
Common pitfalls 4
- Publishing to Kafka right after commit and calling it an outbox: that's still a dual write.
- Non-idempotent compensations or consumers: at-least-once delivery runs the refund twice.
- Letting the LLM improvise the undo: compensations are code registered per tool, not generated text.
- An abandoned Debezium replication slot retains WAL until the Postgres disk fills.
Interview questions 3
Answer out loud first, then reveal.
How do you keep orders and payments consistent across two services without 2PC?Show answer
With a saga. The order service creates the order as PENDING in a local transaction and emits OrderPlaced through an outbox. The payment service charges and emits PaymentSucceeded or PaymentFailed; the order becomes CONFIRMED, or the compensation cancels it and releases stock. I orchestrate it with Temporal or Step Functions so the flow lives in one place and retries are durable. The trade-off: no isolation, so PENDING is a semantic lock readers must respect, and every step and compensation must be idempotent.
What is the dual-write problem and how does the outbox fix it?Show answer
Any code that writes the database and then publishes to a broker does two non-atomic writes. Crash between them and the event is lost; publish first and roll back, and you've announced something that never happened. The outbox makes it one write: the event goes into an outbox table in the same local transaction as the business row, and a relay, a poller or Debezium reading the WAL, publishes it. That's at-least-once, not exactly-once, so consumers dedupe by event id, usually with an inbox table.
An agent executes multi-step actions in real systems. How do you make failures safe?Show answer
I treat the run as a saga. Each tool declares its compensation in code, like cancel_booking for book_hotel, and a durable orchestrator, not the model, runs compensations in reverse order with retries. Reversible steps go first; the irreversible pivot, charging a card or sending an email, goes last and behind human approval. Every tool call carries an idempotency key, so a retry after a timeout doesn't double-book. After a rollback the LLM may propose a new plan; it never decides how to undo.