00:00

Saga Design Pattern with Apache Kafka

Last updated:

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.

Definition: A saga keeps data consistent across services without a distributed transaction: each step is a local transaction, and every step that can be followed by a failure has a compensating action.
StepActionCompensation
Order serviceCreate order as PENDINGMark order CANCELLED
Payment serviceCharge the customerRefund the payment
Inventory serviceReserve stockRelease the stock
Order serviceMark order CONFIRMEDnone (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

Choreography saga for an orderThe order service publishes OrderCreated to order-events. The payment service consumes it and publishes either PaymentCompleted or PaymentFailed to payment-events. On PaymentCompleted, the inventory service reserves stock and publishes StockReserved to inventory-events, and the order service confirms the order. On PaymentFailed, the order service runs its compensation and cancels the order. order servicePENDING order-events payment servicecharge payment-events inventoryreserve stock inventory-events OrderCreated Completed StockReserved PaymentFailed → cancel StockReserved → confirm
In a choreography saga, each service reacts to the previous service's event; no central coordinator exists.

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.

ChoreographyOrchestration
ControlDistributedCentral orchestrator
Best for2–4 stepsMany steps, timeouts, branching
CouplingServices know event typesServices know only their commands
VisibilityNeeds tracing to see the flowSaga 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.

SagaEvent.java
package com.javabytechie.kafka;

public record SagaEvent(String orderId, String type, double amount) {
}
SagaParticipants.java
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 -> { }
        }
    }
}
SagaApplication.java
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));
        };
    }
}
application.yml
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):

Output
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