Architecture
Design Saga Pattern
The saga pattern manages distributed transactions as a sequence of local transactions with compensating actions. If any step fails, compensating transactions undo previous steps.
- Problem β Distributed transactions across microservices
- Solution β Compensating transactions for rollback
- Modes β Choreography (events) vs Orchestration (coordinator)
Sagas are the practical alternative to 2PC: trade immediate consistency for eventual consistency with compensation.
What Is a Saga?
Saga Execution
Choreography vs Orchestration
| Aspect | Choreography | Orchestration |
|---|---|---|
| Coupling | Loose (events) | Tight (direct calls) |
| Visibility | Hard to trace | Easy to trace |
| Complexity | Distributed | Centralized |
| Single Point of Failure | None | Orchestrator |
| Best For | Simple flows | Complex workflows |
Compensating Transactions
Saga State Machine
Practice Exercises
- Design: Implement an order saga with: reserve inventory, charge payment, create shipment. What happens if payment fails?
- Compensation: Design a compensating transaction for "send email notification."
- Monitoring: How would you monitor saga progress and detect stuck sagas?
- Recovery: Design a recovery mechanism for sagas stuck in COMPENSATING state.
What to Learn Next
-> Outbox Pattern Reliable event publishing.
-> Idempotency Safe compensation semantics.
-> Circuit Breaker Saga step resilience.
-> Retry Patterns Retry in saga steps.
-> Design Amazon Checkout saga.
-> Design Uber Trip lifecycle saga.