Video in progress
How do you build an order process spanning several services as a saga on top of Kafka: choreography or orchestration?
In choreography each service reacts to another's event. It starts out simple, but as steps are added nobody sees the whole process. In orchestration a single orchestrator keeps the state and sends commands. With more than 3-4 steps and complex compensations, I choose orchestration.
📖 Answer
The process: create the order → reserve the payment → reserve stock → schedule delivery. If any step fails, the earlier ones are compensated.
Choreography:
OrderCreated → payment reserves and emits PaymentReserved → inventory reserves and emits StockReserved → shipping... If there's a StockFailed, payment listens for it and refunds the money.
In a small chain it's elegant: no central component, and the services are independent. But over time, to answer "where did order 7 get stuck?" you wander through the logs of 5 services. Adding a new step means changing several services, and cycles can appear.
Orchestration:
OrderSaga (a separate service or inside the order service) keeps the state in the DB and writes to command topics: ReservePayment to payment.commands, and waits for the reply on order.saga.replies.
saga_id | order_id | step | status | updated_at
42 | 1001 | RESERVE_STOCK | WAITING | 10:15:03
The process is visible in one place, timeouts are centralized ("no reply in 10 minutes means compensate"), and it's easy to observe. The cost is that the orchestrator is an extra component, and if done wrong, all the business logic piles up in it.
In both cases there are must-haves:
- every step and compensation is idempotent, because commands arrive more than once;
- the state change and the command send go through an outbox, so there's no dual write;
- key =
orderId, so one saga's messages stay in order; - a compensation is not an "undo" but a business action: refunding the money, sometimes with a notification to the customer.
If there are many processes and they're long (days), I also look at a workflow engine like Temporal: it manages the saga state, retries and timers itself.
Sign up to mark studied questions and save your progress.