Why Distributed Transactions Are a Problem?

In microservices:
-
Each service has its own database
-
Traditional 2PC (XA transactions) donβt scale well
-
High latency & tight coupling
π So we use Saga Pattern.
πΉ What is Saga Pattern?
A Saga is a sequence of local transactions, where:
-
Each service performs its transaction
-
If one fails β compensating actions undo previous steps
πΉ Types of Saga
1οΈβ£ Choreography-based Saga
-
No central controller
-
Services react to events
π Example:
2οΈβ£ Orchestration-based Saga
-
Central orchestrator controls flow
-
Services respond to commands
π Example:
πΉ Example Flow (E-commerce)
-
Order Service β create order
-
Payment Service β deduct money
-
Inventory Service β reduce stock
β If inventory fails:
-
Payment Service β refund
-
Order Service β cancel order
πΉ Eventual Consistency
-
Data is not consistent immediately
-
Becomes consistent over time
πΉ Saga vs 2PC
| Aspect | Saga | 2PC |
|---|---|---|
| Coupling | Loose | Tight |
| Performance | High | Slow |
| Scalability | Excellent | Poor |
| Failure Handling | Compensating | Blocking |
πΉ Implementation Tools
-
Kafka / RabbitMQ
-
Spring State Machine
-
Temporal
-
Camunda
πΉ Real-World Use Case
π³ Payment success
π¦ Inventory failure
β© Refund triggered automatically
β Interview One-Liner
βSaga handles distributed transactions by breaking them into local transactions with compensating actions.β
πΉ Follow-Up Questions Interviewers Ask
-
Saga vs Eventual Consistency?
-
How do you handle duplicate events?
-
How do you ensure idempotency?