---
title: "CQRS, event sourcing, saga, and transactional messaging"
chapter: "13"
---

# CQRS, event sourcing, saga, and transactional messaging

These patterns address different problems and are often confused. CQRS separates write and read models; event sourcing stores state transitions; a saga coordinates distributed business work; outbox/inbox bridge database and messaging.

## Core ideas and patterns

| Idea | What it solves | Cost, limit, or warning |
|---|---|---|
| **CQRS** | Optimizes command and query models independently | Creates synchronization and consistency lag |
| **Event sourcing** | Persists an append-only sequence of domain facts | Schema evolution, privacy, replay, and debugging are hard |
| **Saga choreography** | Coordinates through events without a central controller | Flow and failure policy become hard to see |
| **Saga orchestration** | Centralizes process state and compensation decisions | The orchestrator becomes a critical domain component |
| **Transactional outbox** | Atomically stores state and an outgoing message | Relay lag and cleanup need operations |
| **Inbox/deduplication** | Makes message handling idempotent | Retention bounds determine duplicate protection |
| **Compensating transaction** | Semantically reverses completed work | Not every action is reversible |

## How to apply it

Use CQRS only when read/write needs truly diverge. Use event sourcing only when the event history itself is the authoritative business record. Model saga states, timeouts, retries, compensation, human intervention, and irreversibility. Keep the local state change and outbox record in one transaction.

## Evidence, not opinion

Test replay from version zero, upcasters, duplicate and reordered messages, timeout transitions, compensation failures, relay restart, and reconciliation against source systems.

## Small example

A travel booking saga reserves flight, then hotel, then payment. If hotel fails, it cancels the reversible flight hold. If refund needs manual review, the saga enters an explicit intervention state instead of pretending rollback succeeded.

## Feynman check

Explain the design to a new engineer without using the pattern names. State the
problem, the forces that conflict, the chosen boundary or mechanism, what can
fail, and the evidence that would prove the choice still works.
