Course map

Topic 139 / Advanced

Saga pattern and compensating transactions

Chapter 8.5 · Locks, Transactions, and Sagas

What and why

Two-phase commit (→ 138) makes every participant wait on one coordinator's final decision, which blocks real work across service boundaries when that coordinator is slow or down. The saga pattern avoids holding any cross-service lock at all: a saga is a sequence of local transactions, each committing immediately in its own service, where every step that needs undoing has a paired compensating action that semantically reverses it if a later step fails. A saga is not atomic in the ACID sense: intermediate states are genuinely visible to the rest of the system while it's in progress, and compensations are real business operations (refund, release, cancel), not an automatic rollback. Builds on: → 138 (distributed transactions and two-phase commit).

Diagram

Saga forward steps and compensating transactions Forward: reserve inventory, then charge payment, then create shipment. Compensating: release inventory and refund payment, running in reverse order if a later step fails. Forward: Compensating: reserve inventory charge payment create shipment release inventory refund payment (runs if a later step fails)
Choreography: each service publishes an event when its step completes or fails and the next service reacts directly — no central coordinator. Orchestration: a coordinator explicitly calls each step and decides, on failure, which compensations to run and in what order.
Text version of this diagram
Forward:      reserve inventory → charge payment → create shipment
                     │                  │
Compensating: release inventory ← refund payment
              (runs if a later step fails)

How it works

  1. Break the operation into local transactions, each owned by one service and fully committed — no locks held across services — before the next step starts.
  2. For every step with a real-world effect, define a compensating action that undoes it in meaning, not necessarily by reversing the database write (a refund is a new transaction, not deleting the charge).
  3. If a step fails, run the compensating actions for every already-completed prior step, typically in reverse order, so the saga ends undone rather than partially applied.
  4. Choreography: each service publishes an event when its step completes or fails, and the next service(s) react directly — decentralized, no single coordinator, but the overall flow is only visible by tracing events across services.
  5. Orchestration: a central coordinator (→ 122, workflow orchestration) explicitly calls each step and decides, on failure, which compensations to run and in what order — visible in one place, at the cost of that coordinator becoming a dependency (though, unlike 2PC's coordinator, a slow orchestrator delays the saga; it doesn't hold anyone else's locks).
  6. Design compensations alongside the forward path: a compensation (e.g., "release the inventory hold") must itself be idempotent and safe to run even if the forward step partially succeeded (→ 116) — retries and failures on the compensating path are just as real as on the forward one.

Practical example

(illustrative). An order saga: reserve inventory (step 1) → charge payment (step 2) → create shipment (step 3). If step 2 fails after step 1 succeeded, the saga runs step 1's compensation — release the inventory reservation — and the order ends cancelled. Between steps 1 and 2, the inventory system genuinely shows the item as reserved to any other process checking stock — a normal, visible intermediate state, not a bug to eliminate.

When to use it

  • Use when: a business operation spans multiple services and needs a defined, business-meaningful way to undo partial progress (Projects 8 and 15).
  • Avoid when: everything fits in one database — a local transaction (→ 70) gives true atomicity and isolation for free, with no visible intermediate state and no compensations to design.
  • Failure scenarios: a compensating action that isn't idempotent, so a retried compensation double-refunds or double-releases; a step with no reasonable compensation at all (an email already sent, a non-refundable charge already settled) — design around this by ordering irreversible steps last; an orchestrator failure mid-saga leaving the saga's state unclear until recovered from a durable log of completed steps.
  • Simpler alternative: a single database transaction, whenever the data actually lives in one place — reach for a saga only once the operation genuinely crosses service and database boundaries.

Practice

(Pattern kind — implement minimal, spot the misuse; 20–30 min, no lab services, any language). Model the order saga above as a small state machine with 3 forward steps and 2 compensations. Simulate a failure at step 2 and trace which compensations run, in what order. Then spot the misuse: make the inventory-release compensation non-idempotent (running it twice double-increments stock), show the bug by simulating a retried compensation after a timeout, then fix it by making the release a no-op if the reservation is already gone. Done when the double-increment is reproduced, then shown gone after the fix.

Key takeaway

A saga trades 2PC's cross-service blocking for visible intermediate states and explicit, business-meaningful compensations — correctness comes from designing those compensations alongside the forward path, not from infrastructure. Done when you can: design a 3+ step saga with correct, idempotent compensations and state which step, if any, can't be compensated. Used next in → 140; Projects 8, 15.

References

Kleppmann and Riccomini, Designing Data-Intensive Applications — see references.md.

Source directory

Search the guide