What it is
A saga is a way to run a business transaction that spans several services, each with its own database, without a distributed transaction. The saga is a sequence of local transactions. Each one commits in its own service and triggers the next. If a step fails, the saga runs compensating transactions for the steps that already committed, undoing their business effect in reverse order.
Why it exists
In a microservice architecture each service owns its data. Placing an order may need Orders to store the order, Inventory to reserve stock and Payment to charge a card. With one database this would be one ACID transaction. Across services it cannot be:
- Two-phase commit (XA) needs every participant to support it, holds locks while waiting for the slowest participant, and blocks if the coordinator fails at the wrong moment. Most message brokers and many cloud databases do not support it, and it couples the availability of every service.
- Calling services one after another leaves earlier commits in place when a later call fails: the stock stays reserved for an order whose card was declined.
The saga accepts that each step commits on its own and makes undoing an explicit, designed part of the business process.
How it works
- Define the steps and their compensations. For the order: T1 create order
PENDING(compensation: reject order), T2 reserve stock (compensation: release stock), T3 charge card, T4 approve order. A compensation is a new business action, not a rollback; the rejected order still exists with statusREJECTED. - Coordinate. Either an orchestrator sends commands (
ReserveStock,ChargeCard) and reacts to replies, or services choreograph the saga by reacting to each other's events (OrderCreated→StockReserved→PaymentFailed). - On failure, compensate in reverse. If T3 fails, run release stock (undo T2), then reject order (undo T1). The failed step itself needs no compensation: its local transaction did not commit.
- Make it durable. The orchestrator stores the saga's state (a saga log) in its database after every step. Commands, replies and events are published via a transactional outbox, so a crash never loses a message, and participants deduplicate by saga or message id, because messages can arrive more than once.
- Order the steps. Compensatable steps first, then the pivot (the go/no-go step, here charging the card), then retriable steps that must eventually succeed and are retried rather than compensated.
When to use it
- A business process changes data owned by several services and must end consistent: orders, bookings (flight + hotel + car), account opening, fulfilment.
- Long-running processes that wait on people or external systems for minutes or days, where holding locks is impossible.
- When the domain has natural undo actions: cancel, refund, release, credit note.
When not to
- When the data could live in one service and one database: a local transaction is far simpler. Repeated sagas between the same two services often mean the boundary is wrong.
- When a step has no meaningful compensation and cannot be made the pivot or retriable (an email that must not be sent for a cancelled order belongs after the pivot).
- When strict isolation is a hard requirement (e.g. a balance that must never be observed in an intermediate state) and cannot be designed around.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Saga instead of 2PC | Services stay independent and available; no distributed locks | No isolation; compensations to write and test; eventual consistency |
| Orchestration | Whole flow in one place; easy to see, change, monitor and time out | A coordinator to run and keep durable; risk of a "god service" |
| Choreography | No coordinator; services only know events | Flow is implicit; hard to trace and change; cycles with many steps |
| Pivot ordering | Fewer compensations, clearer guarantees | Must analyse which step is riskiest and design retriable steps |
Alternatives
- One service, one database: redraw the boundary so the transaction is local.
- Two-phase commit where every participant supports it and the latency and blocking are acceptable (rare between microservices).
- Workflow engines (e.g. Temporal, AWS Step Functions, Camunda) as the orchestrator, which persist state, retry and time out for you.
- Reservation with expiry (hold stock for 15 minutes, release automatically), reducing the need for explicit compensation.
Failure modes
- Orchestrator crash mid-saga: without durable state the saga is stuck or repeated; with it, the orchestrator resends and participants must deduplicate.
- Lost messages: publishing commands or events next to a database write without an outbox loses them on crash.
- Duplicate messages: at-least-once delivery runs a step or compensation twice unless participants are idempotent.
- Failing compensation: a compensation must be retriable until it succeeds; if it keeps failing, park the saga and alert a human.
- Isolation anomalies: lost updates, dirty reads of reserved or pending data, and requests rejected for resources that are later released.
- Stuck sagas: a participant that never replies; set timeouts per step and compensate or escalate.
In production
Give every saga an id and carry it in every command, reply and event. Persist the saga state transition and the outgoing command in one transaction (outbox). Make each participant record processed message ids (inbox) so retries are safe. Model intermediate states explicitly (PENDING, RESERVED) and show them in the UI. Monitor sagas by state and age, alert on those stuck beyond a deadline, and keep an operator tool to retry or compensate manually. Prefer a workflow engine once flows have more than a few steps or need timers.
Common misconceptions
- "Compensation is a rollback." It is a new, committed business action, visible to everyone, and may itself fail and need retrying.
- "Choreography is more decoupled, so always better." It removes the coordinator but scatters the flow; for long sagas it is harder to change safely.
- "A saga gives ACID across services." It gives atomicity of the business outcome eventually (complete or compensated), not isolation.
- "Every step needs a compensation." Steps after the pivot are retriable instead; the failed step needs none.
Interview angle
When a design writes to several services in one user action, say there is no distributed transaction and propose a saga. List the steps with their compensations, pick orchestration or choreography and justify it, and place the pivot. Then cover reliability: saga state, outbox for messages, idempotent participants, timeouts for stuck steps. Mentioning the isolation problem and a countermeasure (pending states, semantic locks) shows depth.
Model assumptions
This lesson is a scripted illustration. Every command, reply and event is a hand-placed packet; the saga log, stock levels and order states are annotations. The queueing engine does not model transactions, commands, events, compensations or idempotency. The three services exist in the simulation only so that the orchestrator's crash and restart are real node state changes; no requests are simulated. Times are illustrative: about 20 ms between the shopper and Orders, 5 ms between services, 4 ms to the broker and 2 ms to each service's database.