System Design (50 Qs)•Part 3: Distributed Transactions, Consensus & Reliability (26 - 36)
The Saga Pattern: Orchestration vs Choreography for Microservices.
In Simple Words: In microservice architectures where each service owns its private database, ACID multi-database transactions are anti-patterns. A Saga is a sequence of local transactions where each step publishes an event. If any step fails, the Saga executes Compensating Transactions backwards to undo previous actions.
| Aspect | Choreography-Based Saga | Orchestration-Based Saga |
|---|---|---|
| Coordination | Decentralized; services react to pub/sub events | Centralized orchestrator state machine directs steps |
| Visibility | Difficult to track execution status | Crystal clear workflow visibility and auditing |
| Coupling | Loosely coupled | Orchestrator holds business workflow logic |
| Best For | Simple workflows (2–4 services) | Complex enterprise workflows with branching logic |
Architecture Flowchart
sequenceDiagram
autonumber
participant Orch as Order Saga Orchestrator
participant OrderSvc as Order Service
participant PaySvc as Payment Service
participant InvSvc as Inventory Service
Orch->>OrderSvc: 1. Create Pending Order
OrderSvc-->>Orch: Order Created
Orch->>PaySvc: 2. Process Payment ($150)
PaySvc-->>Orch: Payment Successful
Orch->>InvSvc: 3. Reserve Inventory (SKU-99)
InvSvc-->>Orch: FAILED (Out of Stock!)
Note over Orch,PaySvc: Trigger Compensating Transactions
Orch->>PaySvc: 4. Refund Payment ($150)
PaySvc-->>Orch: Refund Confirmed
Orch->>OrderSvc: 5. Mark Order CANCELLED