AlgoViz

Saga pattern

medium 30 min

A saga is a chain of local transactions, one per service, with an undo step for each.

Video lesson · Chapter 1 of 5

An order crosses three owners

0:00 / 4:24

Theory

Read or listen first. About 2 min.

What it is

When one database holds everything, a transaction makes several changes succeed or fail together. When each service has its own database, no single transaction covers them all. A saga replaces that one transaction by a sequence of local transactions. Each one commits in its own service and triggers the next.

If a step fails, the saga does not roll back, because the earlier steps are already committed. It runs compensating transactions: new changes that undo the meaning of the old ones, such as a refund for a charge. A one-line version: a chain of local transactions with an undo button for each step.

Why it exists

Holding locks in several databases until everybody agrees is slow, and it stops everyone when one participant is down. A business process may also last minutes or days, and no database should hold locks for that long.

A saga lets every service commit at once and move on. The price is isolation: other requests can see a half-finished order, and you must design what undo means for each step.

A short history

  1. 1978

    Jim Gray's lecture notes on database operating systems describe two-phase commit, the locking way to make several databases agree.

  2. 1987

    Hector Garcia-Molina and Kenneth Salem publish "Sagas". They split a long-lived transaction into a sequence of smaller ones that can be interleaved with others, with compensating transactions to amend a partial run.

  3. December 2016

    AWS announces Step Functions, a managed workflow service. AWS guidance later uses it to show saga orchestration.

Words to know

Local transaction
An ordinary ACID transaction inside one service and its database.
Compensation
A new transaction that undoes the business meaning of a committed step.
Orchestration
One coordinator tells each service what to do next.
Choreography
No coordinator: services react to one another's events.
Pivot
The point of no return. After it, steps are retried until they succeed.
Semantic lock
A status such as PENDING that tells others a saga is still working on this row.
Correlation id
One id carried by every message of a saga, so its steps can be found.

How it works

Step through the idea, or press Play.

Step 1 of 3

Do one local transaction. Commit in one service, then trigger the next

Understand it

Start here

Booking a picnic

Noor plans a picnic by making three bookings with three different people: the meadow, the food basket and the boat. Nobody can book all three at once. If the last booking fails, Noor must cancel the others.

A picnic, booked and unbooked
Picnic listMeadowBasketBoatMeadow booked

The boat needs no undo, because it was never booked.

The idea

Steps and their undo buttons

Forward, then backward

The failed step has no effect of its own, so undo starts with the last step that finished.

An order saga

StepDoesCompensation
T1Create orderCancel order
T2Reserve stockRelease stock
T3Charge paymentRefund
T4Ship orderCancel shipment, or ask for a return
  • Local transactions

    Each step is ACID inside its own service.

  • Compensation

    Every step that may be undone has an undo action.

  • Eventual consistency

    The services agree in the end, not at every moment.

  • Two approaches

    Orchestration with a coordinator, or choreography with events.

  • State tracking

    Progress is saved, so a restart continues from the right step.

  • Idempotency

    Any step can be repeated safely, because messages repeat.

Approach 1

Orchestration

One orchestrator sends a command to each participant, waits for the reply, and decides what comes next. It also decides when to compensate. The participants know nothing about one another.

One coordinator, three services

A client calls the order saga orchestrator, which stores its progress in a saga log. The orchestrator sends commands to the order, inventory and payment services. Each service is a separate box holding its own database.
Every service keeps its own database. Only the orchestrator knows the whole flow.

A successful order

The order stays PENDING until the last step confirms it.

Advantages

  • The flow is easy to read in one place
  • Error handling is central
  • Adding or removing a step is simple
  • Saga state is easy to see

Disadvantages

  • A single point of failure unless its state is durable and it runs as several copies
  • It can become a bottleneck
  • Participants are tied to the coordinator's commands
  • One more thing to run

Approach 2

Choreography

There is no coordinator. Each service publishes an event after its commit, and others react. It is like dancers who follow the music without a conductor.

Services and an event broker

Order, inventory and payment services each sit in their own box with their own database. All three exchange events with one event broker in the middle; there is no coordinator.
Nobody owns the flow. It exists only as the sum of the reactions.

The event chain

FromEventWho reacts
OrdersOrderCreatedInventory reserves
InventoryInventoryReservedPayments charges
PaymentsPaymentCompletedOrders confirms
OrdersOrderConfirmedNotifications tells the customer
PaymentsPaymentFailedInventory releases, Orders cancels
InventoryInventoryFailedOrders cancels

Advantages

  • No coordinator to fail, though the broker must be highly available
  • Loose coupling between services
  • Each service is autonomous
  • A new listener can join without changing the others

Disadvantages

  • The overall flow is hard to understand
  • Debugging crosses many services
  • Services can end up waiting on one another in a cycle
  • No central view unless you build one

Choose

Which approach?

Orchestrate or choreograph

A team may use both: events between departments, and an orchestrator inside one of them. Just do not drive one step from both sides.

Undo

Compensation is not rollback

A rollback makes a change vanish before anybody sees it. A compensation is a new transaction that reverses the meaning of one that everybody could already see. You charged 100 dollars, so you refund 100 dollars. The statement shows both lines.

What undo means

ActionCompensationNote
Create orderCancel orderMark as cancelled, do not delete
Reserve inventoryRelease inventoryGive back the same reservation, once
Charge paymentRefund paymentA new refund transaction
Send emailSend an apologyIt cannot be unsent
Ship packageAsk for a returnSome actions cannot be undone

Four rules

  1. 1

    Make it idempotent

    It may run twice. See idempotency.

  2. 2

    Undo in reverse order

    Start with the last finished step. Independent steps may be undone together.

  3. 3

    Plan for what cannot be undone

    Put emails and shipping after the pivot, so that nothing behind them can fail for a business reason.

  4. 4

    Expect a compensation to fail

    Retry with backoff, then raise an alert for a person. Never swallow the error.

Order of steps

Compensable, pivot, retryable

Sort the steps into three groups. Compensable steps come first. The pivot is the decision: once it succeeds, there is no way back. Retryable steps follow. They must not be refused for a business reason, so you repeat them until they work.

The point of no return

Do the risky step as late as possible, and the unfixable steps after it.

Isolation

What others see in between

A saga keeps atomicity, consistency and durability in a loose, eventual form, but it has no isolation. Another request may read a pending order, or overwrite a row that the saga later undoes. Compare it with the I in ACID.

Countermeasures

NameWhat you doExample
Semantic lockMark the row as busyOrder status PENDING blocks a second cancel
Commutative updatesMake updates work in any orderAdd and subtract instead of set
Pessimistic viewReorder steps to lower the riskRaise the credit limit last
Reread valueCheck it did not change before writingCompare a version number
Version fileRecord operations and reorder themCancel arrives before authorise
By valueChoose the method by business riskTwo-phase commit for very large sums

Build it

Implementation checklist

  1. 1

    Define the steps

    One local transaction per service.

  2. 2

    Design the compensations

    Write down what undo means for each step, with the business team.

  3. 3

    Make steps idempotent

    Use the saga id plus the step name as the key, and check it before acting.

  4. 4

    Track the state

    Save "step started" before the call and "step done" after it.

  5. 5

    Handle timeouts

    No answer does not mean no effect. Retry or ask for the status; undo as if it may have happened.

  6. 6

    Test failures

    Break every step, and crash the orchestrator between every pair of steps.

States of one saga

Alert on STUCK, and on any saga that stays RUNNING too long.

Numbers

How often will it undo?

Success of a chain

P=p n=0.994≈0.96061,000,000×(1−0.9606)≈39,400P = p^{\,n} = 0.99^{4} \approx 0.9606 \qquad 1{,}000{,}000 \times (1 - 0.9606) \approx 39{,}400
Assume 4 independent steps that each succeed 99% of the time, and a million sagas a day. Then about 39,400 sagas a day fail somewhere. Compensation is a normal path, not a rare one.

Load on the saga log

1,000,00086,400≈12 sagas/s12×4×2=96 writes/s96×3=288 at peak\frac{1{,}000{,}000}{86{,}400} \approx 12\ \text{sagas/s} \qquad 12 \times 4 \times 2 = 96\ \text{writes/s} \qquad 96 \times 3 = 288\ \text{at peak}
Two log writes per step, and peak is 3 times the average. One database is enough.

Compare

Saga or two-phase commit?

SagaTwo-phase commit
LocksOnly inside each local transactionHeld until the decision arrives
Others seeSteps in betweenNothing until commit, for the locked rows
UndoYour codeThe database
One service downThe saga waits or compensatesThe transaction blocks or aborts
Good forLong processes over servicesShort work over a few databases
More in two-stage processing and microservice communication. The need for both starts with a database per service.

Do

  • Make all steps idempotent
  • Save saga state for recovery
  • Design compensations with care
  • Carry a correlation id
  • Test failure scenarios

Do not

  • Assume that compensations always succeed
  • Ignore timeouts
  • Create circular dependencies
  • Drive one step both by commands and by events
  • Forget about partial failures

Summary

The whole topic in one minute.

A saga turns one business transaction into local transactions in order: T1, T2, T3. Each compensable step has an undo. On failure the finished steps are compensated, newest first.

Drive it with an orchestrator when the flow is complex or must be visible, or with events when it is short. Make every step and every compensation idempotent, save the saga's state before acting, set timeouts, and plan for a compensation that fails. Remember what you gave up: a saga is atomic in the end, but it is not isolated.

  • A saga is a sequence of local transactions with compensations.
  • Orchestration has a coordinator; choreography has events.
  • Compensate finished steps in reverse order, with idempotent actions.
  • Put the pivot late, and retry everything after it.
  • Sagas are not isolated: use semantic locks and other countermeasures.

Sources