Saga pattern
medium 30 minA 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
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
1978
Jim Gray's lecture notes on database operating systems describe two-phase commit, the locking way to make several databases agree.
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.
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.
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.
The boat needs no undo, because it was never booked.
The idea
Steps and their undo buttons
Forward, then backward
An order saga
| Step | Does | Compensation |
|---|---|---|
| T1 | Create order | Cancel order |
| T2 | Reserve stock | Release stock |
| T3 | Charge payment | Refund |
| T4 | Ship order | Cancel 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 successful order
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
The event chain
| From | Event | Who reacts |
|---|---|---|
| Orders | OrderCreated | Inventory reserves |
| Inventory | InventoryReserved | Payments charges |
| Payments | PaymentCompleted | Orders confirms |
| Orders | OrderConfirmed | Notifications tells the customer |
| Payments | PaymentFailed | Inventory releases, Orders cancels |
| Inventory | InventoryFailed | Orders 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
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
| Action | Compensation | Note |
|---|---|---|
| Create order | Cancel order | Mark as cancelled, do not delete |
| Reserve inventory | Release inventory | Give back the same reservation, once |
| Charge payment | Refund payment | A new refund transaction |
| Send email | Send an apology | It cannot be unsent |
| Ship package | Ask for a return | Some actions cannot be undone |
Four rules
- 1
Make it idempotent
It may run twice. See idempotency.
- 2
Undo in reverse order
Start with the last finished step. Independent steps may be undone together.
- 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
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
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
| Name | What you do | Example |
|---|---|---|
| Semantic lock | Mark the row as busy | Order status PENDING blocks a second cancel |
| Commutative updates | Make updates work in any order | Add and subtract instead of set |
| Pessimistic view | Reorder steps to lower the risk | Raise the credit limit last |
| Reread value | Check it did not change before writing | Compare a version number |
| Version file | Record operations and reorder them | Cancel arrives before authorise |
| By value | Choose the method by business risk | Two-phase commit for very large sums |
Build it
Implementation checklist
- 1
Define the steps
One local transaction per service.
- 2
Design the compensations
Write down what undo means for each step, with the business team.
- 3
Make steps idempotent
Use the saga id plus the step name as the key, and check it before acting.
- 4
Track the state
Save "step started" before the call and "step done" after it.
- 5
Handle timeouts
No answer does not mean no effect. Retry or ask for the status; undo as if it may have happened.
- 6
Test failures
Break every step, and crash the orchestrator between every pair of steps.
States of one saga
Numbers
How often will it undo?
Success of a chain
Load on the saga log
Compare
Saga or two-phase commit?
| Saga | Two-phase commit | |
|---|---|---|
| Locks | Only inside each local transaction | Held until the decision arrives |
| Others see | Steps in between | Nothing until commit, for the locked rows |
| Undo | Your code | The database |
| One service down | The saga waits or compensates | The transaction blocks or aborts |
| Good for | Long processes over services | Short work over a few databases |
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.