Sagas, the outbox pattern and CQRS

Topic 9 of 9 in Week 5: Distributed systems and service communication12 min readAdvancedFree course

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 made of local steps. Create order (pending), then reserve stock (reserved), then charge card, which is declined; arrange delivery is never run. Compensating actions then run in reverse: release stock (released), then cancel order (cancelled). In choreography, each service reacts to the previous service’s event; in orchestration, one saga orchestrator tells each service what to do next, which is easier to follow. Steps and compensations must be idempotent, and users may briefly see intermediate states.

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 publishes StockReserved; 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 transactional outbox. The order service inserts order 981 into the orders table and an OrderPlaced event for order 981 into an outbox table in one database transaction. A relay, or change data capture, reads new outbox rows and publishes them to a message broker such as Kafka or SQS. There are no saved-but-never-published or published-but-not-saved gaps. The relay may publish twice after a crash, so consumers stay idempotent. CDC tools such as Debezium can read the outbox from the database log instead of polling.

The outbox pattern:

  1. In the same local transaction as the business change, insert the event into an outbox table.
  2. 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.
  3. 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

CQRS: separate models for writes and reads. The client sends commands to the command side, which validates them and writes to a normalised, transactional write database. Events from the write side update read models: denormalised views. The client sends queries to the query side, which reads from the read models for fast reads. Use CQRS when reads and writes have very different shapes or scale; the read side lags slightly. It is often combined with event sourcing, where the write side stores events and views are rebuilt by replaying them.

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.

Exercise

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?

Text
(a)
(b)
(c)
(d)

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.