Distributed transactions and Saga
Senior Always asked 7 min
On this page
The question
What is a saga, and why use one instead of a distributed transaction?
30-second answer
A saga is a sequence of local transactions, one per service, each committed in its own database and triggering the next step. If a step fails, the saga runs compensating transactions that undo the effects of the steps already committed, in reverse order. It replaces a distributed transaction, which needs every database to hold locks and agree, with a series of short, independent commits.
Understand it
A saga: happy path, then compensation
Step by stepOrder 1: Orders saves the order as PENDING in its own database, commits, and starts the saga. No lock is held across services.
View as text
Three services in a column, Orders, Payments and Inventory, each with the state of its local record. Solid arrows go down as the saga moves forward; dashed arrows go back up as compensations run. Two orders run: the first succeeds, the second fails at the third step.
Order 1: Orders saves the order as PENDING in its own database, commits, and starts the saga. No lock is held across services.
Payments charges the card in its own transaction and commits. The order is still PENDING, and other requests can see that.
Inventory reserves the items and commits. Every step so far succeeded.
Orders marks the order APPROVED. Four local transactions in three databases add up to one business transaction.
Order 2: the order is created and the card charged, but Inventory has no stock. Steps 1 and 2 are already committed and cannot be rolled back.
So the saga runs compensations, in reverse order. Payments refunds the charge: a new transaction that undoes the effect, not a rollback.
Orders marks the order CANCELLED. The system is consistent again, but the charge and refund both stay in the history.
Three services in a column, Orders, Payments and Inventory, each with the state of its local record. Solid arrows go down as the saga moves forward; dashed arrows go back up as compensations run. Two orders run: the first succeeds, the second fails at the third step.
Order 1: Orders saves the order as PENDING in its own database, commits, and starts the saga. No lock is held across services.
Payments charges the card in its own transaction and commits. The order is still PENDING, and other requests can see that.
Inventory reserves the items and commits. Every step so far succeeded.
Orders marks the order APPROVED. Four local transactions in three databases add up to one business transaction.
Order 2: the order is created and the card charged, but Inventory has no stock. Steps 1 and 2 are already committed and cannot be rolled back.
So the saga runs compensations, in reverse order. Payments refunds the charge: a new transaction that undoes the effect, not a rollback.
Orders marks the order CANCELLED. The system is consistent again, but the charge and refund both stay in the history.
Takeaway: A saga is a sequence of local transactions, each committed in its own service. When a step fails, the saga runs compensating transactions for the steps that already committed, in reverse order.
Saga choreography vs orchestration
CompareNo one is in charge. Each service listens for events and publishes its own: OrderCreated, then PaymentCharged, then StockReserved. Simple and loosely coupled, but the flow lives in many places.
View as text
Orders, Payments and Inventory, arranged around a center: an event broker in choreography, an orchestrator in orchestration. Arrows show events or commands. Four facts sit below: who decides the next step, what services know, how to see the whole flow, and when it fits.
Choreography: No one is in charge. Each service listens for events and publishes its own: OrderCreated, then PaymentCharged, then StockReserved. Simple and loosely coupled, but the flow lives in many places. Who decides the next step: Each service, on events. Services know: Each other's events. To see the whole flow: Read every service. Fits best: Few steps, few branches.
Orchestration: An orchestrator sends a command to each service in turn and waits for its reply. The whole flow, with every compensation, lives in one state machine you can test. Who decides the next step: One orchestrator. Services know: Only their own commands. To see the whole flow: Read the orchestrator. Fits best: Many steps and branches.
Orders, Payments and Inventory, arranged around a center: an event broker in choreography, an orchestrator in orchestration. Arrows show events or commands. Four facts sit below: who decides the next step, what services know, how to see the whole flow, and when it fits.
Choreography: No one is in charge. Each service listens for events and publishes its own: OrderCreated, then PaymentCharged, then StockReserved. Simple and loosely coupled, but the flow lives in many places. Who decides the next step: Each service, on events. Services know: Each other's events. To see the whole flow: Read every service. Fits best: Few steps, few branches.
Orchestration: An orchestrator sends a command to each service in turn and waits for its reply. The whole flow, with every compensation, lives in one state machine you can test. Who decides the next step: One orchestrator. Services know: Only their own commands. To see the whole flow: Read the orchestrator. Fits best: Many steps and branches.
Takeaway: Choreography chains services through events, with no one in charge. Orchestration puts the flow in one coordinator that sends commands. Choose choreography for short flows, orchestration when steps and compensations multiply.
In code
@Component
class PlaceOrderSaga {
private final CommandBus commands;
private final SagaStore sagas; // saga state survives a restart
PlaceOrderSaga(CommandBus commands, SagaStore sagas) { this.commands = commands; this.sagas = sagas; }
void start(OrderCreated e) {
sagas.save(new SagaState(e.orderId(), Step.CHARGING));
commands.send(new ChargePayment(e.orderId(), e.total()));
}
void on(PaymentCharged r) { sagas.advance(r.orderId(), Step.RESERVING); commands.send(new ReserveStock(r.orderId())); }
void on(StockReserved r) { sagas.advance(r.orderId(), Step.DONE); commands.send(new ApproveOrder(r.orderId())); }
void on(StockUnavailable r) { // failure: compensate in reverse order
sagas.advance(r.orderId(), Step.COMPENSATING);
commands.send(new RefundPayment(r.orderId()));
}
void on(PaymentRefunded r) { sagas.advance(r.orderId(), Step.CANCELLED); commands.send(new CancelOrder(r.orderId())); }
}@Component
class PaymentsOnOrderCreated { // in the Payments service
@KafkaListener(topics = "orders.created", groupId = "payments")
void on(OrderCreated e) {
Payment p = payments.charge(e.orderId(), e.total());
events.send("payments.charged", e.orderId(), new PaymentCharged(e.orderId(), p.id()));
}
@KafkaListener(topics = "inventory.unavailable", groupId = "payments")
void compensate(StockUnavailable e) { // Payments must know Inventory's events
payments.refund(e.orderId());
events.send("payments.refunded", e.orderId(), new PaymentRefunded(e.orderId()));
}
private final PaymentService payments;
private final KafkaTemplate<String, Object> events;
PaymentsOnOrderCreated(PaymentService payments, KafkaTemplate<String, Object> events) { this.payments = payments; this.events = events; }
}@Transactional
void undoChargeWrong(OrderId order) {
// Pretends the charge never happened: the card provider still took the money
Wrong paymentRepository.deleteByOrder(order);
}
@Transactional
void undoCharge(OrderId order) {
Payment p = paymentRepository.findByOrder(order).orElseThrow();
Right if (p.status() == REFUNDED) return; // idempotent: a redelivered command is harmless
Right provider.refund(p.providerChargeId(), "refund-" + order); // idempotency key for the provider
paymentRepository.save(p.refunded());
}Solve it
Design the saga for booking a trip: flight, hotel and car
A travel site books a flight, a hotel and a rental car through three providers, and charges the customer once. Any of the four steps can fail. The flight provider’s tickets cannot be cancelled once issued, while hotel and car bookings can be cancelled for free. Order the steps and define what happens when each one fails.
- List each step and its compensation. Hotel: book, cancel. Car: book, cancel. Charge: charge, refund. Flight: issue, none, because it cannot be undone.
- Find the pivot. The step that cannot be compensated is the point of no return. Run every compensable step before it, so any failure there can still be undone.
- Put the pivot last, or follow it only with steps that will succeed. Steps after the pivot must be retried until they succeed, so make them idempotent.
- Choose orchestration. Four steps with different compensations are easier to read, test and monitor as one state machine than as a chain of events.
- Check. In a test, make each provider fail in turn: every failure before the pivot leaves no booking and no charge, and the pivot is never followed by a compensation.
List<SagaStep> trip = List.of(
new SagaStep("hotel", t -> hotels.book(t), t -> hotels.cancel(t)),
new SagaStep("car", t -> cars.book(t), t -> cars.cancel(t)),
new SagaStep("charge", t -> payments.charge(t), t -> payments.refund(t)),
new SagaStep("flight", t -> flights.issue(t), null) // pivot: cannot be undone
);
void run(Trip t) {
Deque<SagaStep> done = new ArrayDeque<>();
for (SagaStep step : trip) {
try { step.action().accept(t); done.push(step); }
catch (StepFailed e) {
while (!done.isEmpty()) done.pop().compensation().accept(t); // reverse order
throw e;
}
}
}How to answer
- Each service keeps its own database and its own short transactions.
- The result is eventual consistency; intermediate states, such as PENDING, are visible.
- Coordinate it by choreography, with events, or by orchestration, with a central coordinator.
- Every step and compensation must be idempotent, because messages can be redelivered.
Common mistakes
- Saying a saga rolls back like a database transaction. Committed steps stay committed; compensations are new transactions that undo their effect.
- Forgetting that other requests can see the intermediate state, such as a charged card on an order that will be cancelled.
Follow-up questions
Why not use two-phase commit (2PC) across microservices?
In two-phase commit (2PC), a coordinator asks every participant to prepare, holding its locks, and then to commit. All participants must be up, support the protocol, and wait for the slowest one; if the coordinator fails after prepare, they hold locks until it returns. That couples services in time, hurts throughput and availability, and most brokers and NoSQL stores, and HTTP APIs, do not support XA, the standard 2PC protocol.
- 2PC is a blocking protocol; locks are held across network round trips.
- Availability of the whole is the product of every participant's availability.
- It works inside one database or a small trusted cluster, not across autonomous services.
See it in the infographic: A saga: happy path, then compensation
What is the difference between saga choreography and orchestration, and when do you pick each?
In choreography, there is no coordinator: each service listens for events and publishes its own, so the flow emerges from the chain. It is simple and loosely coupled, but the flow is spread across services and hard to follow. In orchestration, a coordinator sends commands to each service and handles replies, so the flow and its compensations live in one place. Choose choreography for two or three steps, orchestration for longer flows with branches.
- Choreography risks cyclic dependencies between services' events.
- The orchestrator must not absorb the services' business logic.
- Tracing and a correlation ID are essential either way.
See it in the infographic: Saga choreography vs orchestration
What is a compensating transaction, and what makes one hard to design?
It is an action that semantically undoes a committed step: refund a charge, cancel a reservation, release stock. It does not erase history; both the step and its compensation remain. It is hard when the effect cannot be undone, such as an email already sent or a ticket already issued, or when other actions already built on the result. Such steps go last, as the pivot.
- Compensations must be idempotent and retryable until they succeed.
- Some compensations are business decisions, such as a refund with a fee.
- Order steps so that the riskiest and the irreversible ones run last.
See it in the infographic: A saga: happy path, then compensation
Sagas have no isolation between them. What can go wrong, and how do you guard against it?
Other sagas can see and act on uncommitted intermediate state. A dirty read: a customer spends credit that a failing saga is about to return. A lost update: two sagas change the same record, and one compensation overwrites the other. Guards include semantic locks, a PENDING flag that others respect; commutative updates, such as adding or subtracting instead of setting; rereading values before acting; and ordering steps so risky ones go first.
- ACID (atomicity, consistency, isolation, durability) gives isolation in one database; a saga gives only eventual atomicity.
- A pending state shown to users is often the simplest countermeasure.
- Version checks catch a record that changed since the saga read it.
See it in the infographic: A saga: happy path, then compensation
How do you make each step of a saga reliable when services crash and messages are redelivered?
Commit each local change and the message that triggers the next step together, with a transactional outbox, so neither is lost. Make every handler idempotent, by recording processed message IDs or checking the current state, because the broker delivers at least once. Persist the saga's state, so an orchestrator resumes after a crash, and add timeouts for steps that never answer.
- A step that never replies needs a timeout that triggers compensation.
- Correlate every message with the saga ID and log it.
- Test each failure point, including a crash between steps.
See it in the infographic: A saga: happy path, then compensation See it in the infographic: Saga choreography vs orchestration
What if a compensating transaction fails?
Retry it, because a compensation must eventually succeed: make it idempotent and keep retrying with backoff, from a durable saga state. If it still cannot succeed, such as a refund to a closed card, park the saga in a failed state and alert a person, with a manual process to finish it.
Where does an orchestrator keep the saga's state?
In its own database, one row per saga with its current step, updated in the same transaction that sends the next command, through an outbox. After a crash it resumes from the stored step. Workflow engines such as Temporal or Camunda keep this state for you.
Check yourself
Show answers
- Refund the charge, then cancel the order: Correct. Compensations undo the committed steps in reverse order.
- Cancel the order, then refund the charge: Incorrect. That is forward order; reverse order keeps dependencies intact.
- Roll back all three database transactions: Incorrect. They are already committed in separate databases; only compensations can undo them.
Show answers
- Nowhere in one place; it emerges from each service's event handlers: Correct. That is choreography's trade-off; tracing shows the flow at run time.
- In the orchestrator's state machine: Incorrect. Choreography has no orchestrator.
- In the broker's configuration: Incorrect. The broker only delivers events; it does not know the business flow.
Show answers
- Last, after every step that can be compensated: Correct. The irreversible pivot goes where nothing after it can fail and need undoing.
- First, so it fails early: Incorrect. If a later step fails, the ticket can no longer be cancelled.
- Anywhere, since sagas compensate every step: Incorrect. An irreversible step has no compensation to run.