Explain the Saga pattern for distributed microservice transactions
Quick Summary: The Saga pattern maintains data consistency across multiple services using a sequence of local ACID transactions and compensating rollback actions on failure, avoiding brittle Two-Phase Commit (2PC) distributed locks.
Direct Interview Answer
Because each microservice owns its private database, traditional ACID transactions or 2PC locks do not scale across independent services. A Saga breaks an operation (like Order → Payment → Inventory) into local transactions.
If step 3 fails, the Saga executes compensating transactions backward (Refund Payment → Cancel Order) to reach eventual consistency.
Detailed Technical Explanation
There are two coordination styles: Choreography (services emit and listen to domain events like PaymentCaptured over Kafka with no central coordinator — great for 2–4 steps) and Orchestration (a dedicated Order Saga Orchestrator state machine commands each participant — far clearer when workflows exceed 4 steps or require timeout retries).
Every Saga participant step and compensating action MUST be idempotent so duplicate message deliveries never double-refund or double-debit.
Practical Walkthrough
Order saga orchestrator state transitions with compensating refund handler.
public enum OrderSagaState { CREATED, PAYMENT_PENDING, INVENTORY_RESERVED, COMPLETED, COMPENSATING, FAILED }
// Compensating step must always be idempotent by orderId:
public void refundPaymentIdempotent(String orderId) {
if (refundLedger.alreadyRefunded(orderId)) {
return; // Safe retry no-op
}
paymentGateway.refund(orderId);
refundLedger.recordRefund(orderId);
}
Safe eventual rollback without cross-service distributed DB locks.
Real-World Production Use Case
E-commerce checkouts, travel bookings, and fintech payouts spanning separate Orders, Wallet, and Inventory microservices.
Common Interview Mistakes to Avoid
- Writing non-idempotent compensating actions that double-refund customers if Kafka redelivers a failure event.
- Ignoring isolation anomalies ("dirty reads" between uncommitted Saga steps) without semantic PENDING statuses.