Saga Pattern
A pattern for managing distributed transactions across multiple services by coordinating a sequence of local transactions with compensating actions for failures.
Also known as: Saga, Long-Running Transaction, Distributed Saga
Category: Software Development
Tags: architecture, software-design, patterns, distributed-systems, domain-driven-design
Explanation
The Saga Pattern is a design pattern for managing data consistency across multiple services in a distributed system without using traditional distributed transactions (two-phase commit). Instead of a single atomic transaction spanning multiple services, a saga breaks the operation into a sequence of local transactions, each updating a single service. If any step fails, compensating transactions are executed to undo the preceding steps.
**The problem it solves:**
In a microservices architecture, each service owns its own database. A business operation that spans multiple services (e.g., placing an order that involves inventory, payment, and shipping) cannot use a single database transaction. Traditional distributed transactions (2PC) are too slow, brittle, and create tight coupling. Sagas provide eventual consistency without these drawbacks.
**Two coordination approaches:**
- **Choreography**: Each service publishes events that trigger the next step. No central coordinator—services react to events independently. Simpler for small sagas but can become hard to follow as complexity grows
- **Orchestration**: A central saga orchestrator directs each step, telling services what to do and handling responses. More explicit control flow but introduces a single point of coordination
**How it works (example: Order Placement):**
1. Order Service creates order (status: PENDING)
2. Payment Service charges customer
3. Inventory Service reserves items
4. Shipping Service schedules delivery
5. Order Service confirms order (status: CONFIRMED)
**If step 3 fails:**
1. Inventory Service reports failure
2. Compensating transaction: Payment Service refunds customer
3. Compensating transaction: Order Service cancels order (status: CANCELLED)
**Key principles:**
- **Compensating transactions**: Every step that can fail must have a corresponding undo operation
- **Idempotency**: Each step must be idempotent—safe to retry without side effects
- **Eventual consistency**: The system may be temporarily inconsistent during saga execution
- **Isolation concerns**: Concurrent sagas may see intermediate states; semantic locks or countermeasures may be needed
**When to use:**
Sagas are essential in microservices architectures where business operations span multiple services. They're the standard approach to distributed data consistency in event-driven systems. For monolithic applications or operations within a single database, traditional ACID transactions remain simpler and more appropriate.
Related Concepts
← Back to all concepts