Queues & Background Processing in Depth · Workflows and Operations
Sagas with Messaging
Coordinate multi-service transactions using events or commands.
A saga splits a business transaction across services into local transactions with compensations. Choreography: services react to each other's events (OrderCreated → PaymentCharged → StockReserved); simple for 2–3 steps but hard to trace. Orchestration: a coordinator sends commands and tracks state (often a workflow engine). Use the outbox for reliable publishing, idempotent handlers, timeouts for missing replies, and semantic locks ("pending" states) to handle isolation.
Saga styles
| Criterion | Choreography | Orchestration |
|---|---|---|
| Coupling | Services know events | Coordinator knows steps |
| Visibility | Distributed; needs tracing | Central state |
| Changing the flow | Touches many services | Change the orchestrator |
| Failure handling | Each service compensates | Coordinator drives compensation |
| Best for | Short, stable flows | Long or complex flows |
Orchestrated order saga
Orchestrator → Inventory: ReserveStock(order) → StockReserved | StockUnavailable
Orchestrator → Payments: ChargePayment(order) → PaymentCharged | PaymentDeclined
on PaymentDeclined → Inventory: ReleaseStock(order) → order CANCELLED
Orchestrator → Shipping: CreateShipment(order) → ShipmentCreated → order CONFIRMED
Timeouts: no reply in 30 s → retry command (idempotent) → after N → compensate
Common pitfalls
- Compensations that can fail without retries.
- Missing timeouts for lost replies.
- Choreography chains no one can visualize.
Key points
- Local transactions + compensations
- Choreography for short flows
- Orchestration for complex flows
Further reading: microservices.io: Saga
Practice questions
What is a semantic lock in a saga?
Answer
Marking a resource with a pending state (e.g., order PENDING) during the saga so other operations know it's mid-transaction, compensating for the lack of isolation.
Why do sagas need timeouts?
Answer
Replies can be lost or services can be down; without timeouts the saga waits forever instead of retrying or compensating.
Open in the app to mark lessons complete, take notes and track your progress.