Saga choreography: one business transaction across several services
When an order touches the order, payment and inventory services, no single database transaction can cover all three. A saga runs one local transaction per service and undoes earlier steps with compensations when a later one fails. This page runs a choreographed saga with a separate H2 database per service, then shows what goes wrong: missing isolation, duplicate and reordered events, and services that never answer.
Contents
Why business transactions across services need sagas
Placing an order in a microservice system touches several services: the order service records the order, the payment service charges the customer, the inventory service reserves the item. Each service owns its database, so no single database transaction can cover all three. If the payment succeeds and the reservation fails, nothing rolls the payment back automatically.
A saga splits the business transaction into a sequence of local transactions, one per service. Each step commits in its own database and then announces what it did. If a later step fails, the saga runs compensating transactions that undo the earlier steps in business terms: a refund for a charge, a release for a reservation. The term comes from a 1987 paper by Hector Garcia-Molina and Kenneth Salem on long-lived database transactions.
There are two ways to coordinate the steps:
- Choreography: there is no coordinator. Each service listens for events from the others and decides its next action itself. The order service publishes
, the payment service reacts withOrderCreated , the inventory service reacts to that, and so on.PaymentCompleted - Orchestration: one component, the orchestrator, knows the whole flow. It sends commands to each service ("charge order 7") and decides what to do with each reply.
| Approach | Consistency | Coupling | Best for |
|---|---|---|---|
| Two-phase commit (XA) | Atomic, with locks held across services | All participants must support XA and be available at once | A few resources inside one data centre, such as two databases |
| Choreographed saga | Eventual, with compensations | Services know each other's events, not each other | Short flows of 2 to 4 steps owned by different teams |
| Orchestrated saga | Eventual, with compensations | The orchestrator knows every service | Long flows, flows with branches, and flows that need one place to see their state |
This page is about choreography. The programs use Spring's JdbcTemplateTransactionTemplate
A choreographed saga, end to end
Three orders take three different paths: one succeeds, one fails at the first step, and one fails at the last step after money has been taken. Each service writes its events to its own outbox table in the same local transaction as its data. A relay then moves them onto the bus, as on the
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.function.Consumer;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionTemplate;
public class SagaFlow {
record Event(String type, int orderId, String item, int amount) {
@Override
public String toString() {
return type + "(order " + orderId + ")";
}
}
/** Stands in for Kafka: delivers each event to every subscriber, in publish order. */
static class Bus {
private final Queue<Event> queue = new ArrayDeque<>();
private final Map<String, List<Consumer<Event>>> subscribers = new HashMap<>();
private final List<Service> services = new ArrayList<>();
void subscribe(String type, Consumer<Event> handler) {
subscribers.computeIfAbsent(type, t -> new ArrayList<>()).add(handler);
}
void deliverAll() {
services.forEach(Service::relay);
while (!queue.isEmpty()) {
Event event = queue.poll();
System.out.println(" " + event);
subscribers.getOrDefault(event.type(), List.of())
.forEach(handler -> handler.accept(event));
services.forEach(Service::relay);
}
}
}
/** One microservice: its own database, local transactions and an outbox. */
static class Service {
final JdbcTemplate jdbc;
private final TransactionTemplate transaction;
private final Bus bus;
Service(String name, Bus bus) {
String url = "jdbc:h2:mem:" + name + ";DB_CLOSE_DELAY=-1";
DataSource ds = new DriverManagerDataSource(url);
this.jdbc = new JdbcTemplate(ds);
this.transaction = new TransactionTemplate(new DataSourceTransactionManager(ds));
this.bus = bus;
bus.services.add(this);
jdbc.execute("CREATE TABLE outbox (id INT AUTO_INCREMENT PRIMARY KEY,"
+ " type VARCHAR(30), order_id INT, item VARCHAR(20), amount INT)");
}
/** Runs the work and stores the events in one local transaction. */
void local(Runnable work, Event... events) {
transaction.executeWithoutResult(status -> {
work.run();
for (Event e : events) {
jdbc.update("INSERT INTO outbox (type, order_id, item, amount)"
+ " VALUES (?, ?, ?, ?)", e.type(), e.orderId(), e.item(), e.amount());
}
});
}
void relay() {
for (Map<String, Object> row : jdbc.queryForList("SELECT * FROM outbox ORDER BY id")) {
bus.queue.add(new Event((String) row.get("TYPE"), (Integer) row.get("ORDER_ID"),
(String) row.get("ITEM"), (Integer) row.get("AMOUNT")));
jdbc.update("DELETE FROM outbox WHERE id = ?", row.get("ID"));
}
}
}
public static void main(String[] args) {
Bus bus = new Bus();
Service orders = new Service("orders", bus);
Service payments = new Service("payments", bus);
Service inventory = new Service("inventory", bus);
orders.jdbc.execute("CREATE TABLE orders (id INT PRIMARY KEY, status VARCHAR(20))");
payments.jdbc.execute("CREATE TABLE wallet (customer VARCHAR(10), balance INT)");
payments.jdbc.execute("CREATE TABLE payments (order_id INT PRIMARY KEY, amount INT,"
+ " status VARCHAR(10))");
payments.jdbc.update("INSERT INTO wallet VALUES ('ada', 100)");
inventory.jdbc.execute("CREATE TABLE stock (item VARCHAR(20) PRIMARY KEY, qty INT)");
inventory.jdbc.update("INSERT INTO stock VALUES ('book', 5), ('pen', 0)");
// Payment service: charges when an order is created, refunds when stock is rejected.
bus.subscribe("OrderCreated", e -> {
int balance = payments.jdbc.queryForObject("SELECT balance FROM wallet", Integer.class);
if (balance < e.amount()) {
payments.local(() -> { }, new Event("PaymentFailed", e.orderId(), e.item(), 0));
return;
}
payments.local(() -> {
payments.jdbc.update("UPDATE wallet SET balance = balance - ?", e.amount());
payments.jdbc.update("INSERT INTO payments VALUES (?, ?, 'CHARGED')",
e.orderId(), e.amount());
}, new Event("PaymentCompleted", e.orderId(), e.item(), e.amount()));
});
bus.subscribe("StockRejected", e -> payments.local(() -> {
payments.jdbc.update("UPDATE wallet SET balance = balance + ?", e.amount());
payments.jdbc.update("UPDATE payments SET status = 'REFUNDED' WHERE order_id = ?",
e.orderId());
}, new Event("PaymentRefunded", e.orderId(), e.item(), e.amount())));
// Inventory service: reserves stock once the payment has gone through.
bus.subscribe("PaymentCompleted", e -> {
int qty = inventory.jdbc.queryForObject(
"SELECT qty FROM stock WHERE item = ?", Integer.class, e.item());
if (qty == 0) {
inventory.local(() -> { }, new Event("StockRejected", e.orderId(), e.item(),
e.amount()));
return;
}
inventory.local(() -> inventory.jdbc.update(
"UPDATE stock SET qty = qty - 1 WHERE item = ?", e.item()),
new Event("StockReserved", e.orderId(), e.item(), e.amount()));
});
// Order service: starts the saga and records how it ended.
bus.subscribe("StockReserved", e -> orders.local(() -> orders.jdbc.update(
"UPDATE orders SET status = 'APPROVED' WHERE id = ?", e.orderId())));
bus.subscribe("PaymentFailed", e -> orders.local(() -> orders.jdbc.update(
"UPDATE orders SET status = 'REJECTED' WHERE id = ?", e.orderId())));
bus.subscribe("PaymentRefunded", e -> orders.local(() -> orders.jdbc.update(
"UPDATE orders SET status = 'CANCELLED' WHERE id = ?", e.orderId())));
Object[][] newOrders = {{1, "book", 30}, {2, "lamp", 500}, {3, "pen", 20}};
for (Object[] o : newOrders) {
int id = (Integer) o[0];
System.out.println("Order " + id + ": " + o[1] + " for " + o[2]);
orders.local(() -> orders.jdbc.update("INSERT INTO orders VALUES (?, 'PENDING')", id),
new Event("OrderCreated", id, (String) o[1], (Integer) o[2]));
bus.deliverAll();
}
System.out.println("orders db : " + orders.jdbc.queryForList(
"SELECT id, status FROM orders ORDER BY id"));
System.out.println("payments db : " + payments.jdbc.queryForList(
"SELECT order_id, amount, status FROM payments ORDER BY order_id")
+ ", balance " + payments.jdbc.queryForObject(
"SELECT balance FROM wallet", Integer.class));
System.out.println("inventory db: " + inventory.jdbc.queryForList(
"SELECT item, qty FROM stock ORDER BY item"));
}
}
Order 1: book for 30
OrderCreated(order 1)
PaymentCompleted(order 1)
StockReserved(order 1)
Order 2: lamp for 500
OrderCreated(order 2)
PaymentFailed(order 2)
Order 3: pen for 20
OrderCreated(order 3)
PaymentCompleted(order 3)
StockRejected(order 3)
PaymentRefunded(order 3)
orders db : [{ID=1, STATUS=APPROVED}, {ID=2, STATUS=REJECTED}, {ID=3, STATUS=CANCELLED}]
payments db : [{ORDER_ID=1, AMOUNT=30, STATUS=CHARGED}, {ORDER_ID=3, AMOUNT=20, STATUS=REFUNDED}], balance 70
inventory db: [{ITEM=book, QTY=4}, {ITEM=pen, QTY=0}]
- Order 1 went through all three steps:
, thenOrderCreated , thenPaymentCompleted , and the order service marked itStockReserved . No service called another; each one only reacted to an event.APPROVED - Order 2, a lamp for 500, failed at the payment step because the balance was 70 after order 1. The payment service published
, and the order becamePaymentFailed . Nothing needed undoing, because nothing had been done.REJECTED - Order 3 was charged 20, then the inventory service found no pens and published
. The payment service compensated with a refund and publishedStockRejected , and the order becamePaymentRefunded .CANCELLED - The three databases agree at the end. The payments table keeps order 3 as
rather than deleting it, the balance is back to 70, and the book stock went from 5 to 4.REFUNDED
Each order started as PENDING
Designing compensating transactions
A compensation is not a rollback. The original step committed, other code may have seen its result, and in the meantime the world moved on. The compensation is a new business operation that makes the overall result acceptable:
- Semantic undo: a charge is undone by a refund, a reservation by a release. The refunded payment stays in the table with its new status, as order 3's did, so the history is visible for audits and customer support.
- Steps that cannot be undone: an email that was sent, or a parcel handed to a courier, cannot be taken back. Put these last, after the point where the saga can still fail. The step after which the saga always goes forward is called the pivot transaction.
- Retryable steps: steps after the pivot must eventually succeed, so they are retried until they do rather than compensated.
- Compensations must not fail: a refund that fails leaves the saga half undone. Make compensations idempotent and retry them, and alert a person if they still fail after many attempts.
The order of the steps also decides how often compensation is needed at all, which the next section shows.
No isolation: what other sagas see
Local transactions commit one at a time, so a saga that is still running exposes its intermediate state. Other sagas can read a charge that is about to be refunded, which a database transaction would have hidden. Here order 4 arrives while order 3, which will fail for lack of stock, is still running, and the program runs the same two orders with the steps in two different orders:
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.function.Consumer;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionTemplate;
public class SagaIsolation {
record Event(String type, int orderId, String item, int amount) {
@Override
public String toString() {
return type + "(order " + orderId + ")";
}
}
/** Stands in for Kafka: delivers each event to every subscriber, in publish order. */
static class Bus {
private final Queue<Event> queue = new ArrayDeque<>();
private final Map<String, List<Consumer<Event>>> subscribers = new HashMap<>();
private final List<Service> services = new ArrayList<>();
void subscribe(String type, Consumer<Event> handler) {
subscribers.computeIfAbsent(type, t -> new ArrayList<>()).add(handler);
}
void deliverAll() {
deliver(Integer.MAX_VALUE);
}
void deliver(int max) {
services.forEach(Service::relay);
for (int i = 0; i < max && !queue.isEmpty(); i++) {
Event event = queue.poll();
System.out.println(" " + event);
subscribers.getOrDefault(event.type(), List.of())
.forEach(handler -> handler.accept(event));
services.forEach(Service::relay);
}
}
}
/** One microservice: its own database, local transactions and an outbox. */
static class Service {
final JdbcTemplate jdbc;
private final TransactionTemplate transaction;
private final Bus bus;
Service(String name, Bus bus) {
String url = "jdbc:h2:mem:" + name + ";DB_CLOSE_DELAY=-1";
DataSource ds = new DriverManagerDataSource(url);
this.jdbc = new JdbcTemplate(ds);
this.transaction = new TransactionTemplate(new DataSourceTransactionManager(ds));
this.bus = bus;
bus.services.add(this);
jdbc.execute("CREATE TABLE outbox (id INT AUTO_INCREMENT PRIMARY KEY,"
+ " type VARCHAR(30), order_id INT, item VARCHAR(20), amount INT)");
}
/** Runs the work and stores the events in one local transaction. */
void local(Runnable work, Event... events) {
transaction.executeWithoutResult(status -> {
work.run();
for (Event e : events) {
jdbc.update("INSERT INTO outbox (type, order_id, item, amount)"
+ " VALUES (?, ?, ?, ?)", e.type(), e.orderId(), e.item(), e.amount());
}
});
}
void relay() {
for (Map<String, Object> row : jdbc.queryForList("SELECT * FROM outbox ORDER BY id")) {
bus.queue.add(new Event((String) row.get("TYPE"), (Integer) row.get("ORDER_ID"),
(String) row.get("ITEM"), (Integer) row.get("AMOUNT")));
jdbc.update("DELETE FROM outbox WHERE id = ?", row.get("ID"));
}
}
}
static void run(boolean paymentFirst) {
String suffix = paymentFirst ? "a" : "b";
Bus bus = new Bus();
Service orders = new Service("orders" + suffix, bus);
Service payments = new Service("payments" + suffix, bus);
Service inventory = new Service("inventory" + suffix, bus);
orders.jdbc.execute("CREATE TABLE orders (id INT PRIMARY KEY, status VARCHAR(20))");
payments.jdbc.execute("CREATE TABLE wallet (balance INT)");
payments.jdbc.update("INSERT INTO wallet VALUES (70)");
inventory.jdbc.execute("CREATE TABLE stock (item VARCHAR(20) PRIMARY KEY, qty INT)");
inventory.jdbc.update("INSERT INTO stock VALUES ('lamp', 3), ('pen', 0)");
// The first step listens for OrderCreated, the second for the first step's success.
String chargeOn = paymentFirst ? "OrderCreated" : "StockReserved";
String reserveOn = paymentFirst ? "PaymentCompleted" : "OrderCreated";
String finalEvent = paymentFirst ? "StockReserved" : "PaymentCompleted";
bus.subscribe(chargeOn, e -> {
int balance = payments.jdbc.queryForObject("SELECT balance FROM wallet", Integer.class);
if (balance < e.amount()) {
System.out.println(" payment: balance " + balance + " < " + e.amount());
payments.local(() -> { }, new Event("PaymentFailed", e.orderId(), e.item(),
e.amount()));
return;
}
payments.local(() -> payments.jdbc.update(
"UPDATE wallet SET balance = balance - ?", e.amount()),
new Event("PaymentCompleted", e.orderId(), e.item(), e.amount()));
});
bus.subscribe(reserveOn, e -> {
int qty = inventory.jdbc.queryForObject(
"SELECT qty FROM stock WHERE item = ?", Integer.class, e.item());
if (qty == 0) {
inventory.local(() -> { }, new Event("StockRejected", e.orderId(), e.item(),
e.amount()));
return;
}
inventory.local(() -> inventory.jdbc.update(
"UPDATE stock SET qty = qty - 1 WHERE item = ?", e.item()),
new Event("StockReserved", e.orderId(), e.item(), e.amount()));
});
// Compensations: undo whatever the earlier step did.
if (paymentFirst) {
bus.subscribe("StockRejected", e -> payments.local(() -> payments.jdbc.update(
"UPDATE wallet SET balance = balance + ?", e.amount()),
new Event("PaymentRefunded", e.orderId(), e.item(), e.amount())));
} else {
bus.subscribe("PaymentFailed", e -> inventory.local(() -> inventory.jdbc.update(
"UPDATE stock SET qty = qty + 1 WHERE item = ?", e.item()),
new Event("StockReleased", e.orderId(), e.item(), e.amount())));
}
bus.subscribe(finalEvent, e -> orders.local(() -> orders.jdbc.update(
"UPDATE orders SET status = 'APPROVED' WHERE id = ?", e.orderId())));
for (String failure : new String[] {"PaymentFailed", "StockRejected"}) {
bus.subscribe(failure, e -> orders.local(() -> orders.jdbc.update(
"UPDATE orders SET status = 'CANCELLED' WHERE id = ?", e.orderId())));
}
System.out.println(paymentFirst ? "Charge first, then reserve stock:"
: "Reserve stock first, then charge:");
orders.local(() -> orders.jdbc.update("INSERT INTO orders VALUES (3, 'PENDING')"),
new Event("OrderCreated", 3, "pen", 20));
bus.deliver(1);
System.out.println(" -- order 4 arrives while order 3 is still running --");
orders.local(() -> orders.jdbc.update("INSERT INTO orders VALUES (4, 'PENDING')"),
new Event("OrderCreated", 4, "lamp", 60));
bus.deliverAll();
System.out.println(" orders " + orders.jdbc.queryForList(
"SELECT id, status FROM orders ORDER BY id") + ", balance "
+ payments.jdbc.queryForObject("SELECT balance FROM wallet", Integer.class));
}
public static void main(String[] args) {
System.out.println("Wallet: 70. Order 3: pen for 20 (out of stock). Order 4: lamp for 60.");
run(true);
run(false);
}
}
Wallet: 70. Order 3: pen for 20 (out of stock). Order 4: lamp for 60.
Charge first, then reserve stock:
OrderCreated(order 3)
-- order 4 arrives while order 3 is still running --
PaymentCompleted(order 3)
OrderCreated(order 4)
payment: balance 50 < 60
StockRejected(order 3)
PaymentFailed(order 4)
PaymentRefunded(order 3)
orders [{ID=3, STATUS=CANCELLED}, {ID=4, STATUS=CANCELLED}], balance 70
Reserve stock first, then charge:
OrderCreated(order 3)
-- order 4 arrives while order 3 is still running --
StockRejected(order 3)
OrderCreated(order 4)
StockReserved(order 4)
PaymentCompleted(order 4)
orders [{ID=3, STATUS=CANCELLED}, {ID=4, STATUS=APPROVED}], balance 10
- Charging first, order 3 took 20 from the wallet of 70. Order 4 then saw a balance of 50, which was less than its 60, and was cancelled. Only afterwards did order 3 fail on stock and refund its 20. The balance ended at 70 again, and both orders were cancelled although order 4 could have been paid.
- Reserving stock first, order 3 failed before any money moved. Order 4 found the full balance, was charged 60 and approved, leaving 10.
The first run is a dirty read across services: order 4 acted on a value that a compensation was about to change. Sagas cannot prevent this completely, but these countermeasures reduce it:
- Order the steps: put the steps most likely to fail first, and the ones that are expensive to compensate, such as money, as late as possible.
- Semantic locks: a
status tells other code that a record is in flux. A second saga can wait, fail fast, or treat pending amounts separately, for example by showing a balance with pending charges listed.PENDING - Commutative updates: debits and credits that add and subtract give the same final balance in any order, unlike updates that set an absolute value.
- Re-reading values: a step that depends on a value read earlier in the saga re-reads it before acting, so it does not act on stale data.
Duplicate and out-of-order events
Brokers deliver at least once, and events on different topics or partitions can arrive in any order. Every saga handler meets both sooner or later. The program shows one example of each, first with handlers that ignore the problem and then with handlers that cope:
import javax.sql.DataSource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionTemplate;
public class SagaDuplicates {
static JdbcTemplate jdbc;
static TransactionTemplate transaction;
// Inventory service: handles PaymentCompleted by reserving one item.
static void reserveNaive(int orderId) {
jdbc.update("UPDATE stock SET qty = qty - 1 WHERE item = 'book'");
}
static void reserveIdempotent(int orderId) {
try {
transaction.executeWithoutResult(status -> {
jdbc.update("INSERT INTO reservations VALUES (?)", orderId);
jdbc.update("UPDATE stock SET qty = qty - 1 WHERE item = 'book'");
});
} catch (DuplicateKeyException e) {
System.out.println(" reservation for order " + orderId + " exists, skipped");
}
}
// Payment service: OrderCreated charges, OrderCancelled refunds.
static void chargeNaive(int orderId, int amount) {
jdbc.update("UPDATE wallet SET balance = balance - ?", amount);
jdbc.update("INSERT INTO charges VALUES (?, 'CHARGED')", orderId);
}
static void refundNaive(int orderId, int amount) {
int updated = jdbc.update("UPDATE charges SET status = 'REFUNDED'"
+ " WHERE order_id = ? AND status = 'CHARGED'", orderId);
if (updated == 1) {
jdbc.update("UPDATE wallet SET balance = balance + ?", amount);
} else {
System.out.println(" nothing to refund for order " + orderId);
}
}
static void chargeTolerant(int orderId, int amount) {
try {
transaction.executeWithoutResult(status -> {
jdbc.update("INSERT INTO charges VALUES (?, 'CHARGED')", orderId);
jdbc.update("UPDATE wallet SET balance = balance - ?", amount);
});
} catch (DuplicateKeyException e) {
String state = jdbc.queryForObject(
"SELECT status FROM charges WHERE order_id = ?", String.class, orderId);
System.out.println(" order " + orderId + " is already " + state + ", not charged");
}
}
static void refundTolerant(int orderId, int amount) {
transaction.executeWithoutResult(status -> {
int updated = jdbc.update("UPDATE charges SET status = 'REFUNDED'"
+ " WHERE order_id = ? AND status = 'CHARGED'", orderId);
if (updated == 1) {
jdbc.update("UPDATE wallet SET balance = balance + ?", amount);
} else {
// Cancelled before it was charged: leave a marker for the late OrderCreated.
jdbc.update("MERGE INTO charges KEY (order_id) VALUES (?, 'CANCELLED')", orderId);
System.out.println(" order " + orderId + " recorded as CANCELLED");
}
});
}
static void reset() {
jdbc.update("UPDATE stock SET qty = 5");
jdbc.update("UPDATE wallet SET balance = 100");
jdbc.update("DELETE FROM reservations");
jdbc.update("DELETE FROM charges");
}
static int value(String sql) {
return jdbc.queryForObject(sql, Integer.class);
}
public static void main(String[] args) {
DataSource ds = new DriverManagerDataSource("jdbc:h2:mem:dups;DB_CLOSE_DELAY=-1");
jdbc = new JdbcTemplate(ds);
transaction = new TransactionTemplate(new DataSourceTransactionManager(ds));
jdbc.execute("CREATE TABLE stock (item VARCHAR(10) PRIMARY KEY, qty INT)");
jdbc.execute("CREATE TABLE reservations (order_id INT PRIMARY KEY)");
jdbc.execute("CREATE TABLE wallet (balance INT)");
jdbc.execute("CREATE TABLE charges (order_id INT PRIMARY KEY, status VARCHAR(10))");
jdbc.update("INSERT INTO stock VALUES ('book', 5)");
jdbc.update("INSERT INTO wallet VALUES (100)");
System.out.println("1. PaymentCompleted(order 5) is delivered twice:");
reserveNaive(5);
reserveNaive(5);
System.out.println(" naive handler : stock " + value("SELECT qty FROM stock")
+ " (expected 4)");
reset();
reserveIdempotent(5);
reserveIdempotent(5);
System.out.println(" idempotent handler: stock " + value("SELECT qty FROM stock"));
System.out.println("2. OrderCancelled(order 6) arrives before OrderCreated(order 6):");
reset();
refundNaive(6, 40);
chargeNaive(6, 40);
System.out.println(" naive handlers : balance " + value("SELECT balance FROM wallet")
+ " for a cancelled order (expected 100)");
reset();
refundTolerant(6, 40);
chargeTolerant(6, 40);
System.out.println(" tolerant handlers : balance " + value("SELECT balance FROM wallet"));
}
}
1. PaymentCompleted(order 5) is delivered twice:
naive handler : stock 3 (expected 4)
reservation for order 5 exists, skipped
idempotent handler: stock 4
2. OrderCancelled(order 6) arrives before OrderCreated(order 6):
nothing to refund for order 6
naive handlers : balance 60 for a cancelled order (expected 100)
order 6 recorded as CANCELLED
order 6 is already CANCELLED, not charged
tolerant handlers : balance 100
- Case 1:
for order 5 arrived twice. The naive inventory handler reserved two books, and the stock fell to 3. The idempotent handler inserted the order id intoPaymentCompleted , whose primary key rejected the second copy, and the stock stayed at 4.reservations - Case 2: the customer cancelled order 6 so quickly that
reached the payment service beforeOrderCancelled . The naive refund found nothing to refund, then the lateOrderCreated charged 40 for a cancelled order.OrderCreated - The tolerant refund recorded order 6 as
even though there was nothing to refund. WhenCANCELLED arrived, the insert of the charge hit that row, so the order was not charged and the balance stayed at 100.OrderCreated
The general rule: a handler must give the same result if an event arrives twice, and it must remember a cancellation even when there is nothing to cancel yet. The
Stuck sagas and timeouts
Choreography has no coordinator watching each saga, so a saga whose next service never answers simply stops. The order stays PENDING
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.function.Consumer;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class SagaTimeout {
record Event(String type, int orderId) {
@Override
public String toString() {
return type + "(order " + orderId + ")";
}
}
/** Stands in for Kafka: a consumer that is down leaves its events waiting on the topic. */
static class Bus {
private final Queue<Event> queue = new ArrayDeque<>();
private final Map<String, List<Consumer<Event>>> subscribers = new HashMap<>();
void publish(Event event) {
queue.add(event);
}
void subscribe(String type, Consumer<Event> handler) {
subscribers.computeIfAbsent(type, t -> new ArrayList<>()).add(handler);
}
void deliverAll() {
while (!queue.isEmpty()) {
Event event = queue.poll();
System.out.println(" " + event);
subscribers.getOrDefault(event.type(), List.of()).forEach(h -> h.accept(event));
}
}
}
static Instant now = Instant.parse("2026-11-14T10:00:00Z");
public static void main(String[] args) {
JdbcTemplate db = new JdbcTemplate(
new DriverManagerDataSource("jdbc:h2:mem:timeout;DB_CLOSE_DELAY=-1"));
db.execute("CREATE TABLE orders (id INT PRIMARY KEY, status VARCHAR(20),"
+ " created_at TIMESTAMP WITH TIME ZONE)");
db.execute("CREATE TABLE wallet (balance INT)");
db.execute("CREATE TABLE stock (qty INT)");
db.update("INSERT INTO wallet VALUES (100)");
db.update("INSERT INTO stock VALUES (5)");
Bus bus = new Bus();
List<Event> inventoryBacklog = new ArrayList<>();
boolean[] inventoryDown = {true};
// Payment service
bus.subscribe("OrderCreated", e -> {
db.update("UPDATE wallet SET balance = balance - 30");
bus.publish(new Event("PaymentCompleted", e.orderId()));
});
bus.subscribe("OrderTimedOut", e -> {
db.update("UPDATE wallet SET balance = balance + 30");
System.out.println(" payment: refunded 30");
});
// Inventory service, down at first: its events wait on the topic
Consumer<Event> reserve = e -> {
db.update("UPDATE stock SET qty = qty - 1");
bus.publish(new Event("StockReserved", e.orderId()));
};
bus.subscribe("PaymentCompleted", e -> {
if (inventoryDown[0]) {
inventoryBacklog.add(e);
} else {
reserve.accept(e);
}
});
bus.subscribe("ReservationNotNeeded", e -> {
db.update("UPDATE stock SET qty = qty + 1");
System.out.println(" inventory: released the reserved item");
});
// Order service: approves only orders that are still pending
bus.subscribe("StockReserved", e -> {
int updated = db.update("UPDATE orders SET status = 'APPROVED'"
+ " WHERE id = ? AND status = 'PENDING'", e.orderId());
if (updated == 0) {
System.out.println(" order: order " + e.orderId()
+ " is no longer pending, compensating");
bus.publish(new Event("ReservationNotNeeded", e.orderId()));
}
});
System.out.println("10:00 order 7 placed, inventory service is down:");
db.update("INSERT INTO orders VALUES (7, 'PENDING', ?)", Timestamp.from(now));
bus.publish(new Event("OrderCreated", 7));
bus.deliverAll();
// In an application: @Scheduled(fixedDelay = 60000) on the order service
now = now.plus(Duration.ofMinutes(31));
System.out.println("10:31 timeout job looks for orders pending over 30 minutes:");
List<Integer> stuck = db.queryForList("SELECT id FROM orders WHERE status = 'PENDING'"
+ " AND created_at < ?", Integer.class,
Timestamp.from(now.minus(Duration.ofMinutes(30))));
for (int id : stuck) {
db.update("UPDATE orders SET status = 'TIMED_OUT' WHERE id = ?", id);
bus.publish(new Event("OrderTimedOut", id));
}
bus.deliverAll();
System.out.println("10:40 inventory service comes back and works through its backlog:");
inventoryDown[0] = false;
inventoryBacklog.forEach(reserve);
bus.deliverAll();
System.out.println("order " + db.queryForObject("SELECT status FROM orders", String.class)
+ ", balance " + db.queryForObject("SELECT balance FROM wallet", Integer.class)
+ ", stock " + db.queryForObject("SELECT qty FROM stock", Integer.class));
}
}
10:00 order 7 placed, inventory service is down:
OrderCreated(order 7)
PaymentCompleted(order 7)
10:31 timeout job looks for orders pending over 30 minutes:
OrderTimedOut(order 7)
payment: refunded 30
10:40 inventory service comes back and works through its backlog:
StockReserved(order 7)
order: order 7 is no longer pending, compensating
ReservationNotNeeded(order 7)
inventory: released the reserved item
order TIMED_OUT, balance 100, stock 5
- At 10:00 the order was created and paid, but
waited on the topic because the inventory service was down.PaymentCompleted - At 10:31 the order service's timeout job found order 7 pending for over 30 minutes. It marked the order
and publishedTIMED_OUT , and the payment service refunded 30.OrderTimedOut - At 10:40 the inventory service came back, processed its backlog and reserved the item. The order service refused to approve an order that was no longer pending and published
, so the inventory service released the item again.ReservationNotNeeded - The end state is consistent: the order timed out, the balance is back to 100 and the stock to 5.
Every saga needs an owner that notices when it is stuck, usually the service that started it, running a
Running a choreographed saga on Kafka
With a real broker, each event type, or each service's events, goes to a Kafka topic, and each service consumes the topics it cares about. A listener in the payment service with Spring for Apache Kafka looks like this. It was not run here, because it needs a Kafka broker:
@KafkaListener(topics = "order-events", groupId = "payment-service")
@Transactional
public void onOrderEvent(OrderEvent event) {
if (!processedEvents.markProcessed(event.eventId())) {
return; // duplicate delivery
}
switch (event.type()) {
case "OrderCreated" -> charge(event); // writes payment and outbox row
case "OrderCancelled" -> refund(event);
default -> { }
}
}
- Reliable publishing: each service writes its events to an outbox in the same local transaction as its data, as
does. Publishing directly from the handler after commit can lose the event and stop the saga.SagaFlow - Keys and partitions: use the order id, or whatever identifies the saga, as the message key, so one saga's events stay in order on one partition.
- Correlation: put the saga id and a causation id, the id of the event that caused this one, in every event. Tracing then shows the whole saga across services; see
distributed tracing . - Failed messages: an event that a handler cannot process after several retries goes to a dead-letter topic, with an alert, rather than blocking the partition. See
Kafka dead-letter topics .
Choosing choreography or orchestration
| Situation | Use |
|---|---|
| 2 to 4 steps, each owned by a different team | Choreography: no shared component to change for every new step |
| Many steps, branches or parallel steps | Orchestration: the flow lives in one place and can be read as code |
| Operators must see where each saga is | Orchestration, or choreography plus a status table kept by the starting service |
| A step that cannot be undone, such as sending goods | Put it after the pivot transaction, and retry it until it succeeds |
| A step that often fails | Run it first, before steps that are expensive to compensate |
| Events that can arrive twice or out of order | Idempotent handlers that remember cancellations |
| A service that may never answer | A timeout job in the service that started the saga |
| Strong consistency between two databases in one place | A local transaction if they can be merged, two-phase commit if not |
Choreography is simple to start and hard to follow once it grows: with 6 services reacting to each other's events, nobody can see the whole flow without tracing. A common path is to start with choreography for a short flow and move to an orchestrator when the flow gains branches. Whichever you choose, the same rules hold: publish through an outbox, make every handler idempotent, design compensations as business operations, and give every saga a timeout. Related pages: