Skip to content
Commitwise
Menu
Java Backend

Sagas and distributed workflows

Keep data consistent across services without distributed transactions, using sagas made of local transactions and compensations, choosing between choreography and orchestration, persisting workflow state, handling timeouts and duplicates, and knowing when a workflow engine such as Temporal is worth it.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A customer places an order. The order service saves it, the payment service charges the card, and the inventory service tries to reserve the items, but one is out of stock. In a single database, a transaction would roll everything back. Here there are three databases. The order exists, the card is charged, and the items aren’t reserved. Someone has to undo the charge, cancel the order, and tell the customer, reliably, even if a service crashes halfway through.

A sagaSagaA business transaction across services made of local transactions, each with a compensating action that undoes it if a later step fails.Open in glossary → is the standard answer: a sequence of local transactions, one per service, where each step has a compensating action that undoes it if a later step fails. This lesson shows the two ways to coordinate sagas, how to make them survive crashes and duplicates, and when to reach for a workflow engine.

New to some of these? Open what you need, or skip ahead.

Basics:What is a transaction?

A transaction groups database changes so they happen all together or not at all: if anything fails, everything is rolled back. It only works inside one database. The Transactions lesson covers how they work in Spring.

Basics:What are events and messages?

Services can talk without waiting for each other by sending messages through a broker such as Kafka. An event says something happened (“OrderPlaced”); a command asks a service to do something (“ReserveStock”). Messages can arrive late or more than once, so receivers must handle duplicates. See Messaging with Kafka.

Part Not started

Transactions across services

Think of planning a trip: you book a flight, a hotel and a car, each with a different company. There’s no button that books all three or none. If the car isn’t available, you cancel the hotel and the flight yourself. That’s a saga: several separate steps, plus a plan for undoing the earlier ones.

For an order:

  1. Order service: create the order as PENDING.
  2. Payment service: charge the card. Undo: refund.
  3. Inventory service: reserve the items. Undo: release them.
  4. Order service: mark the order CONFIRMED.

If step 3 fails, the saga runs the undo steps for what already happened, in reverse: refund the payment, then mark the order CANCELLED.

Two important ideas:

  • Undo is a new action, not a time machine. The refund is a real transaction the customer sees on their statement. An email that was sent can’t be unsent; you send another one.
  • “In progress” is a real state. Between the steps, the order is PENDING. The app shows it, and other code must handle it.

Distributed transactions (2PC/XA) couple the availability of all participants, hold locks across network calls and aren’t supported by most brokers and cloud databases, so microservices use sagas: a sequence of local ACID transactions, each emitting a message that triggers the next, with compensating transactions for steps that can be semantically undone. Sagas give up isolation: other transactions see intermediate states, so design with semantic locks (status fields like PENDING that other operations respect), commutative updates, re-reading values, and ordering steps so that pivot steps (the point of no return, such as a capture) come after compensatable ones and before retriable ones. Coordination styles: choreography (each service reacts to events; simple for two or three steps, but the flow is implicit and cyclic dependencies creep in) and orchestration (a coordinator sends commands and tracks state; explicit, testable, easier to change and to observe). Both rely on the transactional outbox for atomic state-change-plus-message and on idempotent handlers, since delivery is at least once.

// Payment service
@KafkaListener(topics = ["orders"])
fun onOrderPlaced(event: OrderPlaced) {
    payments.charge(event.orderId, event.total)               // local transaction + outbox: PaymentSucceeded or PaymentFailed
}

// Inventory service
@KafkaListener(topics = ["payments"])
fun onPaymentSucceeded(event: PaymentSucceeded) {
    inventory.reserve(event.orderId, event.items)             // StockReserved or StockUnavailable
}

// Payment service again: the compensation
@KafkaListener(topics = ["inventory"])
fun onStockUnavailable(event: StockUnavailable) {
    payments.refund(event.orderId)                            // PaymentRefunded
}

// Order service: follows all of them to update the order's status
@KafkaListener(topics = ["payments", "inventory"])
fun onSagaEvent(event: OrderSagaEvent) {
    orders.apply(event)                                       // PENDING → CONFIRMED or CANCELLED
}
// Payment service
@KafkaListener(topics = "orders")
void onOrderPlaced(OrderPlaced event) {
    payments.charge(event.orderId(), event.total());          // local transaction + outbox: PaymentSucceeded or PaymentFailed
}

// Inventory service
@KafkaListener(topics = "payments")
void onPaymentSucceeded(PaymentSucceeded event) {
    inventory.reserve(event.orderId(), event.items());        // StockReserved or StockUnavailable
}

// Payment service again: the compensation
@KafkaListener(topics = "inventory")
void onStockUnavailable(StockUnavailable event) {
    payments.refund(event.orderId());                         // PaymentRefunded
}

// Order service: follows all of them to update the order's status
@KafkaListener(topics = {"payments", "inventory"})
void onSagaEvent(OrderSagaEvent event) {
    orders.apply(event);                                      // PENDING → CONFIRMED or CANCELLED
}
  • Nobody is “in charge”: each service listens for the event that concerns it, does its local work, and publishes the result.
  • refund is the compensation for charge. It runs when inventory reports that the items aren’t available.
  • The order service listens to everything and moves the order from PENDING to CONFIRMED or CANCELLED, which is what the customer sees.

This works well for short flows. With more steps, the flow is spread across many listeners, and it gets hard to answer “what happens if…?”. That’s where orchestration (next part) helps.

Predict the output

In the choreography above, the inventory service publishes StockUnavailable, but the payment service is down for 10 minutes. What does the customer's order look like during those 10 minutes, and what happens after?

Spot the bugA compensation that charges back twice

Tap the line with the bug.

@KafkaListener(topics = ["inventory"])
fun onStockUnavailable(event: StockUnavailable) {
    val payment = payments.findByOrderId(event.orderId)
    paymentProvider.refund(payment.chargeId, payment.amount)
    payment.markRefunded()
    payments.save(payment)
}
@KafkaListener(topics = "inventory")
void onStockUnavailable(StockUnavailable event) {
    Payment payment = payments.findByOrderId(event.orderId());
    paymentProvider.refund(payment.chargeId(), payment.amount());
    payment.markRefunded();
    payments.save(payment);
}

Designing the steps

  • Order matters: compensatable steps first (reserve stock, authorize the card), the pivot (capture the payment, ship) next, and only steps that can’t fail for business reasons (send email, add loyalty points; retried until they succeed) after it.
  • Prefer reservations to irreversible actions: authorize then capture, reserve then commit stock. A reservation with an expiry is a compensation that happens by itself.
  • Isolation anomalies: a second saga can read stock reserved by a saga that will later be compensated. Use semantic locks (RESERVED, PENDING), re-check at the pivot, and design counters to tolerate commutative updates.
  • Compensations can fail too: they must be retried until they succeed (with alerts), or escalate to a manual queue with full context.
  • Saga = local transactions + messages + compensations; no 2PC. Delivery is at least once: every step and compensation is idempotent; state change + message via the outbox.
  • No isolation: intermediate states are visible; semantic locks (PENDING, RESERVED), re-checks at the pivot.
  • Step order: compensatable → pivot → retriable. Prefer reservations (authorize/capture, reserve/commit) with expiry.
  • Choreography for short flows; orchestration when flows grow, need timeouts, or must be observable and changeable.

Check this part

  1. What is a compensating action?

  2. Why must PENDING be a real, visible order state?

  3. Why are sagas used instead of two-phase commit between services?

  4. Where should the pivot step (the point of no return) go?

A saga splits a business transaction into local transactions, each publishing an event or command, with a compensating action for every step that can be undone. Compensations are business operations (refund, release, cancel), not rollbacks. Intermediate states like PENDING are real and visible. Choreography lets services react to each other's events; orchestration puts the flow in one coordinator, which is easier to follow and change as flows grow.

Part Not started

Orchestrating a saga

In orchestration, one component, the orchestrator, runs the saga like a project manager with a checklist:

  • It remembers where it is: the saga’s current step is saved in the database, so a restart picks up where it left off.
  • It sends commands: “charge this order”, “reserve these items”.
  • It reacts to replies: success moves to the next step; failure starts the compensations, in reverse order.
  • It watches the clock: if a service doesn’t reply within, say, 15 minutes, it treats the step as failed and compensates.

All the logic of “what happens if…” lives in one class, which you can read top to bottom and test.

An orchestrator is a persisted state machine per saga instance: state, step, attempt counters, deadlines, and data needed for compensations. Each transition is a local transaction that updates the saga row and writes the next command to the outbox, so state and messages can’t diverge. Replies are correlated by saga id and processed idempotently (ignore replies that don’t match the expected step or that were already applied, which also handles reordering). Timeouts are deadlines stored with the state and enforced by a scheduler that sends a timeout event, driving compensation or retries. Visibility comes for free: query saga states for dashboards and stuck-saga alerts. For long-running, branching or human-in-the-loop flows, a durable execution engine (Temporal, Cadence, Camunda for BPMN) handles persistence, retries, timers and versioning of workflow code; the price is a new piece of infrastructure and determinism rules for workflow code.

@Service
class OrderSagaOrchestrator(
    private val sagas: SagaRepository,
    private val outbox: OutboxRepository,
) {
    @Transactional
    fun start(order: Order) {
        val saga = sagas.save(OrderSaga.started(order, deadline = Instant.now().plus(Duration.ofMinutes(15))))
        outbox.save(Command.of("payments", ChargePayment(saga.id, order.id, order.total)))
    }

    @Transactional
    fun on(reply: SagaReply) {
        val saga = sagas.findById(reply.sagaId).orElseThrow()
        if (!saga.expects(reply)) return                           // duplicate or out-of-date reply: ignore

        when (reply) {
            is PaymentSucceeded -> {
                saga.moveTo(Step.RESERVING_STOCK)
                outbox.save(Command.of("inventory", ReserveStock(saga.id, saga.items)))
            }
            is StockReserved -> {
                saga.complete()
                outbox.save(Command.of("orders", ConfirmOrder(saga.orderId)))
            }
            is PaymentFailed -> {
                saga.fail(reply.reason)
                outbox.save(Command.of("orders", CancelOrder(saga.orderId, reply.reason)))
            }
            is StockUnavailable -> {
                saga.compensating(reply.reason)
                outbox.save(Command.of("payments", RefundPayment(saga.id, saga.orderId)))
            }
            is PaymentRefunded -> {
                saga.fail(saga.failureReason)
                outbox.save(Command.of("orders", CancelOrder(saga.orderId, saga.failureReason)))
            }
            is StepTimedOut -> {                                   // a step never answered
                saga.compensating("Timed out at ${saga.step}")
                // refunding is safe even if nothing was charged: the payment service treats it as a no-op
                outbox.save(Command.of("payments", RefundPayment(saga.id, saga.orderId)))
            }
        }
        sagas.save(saga)
    }

    @Scheduled(fixedDelay = 60_000)
    @Transactional
    fun expireStuckSagas() {
        sagas.findRunningPastDeadline(Instant.now()).forEach { on(SagaReply.timedOut(it)) }   // like a failure
    }
}
@Service
class OrderSagaOrchestrator {
    private final SagaRepository sagas;
    private final OutboxRepository outbox;

    OrderSagaOrchestrator(SagaRepository sagas, OutboxRepository outbox) {
        this.sagas = sagas;
        this.outbox = outbox;
    }

    @Transactional
    public void start(Order order) {
        var saga = sagas.save(OrderSaga.started(order, Instant.now().plus(Duration.ofMinutes(15))));
        outbox.save(Command.of("payments", new ChargePayment(saga.id(), order.id(), order.total())));
    }

    @Transactional
    public void on(SagaReply reply) {
        var saga = sagas.findById(reply.sagaId()).orElseThrow();
        if (!saga.expects(reply)) return;                          // duplicate or out-of-date reply: ignore

        switch (reply) {
            case PaymentSucceeded r -> {
                saga.moveTo(Step.RESERVING_STOCK);
                outbox.save(Command.of("inventory", new ReserveStock(saga.id(), saga.items())));
            }
            case StockReserved r -> {
                saga.complete();
                outbox.save(Command.of("orders", new ConfirmOrder(saga.orderId())));
            }
            case PaymentFailed r -> {
                saga.fail(r.reason());
                outbox.save(Command.of("orders", new CancelOrder(saga.orderId(), r.reason())));
            }
            case StockUnavailable r -> {
                saga.compensating(r.reason());
                outbox.save(Command.of("payments", new RefundPayment(saga.id(), saga.orderId())));
            }
            case PaymentRefunded r -> {
                saga.fail(saga.failureReason());
                outbox.save(Command.of("orders", new CancelOrder(saga.orderId(), saga.failureReason())));
            }
            case StepTimedOut r -> {                               // a step never answered
                saga.compensating("Timed out at " + saga.step());
                // refunding is safe even if nothing was charged: the payment service treats it as a no-op
                outbox.save(Command.of("payments", new RefundPayment(saga.id(), saga.orderId())));
            }
        }
        sagas.save(saga);
    }

    @Scheduled(fixedDelay = 60_000)
    @Transactional
    public void expireStuckSagas() {
        for (var saga : sagas.findRunningPastDeadline(Instant.now())) {
            on(SagaReply.timedOut(saga));                          // treated like a failure of the current step
        }
    }
}
  • start saves the saga with a 15-minute deadline and sends the first command, both in one transaction (the command goes through the outbox).
  • on(reply) handles every reply in one place. saga.expects(reply) ignores duplicates and replies that arrive too late, so handling is idempotent.
  • The switch/when is the whole saga, readable top to bottom: success moves forward, failure compensates.
  • expireStuckSagas runs every minute and fails sagas whose deadline passed, so an order never stays PENDING forever because a service never answered.

Predict the output

The orchestrator saves the saga and calls kafkaTemplate.send(command) directly inside the @Transactional method, instead of writing to the outbox. The database commit fails after the send. What happens?

Exercisemedium

Add a step to the saga

The business adds a fraud check before payment: a fraud service answers FraudCheckPassed or FraudCheckRejected. Where does the step go, does it need a compensation, and what changes in the orchestrator?

›

Does a fraud check change anything that would need undoing? Where is the cheapest place to fail?

SolutionTry it yourself first
  • Position: first, before payment. It’s the cheapest step to fail, and failing it means nothing else has happened.
  • Compensation: none. A fraud check only reads and decides; there’s nothing to undo.
  • Orchestrator changes: start sends CheckFraud instead of ChargePayment; a new case FraudCheckPassed moves to CHARGING and sends ChargePayment; FraudCheckRejected cancels the order with the reason. The deadline and expects checks cover the new step automatically if the step enum includes it.
  • Tests: a unit test per transition (reply in, expected state and command out), including a duplicate FraudCheckPassed.

Production puzzles

Predict the output

A saga reserves stock, then waits for the customer to complete 3-D Secure, which can take minutes. Meanwhile, another order sees the item as out of stock. The first customer abandons the payment. With no timeout, what happens to the reserved stock?

Exercisehard

Choose the coordination

A travel platform books flight, hotel and car for a trip, with a payment at the end, partner APIs that can take hours to confirm, and a support team that must see where every booking is stuck. Choreography, a hand-written orchestrator, or a workflow engine? Justify it.

›

Weigh flow length, long waits, timers, visibility, and the cost of running new infrastructure.

SolutionTry it yourself first
  • Choreography doesn’t fit: many steps, long waits and per-partner timeouts would be scattered across services, and “where is booking 123 stuck?” would need correlating events from four topics.
  • A hand-written orchestrator works and keeps infrastructure simple: a saga table with state, deadlines and per-step data, an outbox, a timeout scheduler, and an admin view over the saga table for support. It’s a good choice if the team already runs Kafka and the flow is stable.
  • A workflow engine (Temporal) fits best if flows will grow (cancellations, rebooking, partial refunds), waits are long, and many teams will write workflows: durable timers, retries with backoff, history per booking for support, and workflow code that reads like normal code. The cost: running (or buying) the engine and learning its determinism and versioning rules.
  • Either way: every step and compensation idempotent with partner idempotency keys, reservations with expiry, alerts on sagas past deadline, and a manual-intervention queue for compensations that keep failing.
  • Orchestrator = persisted state machine per saga: state, step, data for compensations, deadline. Each transition: one local transaction updating state + writing the next command to the outbox.
  • Replies correlated by saga id, processed idempotently (expects(step)), tolerant of duplicates and reordering.
  • Timeouts as stored deadlines plus a scheduler; reservations with their own expiry as a second net.
  • Never publish directly inside the transaction (phantom commands) or right after it (lost commands): outbox.
  • Workflow engines (Temporal, Camunda) for long, branching, human-in-the-loop flows: durable timers and history, at the cost of infrastructure and determinism rules.

Check this part

  1. Where does an orchestrator keep track of each saga's progress?

  2. A service never replies. What keeps the order from staying PENDING forever?

  3. The orchestrator receives the same PaymentSucceeded twice. What prevents a second ReserveStock command?

  4. When is a workflow engine like Temporal worth its cost?

An orchestrator owns the saga's state machine: it persists the current step, sends commands, reacts to replies, runs compensations in reverse and handles timeouts with scheduled checks. Persisting state and using the outbox makes it survive crashes; idempotent handlers make duplicates harmless. Workflow engines like Temporal provide durable execution, retries and timers out of the box for long or complex flows.

Key takeaways

  • A saga is a series of local transactions with compensations instead of one big transaction.
  • Compensations are new business actions, like a refund, and must be safe to run twice.
  • PENDING is a real state that users and code must handle.
  • An orchestrator keeps the whole flow in one place, saves its progress, and enforces timeouts.
  • Design step order around the pivot and prefer reservations with expiry.
  • Outbox for every state change plus message; idempotency everywhere.
  • Choreography for short flows, orchestration or a workflow engine as flows grow.
  • Make sagas observable: states, deadlines, stuck-saga alerts and a manual escalation path.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.