The Saga pattern: how to “undo” a purchase that went through four microservices
When an order crosses several services, each with its own database, there is no single ROLLBACK. A saga replaces the one giant transaction with a sequence of local transactions, each with a way to be undone.
Step by step
- Order #1042
- —
- FONE-X stock
- 10
- Ana’s balance
- R$ 120
- Delivery
- —
Step 1 of 10
Ana buys 2 headphones at R$ 150
Order #1042 reaches the saga orchestrator. Each service has its own database, so there is no BEGIN … COMMIT that spans all four.
Ana buys 2 headphones at $150 each
In a store that is still a monolith, Ana’s order #1042 is a single transaction in the application’s single database:
BEGIN; INSERT INTO orders (id, customer, total, status) VALUES (1042, 'ana', 300, 'APPROVED'); UPDATE inventory SET qty = qty - 2 WHERE sku = 'PHONE-X'; UPDATE wallets SET balance = balance - 300 WHERE customer = 'ana'; INSERT INTO shipments (order_id) VALUES (1042); COMMIT; -- if any line fails: ROLLBACK and nothing happened
That is the ACID guarantee: either all four changes happen, or none do. If Ana’s balance does not cover $300, the database undoes everything on its own.
Now the store grows and gets split into microservices: Orders, Inventory, Payments and Shipping, each with its own database (the Database per Service pattern). The four lines above now live in four different databases.
The payment fails at step three, and the first two steps are already saved
Each service runs its own COMMIT on its own database, one after the other:
If there were 10 headphones in stock, the store now shows 8 available, even though nobody bought anything. Ana sees an order “processing” that never finishes. Multiply that by thousands of orders a day.
No transaction can span four databases
Payments’ ROLLBACK only undoes what the Payments database did. The COMMITs in Orders and Inventory are already final in their own databases. The ACID guarantee belonged to one database; by splitting the data, we lost atomicity across them.
The classic way out would be a distributed transaction (two-phase commit, 2PC): a coordinator locks all four databases and only commits once every one of them votes “yes”. In microservices that is usually not an option: it requires every database and the message broker to support 2PC, and they all stay blocked waiting for the slowest one. Chris Richardson sums up the constraint in one sentence: “2PC is not an option.”
So the real problem is: how do you keep data consistent across services without a distributed transaction?
Saga
A saga is a sequence of local transactions (each one in a single service, with normal ACID inside it) in which every step that may need to be undone has a compensating transaction that applies the opposite effect. If a step fails, the saga runs the compensations of the steps already completed, from the last to the first.
The term comes from the paper “Sagas” by Hector Garcia-Molina and Kenneth Salem (ACM SIGMOD, 1987), written about long-lived transactions inside a single database. Microservices inherited the idea because they have the same problem for a different reason: you cannot hold one single transaction open.
The key idea
You don’t undo the past with ROLLBACK; you write a new fact that cancels it (“release the 2 headphones”, “cancel order #1042”). Consistency stops being immediate and becomes eventual: there is a window in which the databases disagree, and the saga guarantees that window ends.
Steps, compensations and a point of no return
1 · Every step gets its “undo”
This removes the stuck stock and the order that never ends: when Payments declines, the saga runs C2 and C1.
2 · Classify each step by what happens if it goes wrong
Not every step can be undone (a sent email doesn’t come back). That is why the saga splits transactions into three kinds, and their order matters:
| Kind | What it is | In order #1042 |
|---|---|---|
| compensable | Can be cancelled by another transaction with the opposite effect. | T1 create order, T2 reserve headphones |
| pivot | The point of no return: if it commits, the saga runs to the end; if it fails, the saga compensates. | T3 charge $300 |
| retryable | Comes after the pivot and is idempotent: if it fails, it is retried until it succeeds. | T4 schedule shipping, send email |
This removes the risk of getting stuck halfway with no way back: everything irreversible sits at the pivot or after it, where the saga only moves forward.
3 · Decide who drives the sequence
Someone has to know that T3 comes after T2, and that a decline at T3 triggers C2 and C1. There are two ways:
| Choreography | Orchestration | |
|---|---|---|
| How it works | Each service publishes events and reacts to the others’ events; there is no central controller. | An orchestrator sends commands to each service, receives the replies and decides the next step or the compensations. |
| Benefits | No extra service to maintain; no single point of failure; good for simple flows with few services. | The whole flow is in one place; avoids cyclic dependencies; good for complex flows. |
| Drawbacks | Gets confusing as you add steps (the flow is spread out); risk of cycles between services; hard to integration-test. | One more piece with coordination logic; the orchestrator becomes a point of failure. |
Choreography is where the saga meets Event-Driven Architecture (EDA): the steps are chained by events on a message broker.
4 · What the saga does not solve on its own
- Lack of isolation (the “I” in ACID). Between T2 and C2, another purchase sees only 8 headphones, which were never sold (a dirty read). Other anomalies: lost updates and non-repeatable reads. Countermeasures: a semantic lock (mark the reservation as
PENDINGand handle that state), commutative updates, rereading the value before updating, and the pessimistic view (moving risky updates to after the pivot). - Saving and announcing at the same time. Inventory has to save the reservation and publish
StockReservedatomically; if it crashes in between, the saga stalls. The usual fix is the Transactional Outbox: the event is written to a table in the same database, in the same transaction, and published afterwards. - The client doesn’t get the answer right away. The saga is asynchronous:
POST /ordersreturns thePENDINGorder, and the app pollsGET /orders/1042or gets a notification when it becomesAPPROVEDorCANCELED. - Compensations are your code. There is no automatic rollback: someone has to write, test and make each
Cidempotent.
- ACID transaction
- A set of operations in one database that is atomic, consistent, isolated and durable: all or nothing. Avoid: an unqualified “transaction” when talking about several services.
- Database per Service
- Pattern in which each microservice exclusively owns its database; it is what creates the need for sagas.
- Two-phase commit (2PC)
- Distributed transaction protocol in which a coordinator only commits after every participant votes “ready”. Avoid: XA, as a generic synonym.
- Saga
- Coordinated sequence of local transactions in which failures are handled by compensating transactions. Avoid: “distributed transaction”.
- Local transaction
- ACID transaction that touches only one service’s database; each step of the saga is one.
- Compensating transaction
- A new transaction that applies the opposite effect of an already committed step. Avoid: “rollback”.
- Compensable transaction
- Saga step that can be cancelled by a compensation.
- Pivot transaction
- The saga’s point of no return: once it commits, the saga only moves forward.
- Retryable transaction
- Idempotent step after the pivot, repeated until it succeeds.
- Idempotent
- An operation that, run several times, leaves the same result as running it once.
- Choreography
- Coordinating the saga through events exchanged directly between services, with no central controller.
- Orchestration
- Coordinating the saga through a central orchestrator that sends commands and decides the next step.
- Eventual consistency
- The guarantee that data which diverges for a while converges to a correct state.
- Semantic lock
- An application-level marker (e.g. status
PENDING) signalling that a record is in the middle of a saga. - Transactional Outbox
- Pattern that writes the event to a table in the service’s own database, in the same transaction as the data, to publish it later without losing it.
1. A travel agency books flight → hotel → car, each in its own service. The flight and the hotel confirm, the car rental declines. What does the saga do?
2. The order saga has to send an “Your order was approved!” email. Where should that step go?
3. While the saga for order #1042 is between “reserve 2 headphones” and “charge”, another customer sees the product as sold out. The charge fails and the headphones come back. What problem is this, and which countermeasure helps?
4. An onboarding flow involves 8 services, with branches (“if it’s a company, validate the tax ID; otherwise skip”). The team struggles to understand who reacts to what. Which coordination tends to help?
5. Inventory saves the reservation to its database and, on the next line, publishes StockReserved. The process crashes between the two lines. What happens, and how do you prevent it?
- Renato Augusto — “O desafio que mais reprova programadores nas entrevistas de microsserviços!” (video in Portuguese, ~30 min): compensable, pivot and retryable transactions; orchestration vs choreography; the link to EDA. watch next
- Chris Richardson — Pattern: Saga (microservices.io): the problem, why not 2PC, the order example with a credit limit, lack of isolation and the Transactional Outbox.
- Microsoft Azure Architecture Center — Saga distributed transactions pattern: kinds of transaction, pros and cons of choreography/orchestration, data anomalies and countermeasures.
- Hector Garcia-Molina & Kenneth Salem — “Sagas”, ACM SIGMOD 1987: the paper that named the concept.