Course contents

11. Microservices Lesson 7 of 10

Saga Pattern

Watch a business transaction span three services as local steps with compensations, orchestrated or choreographed, and see where sagas lose isolation.

16 minAdvanced8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Services own their data, so there is no transaction across them; a later failure leaves earlier commits in place.
  • A saga is a sequence of local transactions; each compensatable step has a compensating action, run in reverse on failure.
  • An orchestrator centralises the flow and its state; choreography chains steps through events with no coordinator.
  • Sagas have no isolation: intermediate states are visible. Use pending states, commutative updates and a deliberate pivot.
  • Persist saga state, publish via an outbox, and make every participant idempotent so resends after crashes are safe.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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

  1. 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 status REJECTED.
  2. 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).
  3. 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.
  4. 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.
  5. 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.

The lesson as textEvery step of the simulation, written out.
  1. 1. One order, three databases

    Placing an order touches three services, and each owns its own database: Orders stores the order, Inventory reserves the stock, Payment charges the card. There is no transaction that spans all three. Two-phase commit across services is rarely available and would make every service wait on the slowest and least available one.

    So the naive code just calls them in turn. Here the order row is committed, the stock is reserved and committed, and then the card is declined. Nothing undoes the first two: the stock stays reserved for an order that will never ship. *Scripted illustration.*

    Scene: Orders writes the order, Inventory reserves and commits the stock, then Payment declines the card. The order and the stock reservation remain committed with nothing to undo them.

    Key idea: Across services there is no shared ACID transaction: a later failure leaves earlier commits in place.

  2. 2. A saga: local transactions in sequence

    A saga splits the business transaction into local transactions, one per service, each committed on its own, and pairs each one that may need undoing with a compensating transaction:

    T1 create order PENDING (undo: reject order) · T2 reserve stock (undo: release stock) · T3 charge card · T4 approve order.

    Here an orchestrator in Orders drives the saga. It commits T1, tells the shopper the order was received, then sends a ReserveStock command, waits for the reply, sends ChargeCard, and finally approves the order. It records each step in its saga log, so it always knows where the saga is. *Scripted illustration.*

    Scene: Orders creates the order as pending and answers the shopper, then sends a reserve-stock command to Inventory and a charge command to Payment, waiting for each reply, and finally approves the order in its database.

    Key idea: A saga is a sequence of local transactions, each with a compensating action, driven here by an orchestrator.

  3. 3. A step fails: compensate in reverse

    Same saga, but the card is declined at T3. The orchestrator does not roll anything back (each step is already committed); it runs the compensating transactions in reverse order: ReleaseStock undoes T2 in Inventory, then reject order undoes T1 in Orders.

    Payment needs no compensation: its own local transaction failed, so there is nothing to undo. Compensations are new business actions, not database rollbacks: the order ends up REJECTED, not deleted, and anyone who saw the reservation saw a real, briefly true state. *Scripted illustration.*

    Scene: Inventory reserves stock, then Payment declines the card. The orchestrator sends a release-stock command to Inventory, waits for its reply, and then marks the order as rejected in its own database.

    Key idea: Sagas undo by compensating: semantic “undo” actions, run in reverse order for the steps that completed.

  4. 4. The orchestrator crashes mid-saga

    The orchestrator sends ChargeCard for saga #41 and crashes. Payment charges the card and replies, but no one is listening.

    On restart the orchestrator reads its saga log from the database: #41 was waiting for ChargeCard. It sends the command again, with the same saga id. Payment looks the id up, finds it already charged, and returns the stored result instead of charging twice. The saga then approves the order. Durable saga state plus idempotent participants make crashes survivable; commands and replies are published through an outbox so none are lost. *Scripted illustration.*

    Scene: Orders sends a charge command and then goes offline; Payment charges and replies to no one. Orders restarts, reads the saga state, and sends the same charge command again; Payment finds it already processed and returns the earlier result, and Orders approves the order.

    Key idea: Persist the saga state, resend after a crash, and make every participant idempotent by saga id.

  5. 5. Choreography: no one in charge

    The same saga can run without an orchestrator. In choreography each service publishes an event after its local transaction, and the next service reacts to it: OrderCreated → Inventory reserves → StockReserved → Payment charges → PaymentFailed. Both Inventory and Orders listen for PaymentFailed: Inventory releases the stock, Orders rejects the order.

    No central coordinator, and services only know events, not each other. But the flow exists only in the sum of the subscriptions: harder to see, test and change, and with many steps the event web can grow cycles. Choreography fits short sagas; orchestration fits long or frequently changing ones. *Scripted illustration.*

    Scene: Orders publishes OrderCreated to the broker; Inventory reserves stock and publishes StockReserved; Payment fails and publishes PaymentFailed, which the broker delivers to both Inventory, which releases the stock, and Orders, which rejects the order.

    Key idea: Choreography chains local transactions through events; orchestration centralises the flow in one place.

  6. 6. Others see the half-finished saga

    A saga commits step by step, so it has no isolation: other requests see its intermediate state. Saga #41 holds the last unit of a product while its payment is still pending. Order #42 arrives, Inventory finds stock 0 and publishes OutOfStock: #42 is rejected. Moments later #41’s payment fails and the stock is released. #42 was turned away for stock that came back.

    Countermeasures: a semantic lock (mark records PENDING so others know they may change), keep reserved separate from sold, use commutative updates (add/subtract rather than overwrite), re-read and version-check before acting, and order steps so the riskiest ones run first. *Scripted illustration.*

    Scene: OrderCreated for order 42 reaches Inventory, which finds no stock and publishes OutOfStock. Then saga 41’s PaymentFailed arrives and Inventory releases the unit that order 42 could have had.

    Key idea: Sagas trade isolation for availability; design for visible intermediate states with semantic locks and careful step order.

  7. 7. After the pivot, only forward

    Order the steps deliberately. Compensatable steps come first (create order, reserve stock). Then the pivot: the go/no-go step after which the saga must complete; here, charging the card. Steps after it are retriable: they are designed to succeed eventually and are never compensated.

    Payment succeeds; Orders tries to approve the order and hits a transient database error. It does not refund the card; it retries until the approval commits. Put the step most likely to fail at or before the pivot, and make everything after it idempotent and retryable. *Scripted illustration.*

    Scene: Payment publishes PaymentSucceeded and Orders tries to approve the order; the database returns an error, Orders waits briefly and retries, and the approval succeeds. No compensation runs.

    Key idea: Compensatable steps, then one pivot, then retriable steps that only move forward.

  8. 8. What a saga gives you

    A saga replaces one distributed transaction with local transactions and compensations. It keeps services independent and available, and it guarantees that the business process eventually either completes or is semantically undone.

    In exchange you give up isolation, write compensations for every compensatable step, persist saga state, make every participant idempotent, publish commands and events reliably (outbox), and monitor sagas that get stuck. Choose orchestration for long or changing flows, choreography for short ones.

    Scene: Orders, Inventory and Payment each own a database and coordinate the order saga through the event broker.

    Key idea: Saga = local transactions + compensations + durable state + idempotent, reliably messaged participants.