Video in progress

Staff 🌱 Spring

How do you design a saga for an order process that spans several services: orchestration or choreography?

In a saga each service runs its own local transaction, and if a step fails, the earlier ones are undone with compensating actions. For many steps and a complex process, orchestration (one coordinator); for simple, short flows, choreography (events). State, timeouts and compensation have to be designed from the start.

📖 Answer

An example: order → payment → reserve in the warehouse → shipping.

In choreography each service reacts to events:

OrderCreated → Payment: PaymentCompleted → Inventory: StockReserved → Shipping
StockReservationFailed → Payment: refund → Order: cancelled

There is no center, and services are independent, which is the good side. The bad side: the process isn't written down anywhere, you piece it together from several repos; there's a risk of cyclic dependencies; and it's hard to answer "what stage is this order in right now?".

In orchestration, an OrderSaga state machine sends commands and waits for replies. The process is in one place, so it's easy to observe and change, and timeouts are central. But the coordinator becomes a critical component, and it must not pull other services' logic into itself and turn into a "god service".

In both cases:

  • Compensation is not an "undo". Refunding the money doesn't take you back to "the payment never happened": the customer got an SMS, and the ledger has two entries. Define compensation together with the business.
  • Commands and events can arrive again, so idempotency is a must.
  • Decide in advance what to do when no reply comes: timeouts.
  • There is no isolation, and intermediate states are visible to others. You need "pending" states and a proper way to show them in the UI.
  • The orchestrator's state is stored in the database (Spring State Machine, Temporal, Camunda or your own table).

For complex, long-running processes, workflow engines like Temporal remove a lot of infrastructure code.