Domain-Driven Design (50 Qs)•Part 3: Advanced Architecture & Production Patterns (Senior / Lead)
What is the SAGA Pattern (Choreography vs Orchestration) in DDD microservices?
senior LevelCode ExampleSystem DesignMicroservicesData Structures
In Simple Words: Manages distributed business transactions across multiple Bounded Contexts without 2PC:
- Choreography: Event-driven. Each service listens for events and independently executes its local transaction:
OrderServiceemitsOrderCreated->PaymentServicelistens and charges card -> emitsPaymentCompleted->InventoryServicereserves stock.- Simple for small workflows; difficult to track and debug as services scale.
- Orchestration: A central Saga Orchestrator microservice (e.g. using Temporal, AWS Step Functions, or custom state machine) sends explicit commands to services and tracks status. If a step fails, the orchestrator triggers compensating transactions to roll back.
text
Saga Patterns:
Choreography: [Service A] ──(Event)──► [Service B] ──(Event)──► [Service C]
Orchestration: [Saga Orchestrator]
├─► Command 1 ──► [Service A]
├─► Command 2 ──► [Service B]
└─► (If Fail) ──► Compensate A