Saga Design Pattern in Java: Complete Spring Boot and Kafka Tutorial with Real-World Microservices Example
In a microservices architecture, a business transaction often involves multiple independent services. For example, booking a holiday may require reserving a flight, booking a hotel, and arranging a cab. But what happens if the flight reservation succeeds and the hotel booking fails?
A traditional database transaction cannot easily manage a business process distributed across multiple services and databases. This is where thegitth Saga Design Pattern becomes useful.
In this tutorial, we will understand the Saga Pattern using a real-world holiday booking example. We will explore Saga orchestration and choreography, compensating transactions, Apache Kafka integration, Java implementation, failure handling, retries, and production best practices.
Author: Deep Singh | Category: Java, Spring Boot, Microservices, System Design, Apache Kafka
1. Introduction to Saga Design Pattern
Imagine that you are developing a holiday booking application using Spring Boot microservices. A customer wants to book a complete holiday package that includes:
- Flight reservation through the Flight Service.
- Hotel reservation through the Hotel Service.
- Cab reservation through the Cab Service.
- Payment processing through the Payment Service.
Each service manages its own database. This means that a single business operation involves multiple independent transactions.
Suppose the flight is successfully reserved, but the hotel service reports that no rooms are available. We cannot simply roll back the database transaction of the Flight Service from the Hotel Service.
We need a way to reverse or compensate for the operations that have already completed.
The Saga Pattern solves this problem by dividing a distributed business transaction into a sequence of smaller local transactions. If a step fails, the system executes compensating transactions for previously completed steps according to the business workflow.
2. What Is the Saga Pattern?
The Saga Design Pattern is a distributed transaction management pattern used in microservices architecture. It coordinates a business process across multiple services without requiring one global database transaction.
Each participating service executes its own local transaction. After successfully completing that transaction, it communicates the result to the next step in the Saga.
If a later transaction fails, the Saga executes compensating actions to reverse the business effects of earlier successful transactions.
For example:
Holiday Booking Saga
1. Reserve Flight
2. Reserve Hotel
3. Reserve Cab
4. Confirm Booking
If step 3 fails:
1. Release Hotel Reservation
2. Cancel Flight Reservation
3. Mark Booking as FAILED
The important idea is that a Saga does not provide one atomic database transaction across all services. Instead, it manages consistency through local transactions, events or commands, and compensating actions.
In simple words, Saga is a way to complete a distributed business transaction or recover from a failure using business-level compensation.
3. Saga Pattern with a Real-World Example
Let's understand the Saga Pattern with a holiday booking application. A customer books a holiday package for ₹45,000.
The booking requires three services:
- Flight Service: Reserves an airline ticket.
- Hotel Service: Reserves a hotel room.
- Cab Service: Reserves a cab for airport pickup.
Scenario 1: All Services Succeed
Customer
|
v
Holiday Booking
|
v
Flight Reservation SUCCESS
|
v
Hotel Reservation SUCCESS
|
v
Cab Reservation SUCCESS
|
v
Booking CONFIRMED
All local transactions complete successfully, and the booking is confirmed.
Scenario 2: Hotel Reservation Fails
Customer
|
v
Holiday Booking
|
v
Flight Reservation SUCCESS
|
v
Hotel Reservation FAILED
|
v
Cancel Flight Reservation
|
v
Booking FAILED
The flight reservation has already completed. Since the hotel booking failed, the Saga initiates the flight cancellation as a compensating transaction.
This is the central idea of the Saga Pattern: when a distributed business process cannot continue, the system performs appropriate compensating actions for completed steps.
4. Why Do We Need the Saga Pattern?
In a monolithic application, multiple database operations can often be managed using a single database transaction.
For example:
@Transactional
public void createBooking() {
saveFlightReservation();
saveHotelReservation();
saveCabReservation();
}
If all operations use the same transaction manager and transactional database, a failure can cause the transaction to roll back.
However, in a microservices architecture, each service usually owns its database and transaction boundary.
Flight Service ---- Flight Database
Hotel Service ---- Hotel Database
Cab Service ---- Cab Database
Payment Service ---- Payment Database
A normal Spring @Transactional annotation cannot automatically
roll back changes committed in separate services and databases.
Problems Without Saga
- Partial business transactions may remain incomplete.
- One service cannot directly roll back another service's committed transaction.
- Failures can leave reservations or payments in inconsistent business states.
- Distributed workflows become difficult to coordinate.
- Manual recovery may be required when a downstream operation fails.
Saga helps coordinate these operations using a sequence of local transactions and compensating actions.
5. Saga Architecture
The following diagram illustrates a holiday booking Saga using an orchestrator and multiple Spring Boot microservices.
The Saga Orchestrator manages the overall booking workflow. It sends commands to participating services and processes their success or failure responses.
Kafka can transport commands and result events between the orchestrator and the participating services. Each service remains responsible for its own database transaction.
6. How Does a Saga Workflow Work?
A Saga consists of a sequence of local transactions. Each transaction performs a business operation and produces a result that determines what happens next.
For our holiday booking application:
| Step | Service | Local Transaction | Compensation |
|---|---|---|---|
| 1 | Flight Service | Reserve flight | Cancel flight reservation |
| 2 | Hotel Service | Reserve hotel | Cancel hotel reservation |
| 3 | Cab Service | Reserve cab | Cancel cab reservation |
| 4 | Booking Service | Confirm booking | Mark booking as failed or cancelled |
The Saga progresses when each service reports success. If a step fails, the orchestrator decides which completed steps need compensation.
The exact compensation order is usually the reverse of the completed forward operations, although the business workflow may require additional rules.
7. What Is a Compensating Transaction?
A compensating transaction is a business operation that counteracts the effect of an earlier successful operation.
It is important to understand that compensation is not the same as a database rollback. The original transaction has already committed. Compensation creates a new transaction that corrects the business state.
Example
Forward Transactions:
T1: Reserve Flight SUCCESS
T2: Reserve Hotel SUCCESS
T3: Reserve Cab FAILED
Compensating Transactions:
C2: Cancel Hotel SUCCESS
C1: Cancel Flight SUCCESS
Final Booking Status: FAILED
In this example, the Cab Service failed. The system therefore cancels the hotel and flight reservations that were already completed.
Important Compensation Considerations
- A compensation is a new business transaction, not a technical rollback.
- Compensation can also fail and may require retries or manual recovery.
- Some business operations cannot be fully reversed.
- A compensation may refund money, release inventory, or create a cancellation record.
- Every compensation should be traceable using the original Saga ID.
For example, cancelling a flight reservation may involve a cancellation fee. Therefore, compensation does not always restore the exact original state.
8. Saga Orchestration Pattern
In the orchestration approach, a central component called the Saga Orchestrator controls the distributed workflow.
The orchestrator knows the sequence of operations, sends commands to services, receives their responses, and decides whether to continue or compensate.
Orchestration Workflow
Booking Request
|
v
Saga Orchestrator
|
v
Reserve Flight
|
v
Flight Success?
|
v
Reserve Hotel
|
v
Hotel Success?
|
v
Reserve Cab
|
v
Cab Success?
|
+---- YES ----> Confirm Booking
|
+---- NO -----> Start Compensation
Advantages of Orchestration
- Workflow logic is centralized.
- The execution sequence is easier to understand.
- Compensation logic can be managed in one place.
- It is useful for workflows with many dependent steps.
- Monitoring and workflow status management are easier to organize.
Disadvantages of Orchestration
- The orchestrator becomes an important component that must be highly available.
- Workflow logic can become complicated if too many responsibilities are added.
- Services depend on the command and event contracts defined by the workflow.
9. Saga Choreography Pattern
In the choreography approach, there is no central orchestrator controlling every step. Instead, each service listens for events and performs its own operation.
When a service completes its transaction, it publishes an event. Other services listen for that event and decide what to do next.
Choreography Workflow
Booking Service
|
| Publish BookingCreated
v
Kafka
|
v
Flight Service
|
| Publish FlightReserved
v
Kafka
|
v
Hotel Service
|
| Publish HotelReserved
v
Kafka
|
v
Cab Service
|
| Publish CabReserved
v
Kafka
|
v
Booking Service
|
v
Booking Confirmed
If the Hotel Service fails, it can publish a
HotelReservationFailed event. The services that need
to compensate for earlier operations listen for that event and
execute their cancellation logic.
Advantages of Choreography
- No central workflow controller is required.
- Services can react independently to business events.
- It can work well for relatively simple event-driven workflows.
- Services remain responsible for their own business operations.
Disadvantages of Choreography
- Understanding the complete workflow can become difficult.
- Event dependencies may spread across multiple services.
- Debugging and tracing distributed workflows can be challenging.
- Complex compensation logic can become difficult to coordinate.
10. Orchestration vs Choreography
| Orchestration | Choreography |
|---|---|
| Uses a central Saga Orchestrator. | Uses events exchanged between services. |
| Workflow logic is centralized. | Workflow logic is distributed. |
| The orchestrator sends commands. | Services react to events. |
| Workflow visibility is easier to organize. | End-to-end workflow visibility requires distributed tracing and event correlation. |
| Useful for complex workflows with many dependencies. | Useful for simpler event-driven workflows. |
| Requires an available orchestrator. | Does not require a central workflow controller. |
Both approaches are valid. Choose orchestration when the workflow requires explicit coordination and centralized state management. Choose choreography when independent event reactions are sufficient and the overall workflow remains understandable.
11. Saga Pattern with Apache Kafka
Apache Kafka is commonly used to exchange commands and events between microservices participating in a Saga.
For example, the orchestrator can publish a
ReserveFlightCommand. The Flight Service consumes the
command, performs its local transaction, and publishes either a
FlightReservedEvent or a FlightReservationFailedEvent.
The orchestrator consumes the result and decides which operation should happen next.
Example Kafka Topics
| Topic | Purpose |
|---|---|
| flight.commands | Flight reservation and cancellation commands. |
| flight.events | Flight reservation results. |
| hotel.commands | Hotel reservation and cancellation commands. |
| hotel.events | Hotel reservation results. |
| cab.commands | Cab reservation and cancellation commands. |
| cab.events | Cab reservation results. |
| booking.events | Overall booking status events. |
Every command and event should carry a Saga ID or correlation ID. This helps the orchestrator identify which booking a message belongs to.
Kafka provides durable event storage and independent consumer progress, subject to its configuration. However, it does not automatically make the entire distributed business workflow atomic.
12. Spring Boot Project Structure
For a real microservices implementation, we can separate the application into the following Spring Boot services:
holiday-booking-system
|
|-- booking-service
| |-- controller
| |-- orchestrator
| |-- consumer
| |-- producer
| |-- entity
| |-- repository
| |-- dto
| |-- config
|
|-- flight-service
| |-- consumer
| |-- producer
| |-- service
| |-- entity
| |-- repository
|
|-- hotel-service
| |-- consumer
| |-- producer
| |-- service
| |-- entity
| |-- repository
|
|-- cab-service
| |-- consumer
| |-- producer
| |-- service
| |-- entity
| |-- repository
|
|-- common-events
| |-- command
| |-- event
| |-- dto
Each service owns its business logic and database. The Booking Service coordinates the Saga, while Kafka transports commands and result events.
In production, the shared event contracts should be versioned and managed carefully. Avoid coupling all services to the internal implementation details of another service.
13. Maven Dependencies
The following dependencies are commonly used in a Spring Boot microservice that communicates through Kafka.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
These examples assume a Spring Boot 3.x project using Java 17 or later. Let Spring Boot dependency management select compatible library versions.
The database dependency is included because a production Saga normally persists business data and workflow state. The simplified code below focuses on the message flow and should be extended with persistent repositories before production use.
14. Create Saga Event and Command Classes
First, we need a common structure for commands and events. Every message should include a Saga ID so that the orchestrator can correlate the response with the original booking.
SagaCommand.java
package com.example.booking.dto;
import java.util.UUID;
public record SagaCommand(
UUID sagaId,
String bookingId,
String commandType
) {
}
SagaEvent.java
package com.example.booking.dto;
import java.util.UUID;
public record SagaEvent(
UUID sagaId,
String bookingId,
String service,
String status,
String message
) {
}
The Saga ID identifies the distributed workflow, while the booking ID identifies the business booking.
In a production system, event contracts should also consider a unique event ID, schema version, event timestamp, causation ID, and trace context.
BookingStatus.java
package com.example.booking.dto;
public enum BookingStatus {
PENDING,
FLIGHT_RESERVED,
HOTEL_RESERVED,
CAB_RESERVED,
COMPENSATING,
CONFIRMED,
FAILED
}
These statuses represent the high-level state of our holiday booking workflow.
15. Create the Saga Orchestrator
The Saga Orchestrator coordinates the booking process. It sends the flight reservation command first. After receiving a successful flight response, it sends the hotel reservation command. The same process continues for the cab reservation.
BookingSagaOrchestrator.java
package com.example.booking.orchestrator;
import com.example.booking.dto.SagaCommand;
import com.example.booking.dto.SagaEvent;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class BookingSagaOrchestrator {
private final KafkaTemplate<String, Object> kafkaTemplate;
public BookingSagaOrchestrator(
KafkaTemplate<String, Object> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public void startSaga(
String sagaId,
String bookingId) {
SagaCommand command = new SagaCommand(
java.util.UUID.fromString(sagaId),
bookingId,
"RESERVE_FLIGHT"
);
kafkaTemplate.send(
"flight.commands",
bookingId,
command
);
}
public void handleFlightResult(SagaEvent event) {
if ("SUCCESS".equals(event.status())) {
SagaCommand command = new SagaCommand(
event.sagaId(),
event.bookingId(),
"RESERVE_HOTEL"
);
kafkaTemplate.send(
"hotel.commands",
event.bookingId(),
command
);
} else {
markBookingFailed(event);
}
}
public void handleHotelResult(SagaEvent event) {
if ("SUCCESS".equals(event.status())) {
SagaCommand command = new SagaCommand(
event.sagaId(),
event.bookingId(),
"RESERVE_CAB"
);
kafkaTemplate.send(
"cab.commands",
event.bookingId(),
command
);
} else {
startFlightCompensation(event);
}
}
public void handleCabResult(SagaEvent event) {
if ("SUCCESS".equals(event.status())) {
confirmBooking(event);
} else {
startHotelCompensation(event);
}
}
private void startHotelCompensation(SagaEvent event) {
SagaCommand command = new SagaCommand(
event.sagaId(),
event.bookingId(),
"CANCEL_HOTEL"
);
kafkaTemplate.send(
"hotel.commands",
event.bookingId(),
command
);
}
private void startFlightCompensation(SagaEvent event) {
SagaCommand command = new SagaCommand(
event.sagaId(),
event.bookingId(),
"CANCEL_FLIGHT"
);
kafkaTemplate.send(
"flight.commands",
event.bookingId(),
command
);
}
private void confirmBooking(SagaEvent event) {
System.out.println(
"Booking confirmed: " + event.bookingId()
);
// Persist CONFIRMED status in the booking database.
}
private void markBookingFailed(SagaEvent event) {
System.out.println(
"Booking failed: " + event.bookingId()
);
// Persist FAILED status in the booking database.
}
}
This class demonstrates the basic orchestration idea. Each result advances the workflow or initiates compensation.
For production use, the orchestrator must persist its state, handle compensation results, distinguish retryable from permanent failures, and recover correctly after a restart. The example is not a complete durable Saga state machine.
16. Flight Service Implementation
The Flight Service consumes reservation commands and executes its local business transaction.
FlightCommandConsumer.java
package com.example.flight.consumer;
import com.example.booking.dto.SagaCommand;
import com.example.booking.dto.SagaEvent;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class FlightCommandConsumer {
private final KafkaTemplate<String, Object> kafkaTemplate;
public FlightCommandConsumer(
KafkaTemplate<String, Object> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
@KafkaListener(
topics = "flight.commands",
groupId = "flight-service-group"
)
public void handleCommand(SagaCommand command) {
if ("RESERVE_FLIGHT".equals(command.commandType())) {
reserveFlight(command);
}
if ("CANCEL_FLIGHT".equals(command.commandType())) {
cancelFlight(command);
}
}
private void reserveFlight(SagaCommand command) {
try {
// Execute the local flight reservation transaction.
System.out.println(
"Flight reserved for booking: "
+ command.bookingId()
);
publishResult(command, "SUCCESS",
"Flight reserved successfully");
} catch (Exception exception) {
publishResult(command, "FAILED",
"Flight reservation failed");
}
}
private void cancelFlight(SagaCommand command) {
// Execute the local flight cancellation transaction.
System.out.println(
"Flight cancellation requested: "
+ command.bookingId()
);
publishResult(command, "SUCCESS",
"Flight compensation completed");
}
private void publishResult(
SagaCommand command,
String status,
String message) {
SagaEvent event = new SagaEvent(
command.sagaId(),
command.bookingId(),
"FLIGHT",
status,
message
);
kafkaTemplate.send(
"flight.events",
command.bookingId(),
event
);
}
}
The Flight Service owns the flight reservation and cancellation operations. It does not directly update the Hotel Service database or control the complete Saga.
17. Hotel Service Implementation
The Hotel Service follows the same principle. It receives a reservation command, performs its local transaction, and publishes a result event.
HotelCommandConsumer.java
package com.example.hotel.consumer;
import com.example.booking.dto.SagaCommand;
import com.example.booking.dto.SagaEvent;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class HotelCommandConsumer {
private final KafkaTemplate<String, Object> kafkaTemplate;
public HotelCommandConsumer(
KafkaTemplate<String, Object> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
@KafkaListener(
topics = "hotel.commands",
groupId = "hotel-service-group"
)
public void handleCommand(SagaCommand command) {
if ("RESERVE_HOTEL".equals(command.commandType())) {
reserveHotel(command);
}
if ("CANCEL_HOTEL".equals(command.commandType())) {
cancelHotel(command);
}
}
private void reserveHotel(SagaCommand command) {
try {
// Execute the local hotel reservation transaction.
System.out.println(
"Hotel reserved for booking: "
+ command.bookingId()
);
publishResult(command, "SUCCESS",
"Hotel reserved successfully");
} catch (Exception exception) {
publishResult(command, "FAILED",
"Hotel reservation failed");
}
}
private void cancelHotel(SagaCommand command) {
// Execute the local hotel cancellation transaction.
System.out.println(
"Hotel cancellation requested: "
+ command.bookingId()
);
publishResult(command, "SUCCESS",
"Hotel compensation completed");
}
private void publishResult(
SagaCommand command,
String status,
String message) {
SagaEvent event = new SagaEvent(
command.sagaId(),
command.bookingId(),
"HOTEL",
status,
message
);
kafkaTemplate.send(
"hotel.events",
command.bookingId(),
event
);
}
}
In a real implementation, the Hotel Service should check room availability, create a reservation record, and ensure that the cancellation command is safe to execute more than once.
18. Cab Service Implementation
The Cab Service performs the final reservation step in our example. If it succeeds, the booking workflow can be confirmed.
CabCommandConsumer.java
package com.example.cab.consumer;
import com.example.booking.dto.SagaCommand;
import com.example.booking.dto.SagaEvent;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class CabCommandConsumer {
private final KafkaTemplate<String, Object> kafkaTemplate;
public CabCommandConsumer(
KafkaTemplate<String, Object> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
@KafkaListener(
topics = "cab.commands",
groupId = "cab-service-group"
)
public void handleCommand(SagaCommand command) {
if ("RESERVE_CAB".equals(command.commandType())) {
reserveCab(command);
}
if ("CANCEL_CAB".equals(command.commandType())) {
cancelCab(command);
}
}
private void reserveCab(SagaCommand command) {
try {
// Execute the local cab reservation transaction.
System.out.println(
"Cab reserved for booking: "
+ command.bookingId()
);
publishResult(command, "SUCCESS",
"Cab reserved successfully");
} catch (Exception exception) {
publishResult(command, "FAILED",
"Cab reservation failed");
}
}
private void cancelCab(SagaCommand command) {
// Execute the local cab cancellation transaction.
System.out.println(
"Cab cancellation requested: "
+ command.bookingId()
);
publishResult(command, "SUCCESS",
"Cab compensation completed");
}
private void publishResult(
SagaCommand command,
String status,
String message) {
SagaEvent event = new SagaEvent(
command.sagaId(),
command.bookingId(),
"CAB",
status,
message
);
kafkaTemplate.send(
"cab.events",
command.bookingId(),
event
);
}
}
The example demonstrates how each service owns its local operation. The orchestrator decides whether the complete booking can be confirmed.
19. Implement Compensation Logic
Compensation is one of the most important parts of a Saga implementation. We should not simply mark the booking as failed and ignore the reservations that have already been created.
Suppose the flight and hotel reservations succeed, but the cab reservation fails.
Forward Workflow:
Flight Reserved SUCCESS
Hotel Reserved SUCCESS
Cab Reservation FAILED
Compensation Workflow:
Cancel Hotel REQUESTED
Hotel Cancelled SUCCESS
Cancel Flight REQUESTED
Flight Cancelled SUCCESS
Final Booking Status: FAILED
Compensation Sequence
The orchestrator should track which steps completed successfully. It should compensate only the completed operations that need to be reversed.
For example, if the Cab Service fails, the orchestrator sends
CANCEL_HOTEL and waits for the result. After successful
hotel compensation, it sends CANCEL_FLIGHT.
If hotel compensation fails, the orchestrator must not assume that the hotel reservation was cancelled. It should retry according to policy, record the failure, and provide a recovery mechanism.
A production Saga state machine should explicitly model compensation
states such as COMPENSATING_HOTEL,
COMPENSATING_FLIGHT, and
COMPENSATION_FAILED.
20. Error Handling and Retry Strategy
In distributed systems, failures are expected. Kafka may be temporarily unavailable, a database can time out, or an external service may reject a request.
A reliable Saga implementation must distinguish between temporary failures and permanent business failures.
Temporary Failure
A temporary failure might occur when the database is briefly unavailable. The service can retry the local operation with a controlled backoff.
Permanent Business Failure
A permanent business failure might occur when a hotel has no available rooms. Repeating the same request immediately is unlikely to help. The service should report the failure to the orchestrator.
Recommended Error Handling Strategy
- Use limited retries with exponential backoff for transient failures.
- Classify business errors separately from technical errors.
- Use dead-letter topics for messages that cannot be processed.
- Persist failed Saga states for investigation and recovery.
- Make compensation operations retryable and idempotent.
- Alert operations teams when a Saga remains incomplete for too long.
Do not treat every failed message as a reason to immediately cancel the entire Saga. First determine whether the operation can safely be retried.
21. Saga State Management
A Saga may take seconds or minutes to complete. The orchestrator should not depend only on in-memory Java objects to track its progress.
If the application restarts after reserving a flight but before reserving a hotel, the workflow must be able to recover.
Example Saga State Table
| Column | Purpose |
|---|---|
| saga_id | Unique identifier for the Saga. |
| booking_id | Business booking identifier. |
| current_step | Current workflow step. |
| saga_status | RUNNING, COMPLETED, COMPENSATING, or FAILED. |
| last_event_id | Identifier of the last processed event. |
| created_at | Workflow creation time. |
| updated_at | Last state update time. |
The orchestrator should persist state transitions and correlate incoming events with the correct Saga. It should also support recovery of workflows that were interrupted by application or infrastructure failures.
22. Idempotency and Duplicate Events
Kafka consumers may receive a message again when processing or offset commits fail. A Saga must therefore be designed to handle duplicate commands and events safely.
Imagine that the Flight Service receives the same
RESERVE_FLIGHT command twice. It must not create two
separate reservations for the same booking.
A common approach is to assign every command a unique command ID and store processed command IDs in a database table with a unique constraint.
Processed Command Table
command_id booking_id status
------------------------------------------------
CMD-1001 BOOK-101 SUCCESS
CMD-1002 BOOK-102 SUCCESS
Before executing a command, the service checks whether that command has already been processed. If it has, the service returns the previously recorded result instead of repeating the business operation.
Idempotency is especially important for payment operations, refunds, inventory reservations, and cancellation requests.
23. Transactional Outbox Pattern
A common reliability problem occurs when a service updates its database and publishes an event to Kafka as two separate operations.
For example, the Flight Service may save a reservation successfully
but fail to publish the FlightReserved event.
The orchestrator will not know that the reservation succeeded.
This is known as the dual-write problem.
How Does the Transactional Outbox Pattern Help?
- Save the flight reservation in the service database.
- Save an event record in the Outbox table.
- Commit both changes in the same database transaction.
- A separate publisher reads unpublished outbox records.
- The publisher sends the event to Kafka.
- After successful publication, the record is marked as published.
Flight Service
|
v
Database Transaction
|
+---- Save Flight Reservation
|
+---- Save FlightReserved Event
|
v
Transaction Commit
|
v
Outbox Publisher
|
v
Apache Kafka
|
v
Saga Orchestrator
The outbox pattern makes the local database update and event-record creation atomic within the same database transaction.
It does not automatically provide exactly-once delivery to Kafka. An event may be published more than once if the publisher crashes after sending it but before marking it as published. Consumers should therefore remain idempotent.
24. Saga vs Two-Phase Commit
Saga and Two-Phase Commit (2PC) are different approaches to managing distributed transactions.
| Saga Pattern | Two-Phase Commit |
|---|---|
| Uses a sequence of local transactions. | Uses a prepare phase followed by a commit or rollback phase. |
| Uses compensating transactions for business recovery. | Uses transaction coordination to commit or roll back participants. |
| Supports eventual consistency. | Coordinates atomic commitment across participating resource managers. |
| Does not require one global database transaction. | Requires compatible transaction participants and coordination infrastructure. |
| Useful for long-running microservices workflows. | Can introduce blocking and coordination overhead. |
Saga is often a practical choice for independently deployed microservices that own their databases. It does require careful design of compensation, idempotency, and recovery.
25. Real-World Saga Use Cases
1. E-commerce Order Processing
An order workflow may reserve inventory, process payment, and arrange shipment. If shipment cannot be arranged, the system may release inventory and initiate a refund according to business rules.
2. Payment and Wallet Systems
A wallet transfer may involve debiting one account and crediting another. A distributed workflow must handle failures, duplicate requests, transaction references, and recovery carefully.
3. Travel Booking
Flight, hotel, and cab reservations can be coordinated through a Saga. If one reservation fails, earlier reservations may need to be cancelled.
4. Loan Processing
A loan application may involve customer verification, document verification, risk checks, and approval. A Saga can coordinate independent service operations and their failure handling.
5. Insurance Applications
An insurance workflow may involve customer verification, policy generation, payment, and document creation. Saga can coordinate these steps across services.
26. Saga Pattern Best Practices
A successful Saga implementation requires more than publishing Kafka messages. Consider the following production practices.
1. Keep Each Service Responsible for Its Own Data
A service should manage its own database transactions. Avoid directly updating another microservice's database.
2. Persist Saga State
Store workflow progress so that an orchestrator can recover after a restart or infrastructure failure.
3. Use Unique Saga and Event IDs
Correlation IDs help connect commands, responses, retries, and compensation events to the correct workflow.
4. Make Operations Idempotent
Design commands and compensation operations so that repeated delivery does not create duplicate business effects.
5. Use the Transactional Outbox Pattern
Use an outbox where reliable publication of database changes to Kafka is important.
6. Design Compensation Carefully
Identify how every successful business operation can be reversed or otherwise corrected. Include cases where compensation itself fails.
7. Apply Controlled Retries
Use limited retries and backoff for transient errors. Avoid retrying permanent business failures indefinitely.
8. Monitor Incomplete Sagas
Track workflows that remain in RUNNING, COMPENSATING, or FAILED states for longer than expected.
9. Use Distributed Tracing
Include trace and correlation information in logs and message headers. This helps developers follow one business workflow across multiple services.
10. Protect Sensitive Business Data
Do not publish passwords, authentication tokens, or unnecessary personal and payment information in Kafka events. Apply access controls, encryption, and suitable retention policies.
27. Advantages and Limitations
Advantages
- Supports distributed business workflows across independent services.
- Does not require a single global database transaction.
- Works well with event-driven microservices architectures.
- Allows each service to own its data and local transactions.
- Provides a structured approach to handling partial failures.
- Supports long-running business processes.
Limitations
- Requires careful compensation design.
- Business state may be temporarily inconsistent.
- Debugging distributed workflows can be challenging.
- Duplicate message handling is essential.
- Compensation operations can fail and require recovery.
- Workflow state and monitoring introduce additional complexity.
Saga is not a replacement for every database transaction. Use it when a business process genuinely spans independent transaction boundaries.
28. Saga Pattern Interview Questions
Q1. What is the Saga Design Pattern?
Saga is a distributed transaction management pattern that coordinates a sequence of local transactions across multiple services. It uses compensating transactions to handle failures.
Q2. Why do we need Saga in microservices?
Microservices generally manage their own databases and transactions. Saga helps coordinate a business workflow across these independent transaction boundaries.
Q3. What are the two types of Saga patterns?
The two main approaches are Saga orchestration and Saga choreography.
Q4. What is Saga orchestration?
Orchestration uses a central component called an orchestrator to coordinate workflow steps and compensation.
Q5. What is Saga choreography?
Choreography uses events exchanged between services. Each service reacts to events and performs its own local transaction.
Q6. What is a compensating transaction?
A compensating transaction is a new business operation that counteracts the effect of an earlier successful transaction.
Q7. Is compensation the same as rollback?
No. A rollback reverses uncommitted changes within a transaction. Compensation is a separate transaction that attempts to correct a previously committed business operation.
Q8. Does Saga provide ACID transactions across microservices?
No. Saga coordinates local transactions and typically provides eventual consistency rather than one global ACID transaction.
Q9. Can Kafka be used with Saga?
Yes. Kafka can transport commands and events between participating microservices.
Q10. What happens if a compensating transaction fails?
The system should retry according to a controlled policy, persist the compensation failure, alert operators when necessary, and provide a recovery or manual intervention process.
Q11. What is the dual-write problem?
It occurs when an application writes to a database and publishes an event to Kafka as separate operations. One operation may succeed while the other fails.
Q12. How does the Transactional Outbox Pattern help Saga?
It stores business changes and an event record in the same database transaction. A separate publisher sends the event to Kafka.
Q13. Why is idempotency important in Saga?
Commands and events may be delivered more than once. Idempotency prevents duplicate business operations such as multiple reservations or refunds.
Q14. What is the difference between Saga and Two-Phase Commit?
Saga uses local transactions and compensating actions. Two-Phase Commit coordinates participants through prepare and commit or rollback phases.
Q15. When should we use orchestration instead of choreography?
Orchestration is useful when a workflow has many dependent steps, complex failure handling, or centralized state-management requirements.
Q16. Can a Saga run for several minutes or hours?
Yes. Sagas can manage long-running business processes. They should persist state and support recovery, timeouts, retries, and compensation.
Q17. What happens if the orchestrator crashes?
A durable orchestrator can recover by loading persisted Saga state and processing pending commands or events. In-memory state alone is not sufficient for reliable recovery.
Q18. Is Saga suitable for payment systems?
Yes, but payment workflows require strong idempotency, transaction references, auditability, secure event handling, and carefully designed refund and reconciliation processes.
29. Frequently Asked Questions
Is the Saga Pattern used in Spring Boot microservices?
Yes. Saga can be implemented using Spring Boot services, Kafka, message listeners, local database transactions, and a workflow orchestrator.
Does Saga require Apache Kafka?
No. Saga can use Kafka, RabbitMQ, REST APIs, or other communication mechanisms. The choice depends on the architecture and business requirements.
Does Saga guarantee immediate consistency?
No. Saga generally provides eventual consistency. Different services may temporarily show different business states while the workflow is progressing.
Can Saga compensation fail?
Yes. A compensation may fail because of network problems, unavailable services, or business restrictions. The system must support retry, monitoring, and recovery.
Can we use Saga with a relational database?
Yes. Each microservice can use its own relational database and local transactions. Saga coordinates the overall workflow.
Is Saga suitable for every microservices application?
No. Saga is useful when a business process spans independent transaction boundaries. A simple operation within one service may only need a normal database transaction.
30. Conclusion
The Saga Design Pattern is an important concept in distributed systems and microservices architecture. It helps coordinate business transactions across independent services without depending on one global database transaction.
We started with a holiday booking example and explored how flight, hotel, and cab reservations can be coordinated through a Saga. We also discussed orchestration, choreography, compensating transactions, Kafka integration, and Spring Boot implementation.
For production systems, remember that Saga requires durable workflow state, idempotent operations, controlled retries, reliable event publication, and a clear recovery strategy. The Transactional Outbox Pattern and distributed tracing can help make the overall workflow more reliable and observable.
My suggestion is to build a small Spring Boot project with separate Flight, Hotel, Cab, and Booking services. First implement the successful workflow. Then introduce failures deliberately and implement compensation for each completed operation.
Understanding how a distributed transaction recovers from failure is more valuable than simply knowing how to publish and consume Kafka messages.
Keep learning, build real projects, and focus on solving real-world distributed system problems.
Keep Learning with LearnByDTech
If this tutorial helped you understand the Saga Design Pattern, explore more Java, Spring Boot, Microservices, Apache Kafka, and System Design tutorials on LearnByDTech.
Have you implemented Saga orchestration or choreography in a real-world project? Share your experience and questions in the comments.
Learn. Build. Share.