API / Microservices Design Patterns Interview Questions
What is the Saga pattern and how does it manage distributed transactions across microservices?
The Saga pattern manages a long-running business transaction that spans multiple services without using a distributed two-phase commit (2PC). A Saga is a sequence of local transactions: each step performs a local commit and then publishes an event or sends a command to trigger the next step. If a step fails, the Saga executes compensating transactions — semantic undos — for each previously completed step.
Example — Place Order Saga:
FORWARD STEPS 1. Order Service â INSERT order (status=PENDING) â emit OrderCreated 2. Inventory Svc â UPDATE stock (reserve qty) â emit StockReserved OR StockReservationFailed 3. Payment Svc â charge customer card â emit PaymentProcessed OR PaymentFailed 4. Order Service â UPDATE order (status=CONFIRMED) COMPENSATION (if PaymentFailed at step 3) â Inventory Svc â release reservation (compensate step 2) â Order Svc â UPDATE order (status=CANCELLED) (compensate step 1)
Key properties:
- ACD, not full ACID — Sagas provide Atomicity (all steps complete or are compensated), Consistency (at application level), and Durability, but not Isolation. Intermediate states are visible to concurrent operations, requiring careful handling of anomalies such as dirty reads and lost updates.
- Eventual consistency — the system reaches a globally consistent state eventually, not immediately after each step.
- Two coordination styles — Choreography (event-driven, no central coordinator) and Orchestration (central saga orchestrator directs participants). See Q11 for the comparison.
Sagas are the standard replacement for distributed transactions in microservice architectures because they work across heterogeneous data stores and do not require all participating services to hold locks simultaneously.
More Related questions...