Sagas, the outbox pattern and CQRS
Overview
In a monolith, placing an order can update orders, stock and payments in one database transaction. Once those live in separate services with separate databases, that transaction is gone, and naive solutions leave data half-updated when something fails. Three patterns handle this: sagas for multi-step business transactions, the transactional outbox for publishing events reliably, and CQRS for building fast read views across services.
Why not distributed transactions?
Two-phase commit (2PC) can make several databases commit atomically, but every participant must support it, it holds locks while waiting for the slowest participant, and a coordinator failure can leave participants blocked. Across independently deployed services and external APIs (a card network won’t join your 2PC), it’s rarely practical.
Sagas
A saga is a sequence of local transactions, one per service. Each step commits on its own and triggers the next. If a step fails, the saga runs compensating actions for the steps that already completed, in reverse order.
Compensations undo the business effect, not the database rows: “release the reserved stock”, “refund the payment”, “cancel the order and email the customer”. Some actions can’t be undone (an email already sent), so order steps so that irreversible ones come last, and reserve before you commit (“reserve stock” then later “confirm”).
Choreography vs orchestration
- Choreography: no central coordinator. The order service publishes
OrderCreated; the stock service reacts and publishesStockReserved; payments reacts to that, and so on. Simple for short flows, but the overall process is implicit and hard to follow as it grows. - Orchestration: a saga orchestrator (a service or workflow engine such as Temporal or AWS Step Functions) keeps the saga’s state and tells each service what to do. Easier to understand, monitor and change; the orchestrator becomes a component to run carefully.
Rules for sagas
- every step and compensation must be idempotent, because messages are retried,
- model intermediate states explicitly (
PENDING,PAYMENT_FAILED) and show them honestly, - accept that other users can see intermediate states (there’s no isolation between sagas); use reservations or semantic locks where it matters.
The transactional outbox
A service often needs to update its database and publish an event. Doing them separately is dangerous: if it commits and crashes before publishing, other services never hear about the change; if it publishes first and the commit fails, they hear about something that didn’t happen.
The outbox pattern:
- In the same local transaction as the business change, insert the event into an
outboxtable. - A separate relay reads unpublished outbox rows (by polling, or by tailing the database log with change data capture) and publishes them to the broker.
- It marks them as published (or tracks its position in the log).
The change and the event either both exist or neither does. The relay may publish an event more than once after a crash, so consumers deduplicate by event ID. The mirror image on the consumer side is the inbox: record processed event IDs in the same transaction as the handling.
CQRS
Command Query Responsibility Segregation uses different models for changing data and for reading it:
- the command side validates and applies changes to a normalised, transactional store,
- events from it update one or more read models: denormalised tables, search indexes, caches, each shaped for a specific screen or query,
- queries read only from the read models.
It’s useful when reads and writes differ greatly in shape or volume, or when a screen needs data from several services (a “my orders” view combining orders, shipments and payments). The cost is eventual consistency between write and read sides and more moving parts. Don’t apply it everywhere, only where the read side justifies it.
Event sourcing often accompanies CQRS: instead of storing current state, the write side stores the sequence of events (“deposited 100”, “withdrew 30”) and derives state by replaying them. It gives a perfect audit trail and the ability to rebuild new views from history, at the cost of more complex queries and schema evolution of events.
In an interview
For any multi-service write: “Checkout is an orchestrated saga: reserve stock, charge payment, confirm order; if payment fails we release the stock. Each service publishes its events through an outbox so state and events can’t diverge, and consumers are idempotent. The order-history screen reads a CQRS view built from those events.”
Recap
Without cross-service transactions, sagas chain local transactions and undo completed steps with compensating actions, coordinated by choreography or an orchestrator. The transactional outbox writes state changes and events together, so publishing is reliable. CQRS builds read-optimised models from events for fast queries across services, accepting a short lag. Idempotency underpins all three.
Book a trip across services
A travel app books a trip with three services: Flights (reserve a seat), Hotels (reserve a room) and Payments (charge the card). Each has its own database. (a) Design an orchestrated saga for 'book trip', including compensating actions. (b) The hotel step fails. List exactly what happens. (c) How does each service publish its events reliably? (d) The 'My trips' screen needs data from all three services and must load fast. How would you build it?
(a)
(b)
(c)
(d)(a) Orchestrator (a Trip saga with its own state table):
1. Flights: reserve seat (compensation: release seat)
2. Hotels: reserve room (compensation: release room)
3. Payments: charge card (compensation: refund)
4. Flights + Hotels: confirm reservations
Trip state goes PENDING -> CONFIRMED or CANCELLED. Every step is idempotent and
keyed by trip_id, so retries are safe.
(b) Seat reserved -> hotel reservation fails -> orchestrator runs compensations in
reverse: release the seat; payment was never attempted. Trip marked CANCELLED and
the user is told no room was available (or offered alternatives).
(c) Transactional outbox in each service: write the business change and an outbox row
in the same local transaction; a relay (or CDC such as Debezium) publishes outbox
rows to the broker. Consumers deduplicate by event ID.
(d) CQRS read model: a "trips view" service subscribes to flight, hotel and payment
events and maintains a denormalised table/document per user trip. The screen reads
just that; it may lag by a second or two.Summary
- With a database per service there are no cross-service transactions; sagas replace them with a sequence of local transactions.
- Each saga step has a compensating action that semantically undoes it if a later step fails.
- Sagas can be choreographed (services react to events) or orchestrated (a coordinator drives the steps).
- The transactional outbox writes the state change and the event in one local transaction, then a relay publishes it, so changes and events can't diverge.
- CQRS separates the write model from read-optimised models built from events, at the cost of eventual consistency.