Microservice Patterns
Saga
Keep data consistent across services without a distributed transaction: run a sequence of local transactions and, when one fails, undo the completed ones with compensating actions.
What you will learn
- Explain why a database transaction cannot span several microservices.
- Model a business process as local transactions plus compensating actions.
- Compare orchestration and choreography.
- Recognise the isolation problems sagas introduce and the countermeasures.
Before you start
Overview
Booking a trip means reserving a flight, a hotel and a car from three different companies. Nobody can lock all three at once. You book them one by one, and if the car is unavailable you cancel the hotel and the flight. That is a saga: a series of steps, each with an "undo".
With a database per service, placing an order touches the Orders, Payment and Inventory databases. A single ACID transaction cannot span them. A saga splits the business transaction into local transactions, one per service, each committing on its own. If a step fails, the saga runs compensating transactions for the steps that already committed, in reverse order.
Why not a distributed transaction?
Two-phase commit (2PC) can make several databases commit atomically, but it holds locks across services while waiting for the slowest participant, blocks if the coordinator dies at the wrong moment, and is not supported by most message brokers and NoSQL stores. Microservices trade atomicity for availability and accept eventual consistency — sagas make that explicit and safe.
Steps and compensations
| Step (local transaction) | Compensation | Notes |
|---|---|---|
| Orders: create order (PENDING) | Cancel order | The PENDING state tells everyone the order is not final yet. |
| Payment: charge card | Refund | A refund is a new business action, visible on the statement — not a rollback. |
| Inventory: reserve stock | — | The last step needs no compensation: if it succeeds, the saga is done. |
Press play or step through the interaction.
Run it
Scenario B fails 30% of orders at the last step. Compare Rolled back cleanly with scenario C's Left inconsistent: same failures, completely different data quality. Open the Live sequence tab to see refunds and cancellations happen.
Orchestration vs choreography
Choreography suits short sagas of two or three steps owned by one team. As soon as the flow branches, has timeouts, or spans teams, an orchestrator is easier to reason about, test and monitor.
Run the choreographed version below. The same business flow emerges from subscriptions alone — and scenario C shows its classic failure mode: one team forgets to subscribe to a failure event, nothing errors, and orders quietly stay PENDING with the customer's card charged.
The catch: no isolation Advanced
Advanced Each local transaction commits immediately, so other requests can see a saga's intermediate state — a payment for an order that will be cancelled a second later. These anomalies (dirty reads, lost updates) are handled by design, not by the database:
- Semantic locks — states such as
PENDINGorAPPROVAL_PENDINGtell other operations to keep away or wait. - Pivot transaction — order steps so that everything after the point of no return can only succeed (or be retried until it does).
- Commutative updates — design operations so their order does not matter (debit and credit as separate entries).
- Reread values before updating, and fail the saga if they changed.
Implementation sketch (orchestrator)
@Component
public class PlaceOrderSaga {
private final SagaRepository sagas; // persisted saga state
private final CommandPublisher commands; // writes commands via an outbox
PlaceOrderSaga(SagaRepository sagas, CommandPublisher commands) {
this.sagas = sagas;
this.commands = commands;
}
@Transactional
public void start(PlaceOrder request) {
SagaState saga = sagas.save(SagaState.start(request));
commands.send(new CreatePendingOrder(saga.id(), request));
}
@Transactional
public void onReply(StepReply reply) {
SagaState saga = sagas.findById(reply.sagaId()).orElseThrow();
if (saga.alreadyHandled(reply.messageId())) return; // replies may be redelivered
if (reply.success()) {
saga.markDone(reply.step());
switch (reply.step()) {
case CREATE_ORDER -> commands.send(new ChargeCard(saga.id(), saga.payment()));
case CHARGE_CARD -> commands.send(new ReserveStock(saga.id(), saga.items()));
case RESERVE_STOCK -> commands.send(new ApproveOrder(saga.id()));
}
} else {
saga.startCompensating();
// Undo completed steps in reverse order: refund, then cancel the order.
saga.completedSteps().reversed().forEach(step -> commands.send(step.compensation(saga.id())));
}
sagas.save(saga);
}
}Trade-offs
| Benefits | Costs | |
|---|---|---|
| Consistency | Data across services converges to a consistent state. | Only eventually; intermediate states are visible. |
| Availability | No cross-service locks; each service stays autonomous. | More moving parts: saga state, replies, timeouts. |
| Complexity | Explicit model of a long-running business process. | Every step needs a compensation and every handler must be idempotent. |
Production considerations
- Persist saga state and give every saga instance an id carried by all its messages.
- Add timeouts per step: a participant that never replies must trigger compensation, not a saga stuck forever.
- Monitor sagas stuck in non-final states and the rate of compensations — a rising rate is a business signal too.
- Consider a workflow engine (Temporal, Camunda) when sagas become long or numerous.