Module 5 · Distributed systemsLesson 56 of 887 minAdvanced
The saga pattern
A saga splits a long action into local steps, and if one step fails, it runs undo steps for the ones before it.
Run the happy path, then "Failure + undo" and watch the compensations run in reverse order.
A saga is a sequence of local transactions, one per service. Each step has a compensating action that semantically undoes it:
| Step | Compensation |
|---|---|
| Create order (pending) | Cancel order |
| Charge card | Refund card |
| Reserve stock | Release stock |
If step 3 fails, the saga runs the compensations for steps 2 and 1, in reverse order.
Two styles
Orchestration: one orchestrator (a service or a workflow engine) tells each service what to do next and handles failures. Easy to see the whole flow in one place. Tools: Temporal, AWS Step Functions, Camunda.
Choreography: no central brain. Each service listens for events and reacts: OrderCreated triggers payment, PaymentSucceeded triggers inventory, StockFailed triggers a refund. Loosely coupled, but the flow is spread across services and harder to follow.
Things to design for
- No isolation: other requests can see the in-between state ("pending" orders, a charge that will be refunded). Use clear statuses and show them honestly in the UI.
- Compensations can't always undo: you can't unsend an email. Order steps so the hard-to-undo ones come last, or use soft actions ("reserve" before "commit").
- Idempotency: steps and compensations may be retried, so both must be safe to repeat.
- Reliable messaging: use the outbox pattern so a service never commits a step without the next message being sent.
- Timeouts: if a step never answers, the orchestrator must decide to retry or compensate.
Sagas trade instant all-or-nothing for availability and loose coupling, which is the right trade for most business workflows between services.