How-To Guide

How to Implement the Saga Pattern

Coordinate a distributed transaction with a saga: run local steps, compensate on failure, and make each step and compensation idempotent.

On this page

  1. Introduction
  2. Break the transaction into local steps
  3. Define a compensation per step
  4. Run the steps and compensate on failure
  5. Make the steps and compensations idempotent
  6. Choose orchestration or choreography
  7. Test the success, the failure, and the retry
  8. Common pitfalls
  9. Conclusion

Introduction

A business transaction that spans several services cannot use a single database transaction: each service has its own database, and a distributed transaction that holds locks across them is fragile and reduces availability. The saga pattern breaks the transaction into a sequence of local transactions, one per service, and defines a compensating action for each. If a later step fails, the compensations for the earlier steps run in reverse, undoing the partial work.

This tutorial implements a saga: break the transaction into local steps, define a compensation per step, run the steps and compensate on failure, and make the steps idempotent. The examples use a cross-service order flow, and the pattern applies to any process that touches several services.

Break the transaction into local steps

Split the cross-service work into a sequence of steps, each a local transaction in one service that commits on its own. An order flow might be: create the order in the order service, reserve the stock in the inventory service, charge the payment in the payment service, and confirm the order. Each step is a local transaction with its own commit, and the sequence is coordinated by messages or an orchestrator.

Define the sequence and the failure points. Each step can fail, and the saga must handle each failure by compensating the steps already completed. The sequence is the plan, and the compensations are the plan for failure. A saga without defined compensations cannot recover, and a partial state persists.

# saga: order flow across services
1. order.create        (order service)      -> comp: order.cancel
2. inventory.reserve   (inventory service)  -> comp: inventory.release
3. payment.charge      (payment service)    -> comp: payment.refund
4. order.confirm       (order service)
# if step 3 fails, run comp 2 then comp 1, in reverse

Define a compensation per step

A compensation is a new action that reverses the effect of a completed step, not a database rollback. Charging a payment is compensated by refunding it; reserving stock is compensated by releasing it; creating an order is compensated by cancelling it. Define each compensation as a normal operation with its own logic, because it has to reverse a committed effect.

Some steps cannot be compensated, such as sending an email or an irreversible external effect. For those, order the steps so the irreversible ones come last, after the compensable ones, so a failure before them can still roll back. This is the saga’s design constraint: put the point of no return at the end, and keep the earlier steps compensable.

Run the steps and compensate on failure

Run the steps in order. When a step fails, run the compensations for the completed steps in reverse order, each compensation itself retried until it succeeds or a policy decides it cannot. The saga then ends in a consistent state: either all the steps applied, or the completed ones compensated. The reverse order matters, because a later step may depend on an earlier one.

Persist the saga’s state so a crash does not lose the progress. Store the saga’s current step and its status in a durable store, so a restart resumes from the last completed step and runs the compensations for the rest. The saga’s progress is itself state that must survive a crash, which is why it is persisted and not held only in memory.

# on failure at step 3:
compensate step 2 (inventory.release)
compensate step 1 (order.cancel)
# persist the saga state so a crash resumes from the last completed step

Make the steps and compensations idempotent

A saga’s messages can be redelivered and its steps retried, so each step and each compensation must be idempotent: applying it twice has the same effect as once. An idempotency key on the charge prevents a double charge, and a check on the reservation prevents a double reserve. Without idempotency, a retry of a step or a redelivery of a compensation double-applies, and the saga ends in a wrong state.

Idempotency is what makes the saga safe across a failure. A step that times out may have applied, so the saga retries it, and the retry must not double-apply. A compensation that is redelivered must not reverse twice. Design each step with an idempotency key or a state check, so a repeat is a no-op, and the saga can be retried without fear.

async function charge(paymentId, amount, idempotencyKey) {
  const existing = await store.get(idempotencyKey);
  if (existing) return existing;                 // the retry is a no-op
  const result = await paymentProvider.charge(amount);
  await store.set(idempotencyKey, result);
  return result;
}

Choose orchestration or choreography

A saga is coordinated either by an orchestrator or by choreography. In orchestration, a central saga object runs the steps and the compensations in order, which makes the flow visible in one place and is easier to reason about and to debug. In choreography, each service listens for the events and decides what to do next, which decouples the services but scatters the flow across them.

Orchestration suits a complex flow with many steps and compensations, because the sequence is in one place. Choreography suits a simpler flow with few participants, because it avoids the central component. Both need the idempotent steps and the persisted state; the choice is about where the sequence lives, not about the safety.

Test the success, the failure, and the retry

Test the happy path, where all the steps apply. Test a failure at each step and assert the compensations run in reverse for the completed steps, leaving the system consistent. Test that a redelivered step does not double-apply, by sending the same message twice and asserting one effect. Test that a crash mid-saga resumes and completes the compensations, by killing the process and restarting.

# force a failure at the payment step and assert the compensations
node scripts/run-saga.mjs --fail-at payment
# assert: inventory released, order cancelled, no charge applied

Common pitfalls

A step with no compensation, so a failure leaves a partial state, an irreversible step before the compensable ones, steps and compensations that are not idempotent so a retry double-applies, the saga state only in memory so a crash loses the progress, and compensations run in the wrong order are the recurring mistakes. A compensation per step, the irreversible steps last, idempotency keys, a persisted saga state, and reverse-order compensations address them.

Conclusion

A saga coordinates a distributed transaction with local steps and compensations. Break the work into local steps, define a compensation per step and put the irreversible last, run the compensations in reverse on failure, make every step and compensation idempotent, and persist the saga state. Self-check by forcing a failure at each step and asserting the compensations run in reverse, and by redelivering a step and asserting no double-apply. Then a cross-service transaction ends consistent even when a step fails.

Sources: Microservices.io: Saga pattern, Chris Richardson: Saga pattern (book), AWS: Saga orchestration pattern.

FAQ

Why not a two-phase commit?
A two-phase commit needs every participant to hold locks and coordinate, which is fragile across services and does not scale with availability. A saga uses local transactions and compensations, so each service commits locally and the coordination is by messages, which tolerates a slow or failed participant.
What is the difference between a compensation and a rollback?
A rollback undoes a transaction that has not committed; a compensation is a new action that reverses the effect of a committed step, such as issuing a refund for a charge. It is not a database rollback, so it must be a defined action and must be idempotent.

Related Examples