Skip to content
System Design Lab
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.

Advanced 9 min read· Updated 2026-11-18

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)CompensationNotes
Orders: create order (PENDING)Cancel orderThe PENDING state tells everyone the order is not final yet.
Payment: charge cardRefundA 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.
Order SagaOrdersPaymentInventory

Press play or step through the interaction.

Orchestrated saga where the third step fails and the first two are compensated.

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.

Loading simulation…

Orchestration vs choreography

Option AOrchestration
CustomersCustomersOrder SagaorchestratorOrder SagaOrderscreate / cancelOrdersPaymentcharge / refundPaymentInventoryreserve / releaseInventory
A saga orchestrator tells each service what to do and tracks the state. Easy to follow and change; one more component to run.
Option BChoreography
Ordersemits OrderCreatedOrdersEvent busEvent busPaymentemits PaymentChar…PaymentInventoryemits StockReserv…Inventory
Each service reacts to the previous service's event. No central coordinator, but the flow is spread across services and hard to see.

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.

Loading simulation…

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:

Advanced
  • Semantic locks — states such as PENDING or APPROVAL_PENDING tell 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)

PlaceOrderSaga.java
@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

BenefitsCosts
ConsistencyData across services converges to a consistent state.Only eventually; intermediate states are visible.
AvailabilityNo cross-service locks; each service stays autonomous.More moving parts: saga state, replies, timeouts.
ComplexityExplicit 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.

Further reading

Related topics