Saga Design Pattern with Apache Kafka
In a microservices system, one business operation often changes data in several services. Placing an order may charge a payment, reserve stock and book a delivery, each in its own database. A single ACID transaction across those databases is not possible, and two-phase commit does not fit services that communicate through Kafka.
The Saga pattern solves this with a sequence of local transactions connected by events, plus compensating transactions that undo earlier steps when a later one fails. This tutorial shows how to build sagas on Kafka, how to publish events reliably with the outbox pattern, and how to run a small choreography example in Spring Boot.
1. What Is the Saga Pattern?
A saga is a sequence of local transactions. Each step commits in its own service and publishes an event that triggers the next step. If a step fails, the saga runs compensating actions for the steps that already completed.
| Step | Action | Compensation |
|---|---|---|
| Order service | Create order as PENDING | Mark order CANCELLED |
| Payment service | Charge the customer | Refund the payment |
| Inventory service | Reserve stock | Release the stock |
| Order service | Mark order CONFIRMED | none (final step) |
2. Why Use Kafka for Sagas?
- Durable events: saga events survive service restarts and are replayed after failures.
- Loose coupling: services react to events instead of calling each other synchronously.
- Ordering per saga: using the order ID as the key keeps all events of one saga in one partition, in order.
- Audit trail: the topics record every step of every saga.
3. Choreography and Orchestration
3.1 Choreography
Each service listens for events and decides what to do next. It is simple for short flows and has no single point of control, but the overall flow is spread across services and becomes hard to follow as steps are added.
3.2 Orchestration
A dedicated orchestrator (often part of the order service) sends commands such as ChargePayment to command topics, listens for replies, and keeps the saga state, for example in a database table or a Kafka Streams state store. The flow is explicit in one place, which makes complex sagas with many steps and timeouts easier to manage.
| Choreography | Orchestration | |
|---|---|---|
| Control | Distributed | Central orchestrator |
| Best for | 2–4 steps | Many steps, timeouts, branching |
| Coupling | Services know event types | Services know only their commands |
| Visibility | Needs tracing to see the flow | Saga state in one place |
4. Publishing Events Reliably: The Outbox Pattern
A saga step must change its database and publish an event. If the service commits to the database and crashes before sending to Kafka, the saga stops; if it sends first and the database commit fails, other services act on a change that never happened. Kafka transactions do not cover an external database.
The transactional outbox writes the event into an outbox table in the same local transaction as the business change. A separate process publishes the rows to Kafka. With Debezium, a Kafka Connect source connector reads the outbox table from the database's change log, and its Outbox Event Router transformation routes each row to a topic based on a column such as aggregatetype, using the aggregate ID as the record key. Delivery is at-least-once, so consumers must handle duplicates.
5. Spring Boot Example: A Choreography Saga
This demo runs the three services in one application so that you can see the whole flow; in production, each listener lives in its own service. Order ORD-1 succeeds; ORD-2 exceeds the customer's credit limit and is compensated.
package com.javabytechie.kafka;
public record SagaEvent(String orderId, String type, double amount) {
}
package com.javabytechie.kafka;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
@Component
public class SagaParticipants {
private static final double CREDIT_LIMIT = 5000;
private final KafkaTemplate<String, SagaEvent> kafka;
public SagaParticipants(KafkaTemplate<String, SagaEvent> kafka) {
this.kafka = kafka;
}
// Payment service: local transaction "charge", then publish the outcome
@KafkaListener(topics = "order-events", groupId = "payment-service")
public void onOrderCreated(SagaEvent e) {
String outcome = e.amount() <= CREDIT_LIMIT ? "PAYMENT_COMPLETED" : "PAYMENT_FAILED";
System.out.println("payment: " + e.orderId() + " -> " + outcome);
kafka.send("payment-events", e.orderId(), new SagaEvent(e.orderId(), outcome, e.amount()));
}
// Inventory service: reserve stock only after a successful payment
@KafkaListener(topics = "payment-events", groupId = "inventory-service")
public void onPayment(SagaEvent e) {
if (e.type().equals("PAYMENT_COMPLETED")) {
System.out.println("inventory: " + e.orderId() + " -> STOCK_RESERVED");
kafka.send("inventory-events", e.orderId(), new SagaEvent(e.orderId(), "STOCK_RESERVED", e.amount()));
}
}
// Order service: finish the saga or compensate
@KafkaListener(topics = {"payment-events", "inventory-events"}, groupId = "order-service")
public void onSagaStep(SagaEvent e) {
switch (e.type()) {
case "PAYMENT_FAILED" -> System.out.println("order: " + e.orderId() + " -> CANCELLED (compensated)");
case "STOCK_RESERVED" -> System.out.println("order: " + e.orderId() + " -> CONFIRMED");
default -> { }
}
}
}
package com.javabytechie.kafka;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaAdmin;
import org.springframework.kafka.core.KafkaTemplate;
@SpringBootApplication
public class SagaApplication {
public static void main(String[] args) {
SpringApplication.run(SagaApplication.class, args);
}
@Bean
KafkaAdmin.NewTopics sagaTopics() {
return new KafkaAdmin.NewTopics(
TopicBuilder.name("order-events").partitions(3).build(),
TopicBuilder.name("payment-events").partitions(3).build(),
TopicBuilder.name("inventory-events").partitions(3).build());
}
@Bean
ApplicationRunner placeOrders(KafkaTemplate<String, SagaEvent> kafka) {
return args -> {
// Order service: local transaction "create order as PENDING", then publish
kafka.send("order-events", "ORD-1", new SagaEvent("ORD-1", "ORDER_CREATED", 250));
kafka.send("order-events", "ORD-2", new SagaEvent("ORD-2", "ORDER_CREATED", 9000));
};
}
}
spring:
kafka:
bootstrap-servers: localhost:9092
producer:
value-serializer: org.springframework.kafka.support.serializer.JacksonJsonSerializer
consumer:
auto-offset-reset: earliest
value-deserializer: org.springframework.kafka.support.serializer.JacksonJsonDeserializer
properties:
spring.json.trusted.packages: com.javabytechie.kafka
The Maven dependencies are the same as in Apache Kafka with Spring Boot. TopicBuilder without replicas(...) uses the broker's default replication factor.
Output (Spring Boot 4.2.0, local Kafka 4.4 broker):
payment: ORD-2 -> PAYMENT_FAILED
payment: ORD-1 -> PAYMENT_COMPLETED
inventory: ORD-1 -> STOCK_RESERVED
order: ORD-2 -> CANCELLED (compensated)
order: ORD-1 -> CONFIRMED
ORD-1 passes the payment step, so inventory reserves stock and the order service confirms the order. ORD-2 is above the credit limit; the payment service publishes PAYMENT_FAILED, inventory ignores it, and the order service compensates by cancelling the order. The two sagas run independently, so their lines can interleave differently; the steps of one saga always appear in order because each step is triggered by the previous step's event. A real implementation would update each service's database through the outbox pattern instead of printing.
6. Common Mistakes
- Publishing events outside the database transaction ("dual write"), which loses or invents saga steps after a crash.
- Non-idempotent steps: Kafka delivers at least once, so a payment handler must not charge twice for the same order ID.
- No compensation for a step that can be followed by a failure.
- Random keys: without the saga ID as the key, events of one saga can be processed out of order.
- No timeout handling: a saga waiting for a reply that never comes stays pending forever; orchestrators need deadlines.
7. Best Practices
- Use the outbox pattern (for example with Debezium) for every step that writes to a database and publishes an event.
- Make every handler idempotent, with a processed-event table or unique constraints on the saga ID and step.
- Design compensations as business actions (refund, release) rather than database rollbacks; they must also be idempotent.
- Choose orchestration for long or branching sagas, and add tracing headers to follow sagas across services.
- Accept eventual consistency in the UI, for example by showing "order pending" until the saga completes.
8. Conclusion
The Saga pattern replaces distributed transactions with local transactions linked by Kafka events and undone by compensating actions. Choreography suits short flows, orchestration suits complex ones, and the transactional outbox, often with Debezium, makes each step's database change and event consistent. Combine it with idempotent consumers and per-saga keys for a reliable design.
9. References
Saga Pattern with Kafka Interview Questions and Answers
Common interview questions on Saga Pattern with Kafka, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What is a compensating transaction?
Answer: A business action that semantically undoes a completed saga step, such as a refund for a payment or releasing reserved stock. It is not a database rollback, because the original step has already committed and may have been seen by others.
Intermediate questions
Q. When would you choose orchestration over choreography?
Answer: When the saga has many steps, conditional branches or timeouts, or when you need one place to see and control its state. Choreography works well for a few steps but spreads the flow across services, which makes larger sagas hard to understand and change.
Q. What is the dual-write problem and how does the outbox pattern solve it?
Answer: A service that writes to its database and then sends to Kafka can fail between the two, leaving them inconsistent. The outbox pattern writes the event into an outbox table in the same local transaction as the business change, and a relay such as Debezium publishes it afterwards. The event is published if and only if the transaction commits, possibly more than once.
Tricky and scenario questions
Q. Can Kafka transactions replace the outbox pattern in a saga?
Answer: Not when the step also writes to a database. Kafka transactions make writes to Kafka topics and consumer offsets atomic, but they do not include an external database. Spring can synchronise a Kafka transaction with a database transaction, yet a crash between the two commits can still make them diverge. The outbox keeps one source of truth: the database.
Q. A payment event is delivered twice. How do you prevent a double charge?
Answer: Make the payment step idempotent. Store processed saga IDs (or event IDs) in the payment database within the same transaction as the charge, and skip events already recorded. Pass an idempotency key to the payment provider as well, so a retried external call does not charge twice.