Nguyen Le Phong

The Saga Pattern, or How to Undo Half a Checkout

A saga splits one business transaction into local steps, each with a way back.

Say you open the order dashboard after lunch and one row looks wrong. The payment went through. The stock reservation failed. The confirmation email went out anyway. Now support is asking a simple question nobody can answer quickly: does this customer own the product or not?

Nobody was careless. The checkout crossed four services, each with its own database, and no single transaction could cover all of them. That's the problem the Saga pattern exists for. Let's walk through one checkout step by step: where each step commits, how to undo it, and which order keeps the undo cheap.

Two teammates look at an order dashboard where one checkout stopped halfway after a step failed.
Paid, not reserved, email already sent: the kind of row a saga is there to prevent.

Why one transaction stops working

Inside one database, a transaction is a safety net: every write commits or none does. Once orders, payments and inventory each own their data, that net doesn't stretch across them. Two-phase commit exists, but it makes every participant wait on the slowest one and on the coordinator, which is exactly the coupling you split the services to get away from.

The alternative is older than microservices. In 1987, Hector Garcia-Molina and Kenneth Salem at Princeton proposed sagas for long-lived transactions that held database locks for hours (Sagas, SIGMOD 1987). A saga is a sequence of smaller transactions, and the system guarantees that either all of them complete or compensating transactions run to amend the partial execution. Chris Richardson later carried the idea over to microservices and defined a saga as "a reliably coordinated sequence of local transactions" (microservices.io).

One checkout, step by step

Each step commits in its own service and comes with a planned way back:

Step Service Local transaction Way back
1 Order Create the order as PENDING Mark it REJECTED
2 Payment Authorize the card (hold the money) Cancel the authorization
3 Inventory Reserve the items Release the reservation
4 Payment, Order Capture the money, mark the order CONFIRMED None: this is the point of no return
5 Notification, Shipping Send the email, request delivery None needed: retry until it succeeds

Look at step 2. Charging the card right away would turn the undo into a refund, which is messier for everyone. Card payments let you split authorization from capture: you hold the amount first and take it later. Stripe, for example, notes that an online card authorization is usually valid for 7 days, and canceling an uncaptured payment releases the hold (Stripe docs). Same business flow, much cheaper undo.

Put the point of no return late

Microsoft's saga guide sorts steps into three kinds (Saga design pattern):

  • Compensable steps can be undone by another transaction with the opposite effect.
  • The pivot is the point of no return. Once it succeeds, the saga has to run to the end.
  • Retryable steps come after the pivot. They're idempotent, so you can keep retrying them until they succeed.

This is the most useful design tool in the whole pattern. Anything you can't take back goes after the pivot. You can't unsend an email, so the confirmation goes out after the payment is captured, and never before the stock is reserved. That one reorder would have prevented the dashboard row at the top of this post.

Undo is rarely a clean rewind, either. A compensating transaction is a new business action with effects people can see: the order shows "Cancelled," the hold disappears from the customer's banking app. Microsoft also points out that compensating transactions can fail themselves, so they need retries too, plus an alert when the retries run out.

Orchestration or choreography

There are two ways to coordinate the steps. In choreography, each service publishes an event when it's done and the next service reacts: OrderCreated, then PaymentAuthorized, then StockReserved or StockReservationFailed. In orchestration, an orchestrator tells each participant what to do next and runs the compensations when a step fails. Microsoft's guide sums up the trade-offs like this:

Choreography Orchestration
Good fit Simple flows with few services Complex flows, or flows that keep gaining steps
Watch out for The full flow is hard to see, services can end up depending on each other in a cycle, and integration tests need every service running One more component to build and run, and it's a point of failure for the whole workflow

A practical test: which one can your team debug on an ordinary Tuesday afternoon, when one step failed and a customer is waiting? For a checkout with money in it, having the whole flow written down in one readable place is usually worth the extra component. Here's the core of an orchestrator, stripped to the bone:

type Step = {
  name: string;
  run: () => Promise<void>;
  compensate?: () => Promise<void>;
};

async function runSaga(steps: Step[]): Promise<void> {
  const done: Step[] = [];
  for (const step of steps) {
    try {
      await step.run();
      done.push(step);
    } catch (err) {
      for (const prev of done.reverse()) {
        await prev.compensate?.();
      }
      throw err;
    }
  }
}

A real orchestrator also saves its state after every step, so a restart in the middle of a saga picks up where it left off instead of forgetting it. A workflow engine can do that bookkeeping for you. The shape stays the same: run forward, and on failure walk back through what already succeeded.

Two engineers compare a hand-drawn service workflow next to a laptop while they discuss who coordinates each step.
Draw the forward path and the way back on the same page. If the way back is missing for a step, that step needs a decision.

The missing I in ACID

A saga gets you all-or-nothing in the end, after the compensations have run. It doesn't give you isolation. While one saga is halfway through, another can read its half-finished data. Microsoft lists the usual anomalies: lost updates, dirty reads, and fuzzy reads where two steps of one saga see different values. Richardson calls the fixes countermeasures: design techniques that bring back some of the isolation you lost.

The one you'll use most is a semantic lock, and you've already seen it: the PENDING status on the order. Other code knows a pending order isn't final, so it doesn't ship it, count it as revenue or let the customer edit it. Two more are worth knowing. Commutative updates give the same result in any order (adding 5 then subtracting 2 equals subtracting 2 then adding 5). And rereading a value right before you update it tells you whether someone changed it underneath you.

Richardson flags one more trap: each step must update its database and publish its message atomically, or the saga stalls and nobody notices. The outbox pattern is the usual answer.

Retries, duplicates and "where is this order now?"

Messages arrive twice. A timeout hides a step that actually succeeded. If the payment step runs twice because the orchestrator never saw the first reply, the customer must not be charged twice. Give each step a stable key (the saga ID plus the step name works), store the result the first time, and return that stored result on a repeat. Designing APIs That Survive the Second Click covers this in detail.

Then make the saga visible. Put the saga ID, current step, retry count and any compensation on every log line. Track how many sagas are stuck, how often compensation runs and which step fails most. A small admin page that answers "where is order 9001 right now?" will save support more time than any architecture diagram.

An engineer and an operations teammate check a timeline dashboard for a workflow that got stuck between services.
With a saga ID on every step, a stuck order becomes a timeline you can read, retry and explain to the customer.

When you don't need a saga

If the whole flow fits in one database, use one transaction and enjoy it. Splitting a checkout across services only to glue it back together with a saga is a lot of ceremony for nothing, and Microsoft's guide notes the pattern fits poorly when transactions are tightly coupled. Sagas earn their keep once services really do own separate data and the team has accepted that customers will see the final result a little after the click.

Try this week

  • Take one flow that crosses services and write its step table: the local transaction, the way back, and which step is the pivot.
  • Move every irreversible step (emails, shipping requests, partner webhooks) after the pivot.
  • Check whether your payment step charges the card or only authorizes it.
  • Add a count of stuck sagas to the on-call dashboard.

For how data ownership shapes all of this, see Who Owns the Data?.

What did you think?

Frequently asked questions

What is the Saga pattern?
A saga splits one business transaction that spans several services into a sequence of local transactions. Each one commits in its own service. If a later step fails, compensating transactions undo the earlier ones. Hector Garcia-Molina and Kenneth Salem introduced sagas in 1987, and Chris Richardson describes the microservices version on microservices.io.
What is a compensating transaction?
A new transaction with the opposite business effect of an earlier step, such as canceling a card authorization or releasing a stock reservation. It isn't a database rollback, its effects can be visible to the customer, and it can fail itself, so it needs retries and alerting.
What is a pivot transaction in a saga?
The point of no return. Steps before it can be compensated. Once the pivot succeeds, the saga must finish, and the steps after it should be idempotent so they can be retried until they succeed. Put irreversible actions such as sending emails after the pivot.
Should I use orchestration or choreography for a saga?
Choreography, where services react to each other's events, suits simple flows with few services. Orchestration, where a central orchestrator tells each service what to do, suits complex or growing flows and keeps the whole process readable in one place, at the cost of one more component to run.
Does a saga provide isolation like an ACID transaction?
No. Other code can see a saga's half-finished data, which can cause lost updates and dirty reads. Teams use countermeasures such as a semantic lock (a PENDING status other code respects), commutative updates and rereading a value before updating it.