Saga Pattern in Java Microservices
Learn Saga Pattern in Java with distributed transactions, choreography saga, orchestration saga, Kafka integration, compensation transactions, Spring Boot implementation, banking examples, and interview questions.
What You Will Learn
- What is Saga Pattern?
- Why Saga is Needed
- Distributed Transaction Challenges
- Choreography Saga
- Orchestration Saga
- Compensation Transactions
- Kafka Integration
- Spring Boot Examples
- Banking Use Cases
- Enterprise Architecture
- Interview Questions
Introduction
In Monolithic Applications:
Single Database
Single Transaction
Single Commit
Example:
Create Order
Reserve Inventory
Process Payment
Create Shipment
Everything happens in:
@Transactional
If one step fails:
Rollback Entire Transaction
Easy.
Problem In Microservices
Consider:
Order Service
Inventory Service
Payment Service
Shipping Service
Each service has:
Own Database
Question:
How do we rollback
across multiple databases?
Traditional transactions do not work.
Saga Pattern solves this problem.
What is Saga Pattern?
Saga Pattern manages distributed transactions across multiple microservices.
Instead of:
One Large Transaction
Use:
Multiple Local Transactions
connected by events.
Purpose of Saga Pattern
Primary Goal:
Maintain Data Consistency
Across Microservices
without using:
Distributed Database Transactions
Traditional Transaction
flowchart LR
A[Order]
B[Inventory]
C[Payment]
D[Shipping]
A --> B
B --> C
C --> D
Single transaction.
Rollback everything.
Microservice Challenge
flowchart LR
A[Order Service]
B[Inventory Service]
C[Payment Service]
D[Shipping Service]
A --> B
B --> C
C --> D
Each service owns its own database.
No global transaction exists.
Saga Solution
flowchart LR
A[Order Service]
B[Inventory Service]
C[Payment Service]
D[Shipping Service]
A --> B
B --> C
C --> D
Each step commits independently.
Failures handled through:
Compensation Transactions
Core Idea
Saga consists of:
Local Transaction
+
Compensation Transaction
Example Order Flow
Create Order
Reserve Inventory
Charge Payment
Ship Product
Successful Saga
flowchart LR
A[Create Order]
B[Reserve Inventory]
C[Charge Payment]
D[Create Shipment]
A --> B
B --> C
C --> D
Everything succeeds.
Failure Scenario
Suppose:
Payment Failed
Workflow:
Order Created
Inventory Reserved
Payment Failed
Need rollback.
Compensation Flow
flowchart LR
A[Create Order]
B[Reserve Inventory]
C[Payment Failed]
D[Release Inventory]
E[Cancel Order]
A --> B
B --> C
C --> D
D --> E
Compensation Transaction
Normal Transaction:
Reserve Inventory
Compensation:
Release Inventory
Examples:
| Action | Compensation |
|---|---|
| Create Order | Cancel Order |
| Reserve Inventory | Release Inventory |
| Debit Account | Credit Account |
| Create Shipment | Cancel Shipment |
Saga Architecture
flowchart LR
A[Client]
B[Order Service]
C[Inventory Service]
D[Payment Service]
E[Shipping Service]
A --> B
B --> C
C --> D
D --> E
Types of Saga
Choreography Saga
Orchestration Saga
Choreography Saga
Services communicate using events.
No central coordinator.
Choreography Flow
flowchart LR
A[Order Created Event]
B[Inventory Reserved Event]
C[Payment Completed Event]
D[Shipment Created Event]
A --> B
B --> C
C --> D
Each service listens for events.
Choreography Example
Order Service publishes:
OrderCreated
Inventory Service consumes:
OrderCreated
Then publishes:
InventoryReserved
Payment Service consumes:
InventoryReserved
And so on.
Choreography Architecture
flowchart LR
A[Order Service]
B[Kafka]
C[Inventory Service]
D[Payment Service]
E[Shipping Service]
A --> B
B --> C
B --> D
B --> E
Benefits of Choreography
✅ Simple
✅ Event Driven
✅ No Central Coordinator
✅ Highly Scalable
Drawbacks of Choreography
❌ Hard To Debug
❌ Event Chains Become Complex
❌ Difficult Monitoring
Orchestration Saga
Uses a central coordinator.
Coordinator controls workflow.
Orchestration Flow
flowchart LR
A[Saga Orchestrator]
B[Order Service]
C[Inventory Service]
D[Payment Service]
E[Shipping Service]
A --> B
A --> C
A --> D
A --> E
Orchestrator Responsibilities
Invoke Services
Track Progress
Handle Failures
Trigger Compensation
Banking Transfer Example
Transfer:
Debit Account A
Credit Account B
Successful Banking Saga
flowchart LR
A[Debit Account]
B[Credit Account]
C[Transfer Complete]
A --> B
B --> C
Failed Banking Saga
Credit fails:
flowchart LR
A[Debit Account]
B[Credit Failed]
C[Compensate]
D[Refund Account]
A --> B
B --> C
C --> D
Insurance Example
Claim Processing:
Create Claim
Fraud Check
Approve Claim
Generate Payment
Insurance Saga
flowchart LR
A[Create Claim]
B[Fraud Check]
C[Approve Claim]
D[Generate Payment]
A --> B
B --> C
C --> D
Compensation Example
If payment fails:
Reverse Approval
Cancel Claim
Notify Customer
E-Commerce Example
Workflow:
Place Order
Reserve Inventory
Process Payment
Arrange Shipping
Retail Saga Flow
flowchart LR
A[Place Order]
B[Reserve Inventory]
C[Payment]
D[Shipping]
A --> B
B --> C
C --> D
Kafka Integration
Kafka is commonly used for Saga communication.
Events:
OrderCreated
InventoryReserved
PaymentCompleted
ShipmentCreated
Kafka Saga Architecture
flowchart LR
A[Order Service]
B[Kafka Topic]
C[Inventory Service]
D[Payment Service]
E[Shipping Service]
A --> B
B --> C
B --> D
B --> E
Spring Boot Command Example
Order Event:
public record OrderCreatedEvent(
String orderId) {
}
Event Publisher
kafkaTemplate.send(
"orders",
event);
Event Consumer
@KafkaListener(
topics = "orders")
public void process(
OrderCreatedEvent event) {
}
Saga State Tracking
Often stored in:
Saga Log
Saga Table
Workflow Database
Saga State Example
Saga Id
Current Step
Status
Timestamp
Saga State Flow
flowchart LR
A[Started]
B[Inventory Completed]
C[Payment Completed]
D[Finished]
A --> B
B --> C
C --> D
Real Enterprise Examples
Banking
Fund Transfers
Account Opening
Loan Processing
Insurance
Claim Processing
Policy Issuance
Premium Collection
Retail
Order Processing
Inventory Management
Travel Booking
Flight Booking
Hotel Reservation
Payment Processing
Healthcare
Patient Registration
Insurance Verification
Saga vs Two Phase Commit
| Feature | Saga | 2PC |
|---|---|---|
| Scalability | High | Low |
| Performance | High | Low |
| Microservices | Excellent | Poor |
| Rollback | Compensation | Global Rollback |
| Availability | High | Lower |
Saga vs Event Sourcing
| Feature | Saga | Event Sourcing |
|---|---|---|
| Distributed Transaction | Yes | No |
| Event Storage | Optional | Required |
| Focus | Consistency | Audit History |
Benefits
✅ Distributed Transaction Support
✅ Microservice Friendly
✅ High Scalability
✅ Event Driven
✅ No Distributed Locks
✅ Cloud Native
Limitations
❌ Complex Design
❌ Compensation Logic Required
❌ Eventual Consistency
❌ Hard Debugging
When To Use Saga
Use Saga when:
Microservices
Distributed Transactions
Multiple Databases
Cloud Native Systems
When NOT To Use Saga
Avoid when:
Monolithic Applications
Single Database
Simple CRUD Systems
Real Enterprise Architecture
flowchart LR
A[Client]
B[API Gateway]
C[Order Service]
D[Kafka]
E[Inventory Service]
F[Payment Service]
G[Shipping Service]
A --> B
B --> C
C --> D
D --> E
D --> F
D --> G
Interview Questions
What is Saga Pattern?
A pattern for managing distributed transactions across microservices.
Why Use Saga?
To maintain consistency without distributed transactions.
Types of Saga?
Choreography
Orchestration
What is Compensation?
Rollback logic for completed local transactions.
Kafka Role?
Used to exchange saga events.
Saga vs 2PC?
Saga uses compensation.
2PC uses distributed commits.
Biggest Benefit?
Scalable distributed transactions.
Biggest Drawback?
Complexity.
Key Takeaways
- Saga Pattern manages distributed transactions.
- Uses local transactions and compensation actions.
- Common in Microservices Architecture.
- Supports Choreography and Orchestration models.
- Frequently implemented using Kafka.
- Widely used in Banking, Insurance, Retail, Travel, and Healthcare systems.
- One of the most important patterns for enterprise microservices.