What Is Saga Pattern?
The Saga pattern manages distributed transactions across multiple microservices. Instead of one ACID transaction spanning services, a saga breaks it into a sequence of local transactions with compensating actions (rollbacks) if any step fails. It's essential for data consistency in microservices.
How Saga Pattern Works
Order saga: Reserve Inventory → Charge Payment → Ship Order. If Payment fails: compensate by Unreserving Inventory. Each service handles its local transaction and publishes events. The saga coordinator (or choreography) ensures all steps complete or all compensations run.
Key Concepts
- Compensating Transaction — The undo action for each step — unreserve inventory, refund payment, cancel shipment
- Choreography — Services react to events — no central coordinator. Simpler but harder to monitor
- Orchestration — A central saga coordinator directs the sequence — easier to understand and debug
Frequently Asked Questions
Saga vs two-phase commit?
Two-phase commit (2PC) locks resources across services — doesn't scale. Sagas use eventual consistency with compensations — more complex logic but better performance and resilience.