Sagas
Run a business transaction across services as a chain of local transactions with compensating actions, and handle the isolation you give up.
The problem
An online shop has three services, each with its own database: orders, payments and inventory. Checkout must create an order, take payment and reserve stock. If the item turns out to be sold out, the customer must not be charged.
A distributed transaction is the textbook answer, and it does not fit. The payment service calls an external card processor over HTTP, which has no prepare step. Card authorisation can take seconds, and some workflows, such as a booking that waits for a supplier to confirm, take hours. Nobody can hold database locks for that long. And if any one service is down, nothing can be sold.
The first thing teams try is calling the three services in order and hoping. A crash after the payment and before the reservation leaves a charged customer with no order, and nothing in the system knows it happened.
In 1987 Hector Garcia-Molina and Kenneth Salem described a way to run long-lived transactions without long-held locks: break the work into a sequence of small transactions, each with a defined way to undo it. They called the sequence a saga. Their paper was about a single database. The idea found its largest audience decades later, with microservices.
How a saga works
A saga is a sequence of local transactions. Each one runs in one service, commits to that service’s database straight away, and then triggers the next. Each step that might need undoing has a compensating action, a new transaction that reverses its business effect.
For checkout:
| Step | Action | Compensating action |
|---|---|---|
| 1 | Create the order as PENDING |
Mark the order REJECTED |
| 2 | Place a hold on the card | Release the hold |
| 3 | Reserve the stock | Release the reservation |
| 4 | Capture the payment, mark the order CONFIRMED |
None. Retry until it succeeds. |
If step 3 fails, the saga runs the compensations for steps 2 and 1, in that order. The guarantee is that the saga either completes or every completed step is compensated.
Step 1 of 8
A customer checks out. The orchestrator starts a saga and saves its state durably, so it can resume after a crash. There is no global transaction, and no lock is held across services.
Read the steps as text
- A customer checks out. The orchestrator starts a saga and saves its state durably, so it can resume after a crash. There is no global transaction, and no lock is held across services.
- Step one. The order service creates the order in its own database and commits. The status is PENDING, which tells every other reader that this order is not final yet.
- Step two. The payment service places a hold of £40 on the customer's card and commits. A hold is used instead of a charge because it is cheap to undo.
- Step three. The inventory service tries to reserve the item, but another customer has just taken the last one. It replies that the step has failed.
- Nothing can be rolled back in the database sense, because steps one and two have already committed. So the orchestrator runs their compensating actions, in reverse order.
- Compensate step two: release the hold. The first request times out, so the orchestrator retries with the same idempotency key. The payment service releases the hold once, however many retries arrive.
- Compensate step one: the order service marks the order REJECTED. It does not delete the row, because the customer and the support team need to see what happened.
- Every service is consistent again: no order, no hold, no stock taken. For a short time, though, the pending order and the hold were visible to others. A saga gives all or nothing eventually, with no isolation on the way.
Three points make this work in practice.
Compensation is not rollback. A database rollback leaves no trace. A compensation is a visible business action: a refund appears on a statement, a rejected order stays in the history. Some effects cannot be compensated at all, such as an email that has been sent or a parcel that has left the warehouse.
Order the steps by how reversible they are. Put steps that are likely to fail and easy to undo first. Put the step that cannot be undone as late as possible. That step is the pivot: before it the saga can still be abandoned, and after it every remaining step must be one that can be retried until it succeeds. In the table, capturing the payment is the pivot.
Compensations must not fail for good. If releasing a hold fails, the saga retries it. If it keeps failing, a person is alerted. There is no compensation for a compensation.
Choreography and orchestration
There are two ways to connect the steps.
In choreography there is no central controller. Each service publishes an event when it finishes its step, and other services react. The order service emits OrderCreated, the payment service hears it and emits PaymentAuthorised, and so on. Failure events travel the same way and trigger compensations.
In orchestration one component, the orchestrator, holds the saga’s state machine. It sends a command to each service, waits for the reply, and decides the next step or the compensations. Its state is persisted, so it can resume after a crash. Workflow engines such as Temporal and AWS Step Functions are built for this role.
| Choreography | Orchestration | |
|---|---|---|
| Where the flow is defined | Spread across the services’ event handlers | In one place |
| Coupling | Services know only events | The orchestrator knows every participant |
| Finding a stuck saga | Hard. You reconstruct it from events. | Easy. Ask the orchestrator. |
| Good fit | Two or three steps, stable flow | Longer flows, timeouts, branching |
Living without isolation
A saga gives atomicity in the eventual sense, and durability, but no isolation. Each step commits on its own, so the rest of the system can see a half-finished saga. Another request might read the pending order, count the reserved stock as sold, or change a record that the saga is about to compensate.
The countermeasures are design techniques, not database features:
- Semantic locks. Mark the records a saga is working on with a state such as
PENDING. Other code must respect it: a pending order is not shipped, and a second saga that finds one either waits or fails fast. - Pending states shown to users. “Payment processing” is honest and discourages double submissions.
- Reserve, then confirm. A card hold or a stock reservation with an expiry is easy to release, and other readers can see that it is provisional.
- Commutative updates. Add and subtract amounts instead of overwriting a balance, so steps and compensations give the same result in any order.
- Re-read before writing. Check a version number, so a step fails cleanly if the record changed underneath it.
Reliable steps: idempotency and the outbox
Messages between steps are delivered at least once, so every step and every compensation will sometimes arrive twice. Each must be idempotent: keyed by the saga id, so that a repeat is recognised and has no further effect. A compensation can even arrive before the step it undoes, when the original request was delayed and timed out. The service should record the cancellation so that the late step is refused.
There is one more gap. A service must update its database and send the next message. If it does these as two separate actions, a crash between them either loses the message or announces a change that never committed. The transactional outbox closes the gap. The service writes the outgoing message into an outbox table in the same local transaction as the state change. A separate relay reads new outbox rows, by polling or by tailing the database log with a tool such as Debezium, and publishes them to the broker. Delivery is at least once, so consumers still deduplicate.
When a saga is the wrong tool
Choose a saga when a business process spans services or external systems, each step can be undone or retried, and users can tolerate a visible intermediate state.
Do not choose one when:
- All the data is in one database. Use a local transaction. It is simpler and fully isolated.
- The invariant cannot tolerate intermediate states being seen, such as a ledger in which debits and credits must always balance. Keep that data together, or use a database with real distributed transactions.
- A step has no meaningful compensation and cannot be moved to the end.
- You are using it to cover for service boundaries drawn in the wrong place. If two services always change together, they may be one service.
In the interview
Reach for a saga when one user action updates several services, as in the payment system and food delivery case studies. Name the steps and the compensation for each. Say whether you would orchestrate or choreograph, and why. Then show that you know the costs. There is no isolation, so you use pending states. Messages repeat, so steps are idempotent. The database write and the event are tied together with an outbox. Saying what happens when a compensation itself fails is the detail that marks a senior answer.
Key takeaways
- A saga is a sequence of local transactions. If a step fails, the completed steps are undone by compensating actions run in reverse order.
- A compensation is a new, visible business action, not a rollback. Put steps that are hard to undo as late as possible.
- Choreography connects steps with events and suits short flows. Orchestration puts the flow in one persisted state machine and suits long ones.
- Sagas have no isolation. Use pending states, reservations and version checks so that half-finished work does no harm.
- Every step and compensation must be idempotent, because messages are delivered at least once.
- The transactional outbox makes "update my database and publish a message" atomic by writing the message in the same local transaction.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What is a saga?
A business transaction split into a sequence of local transactions, each in one service. If a step fails, the earlier steps are undone by compensating actions.
How does a compensating action differ from a rollback?
A rollback erases uncommitted work without trace. A compensation is a new committed transaction that reverses the business effect, such as a refund, and it is visible. Some effects cannot be compensated.
Choreography versus orchestration
Choreography: services react to each other's events, with no central controller. Orchestration: one component holds the saga state machine and sends commands. Use orchestration for longer or branching flows.
What is a semantic lock?
An application-level marker, such as a PENDING status, on a record that a saga is still working on. Other code must check it and wait, fail or treat the record as not final.
What is the pivot step of a saga?
The point of no return. Steps before it can be compensated. Steps after it must be retried until they succeed, because the saga can no longer be abandoned.
What problem does the transactional outbox solve?
The dual write: updating a database and publishing a message as two actions that a crash can separate. The message is stored in an outbox table in the same transaction and published later by a relay.