Apache Camel Saga EIP: undoing work across services
A saga replaces one big transaction with steps that commit at once and compensations that undo them when a later step fails. Camel's Saga EIP declares those steps and compensations in routes. This page explains how a saga runs, then shows each important behaviour running, from what a compensation can see to sagas that time out and compensations that fail.
Contents
What a saga is, and how Camel runs one
An order that touches three services, such as credit, stock and shipping, cannot use one database transaction: each service owns its data, and a distributed lock across them would make every service wait for the slowest. A saga gives up on atomic commit. Each step commits locally at once, and each step that changed something registers a compensation, an action that undoes it. If a later step fails, the saga runs the compensations of the steps that already succeeded. The data is inconsistent for a short time, and consistent again once the saga has completed or compensated.
Camel's Saga EIP turns this into route configuration:
- saga(): starts a saga, or joins the one the exchange is already part of. It applies to the whole route it is in, wherever in the route it appears.
- compensation(uri): the endpoint to call if the saga fails. Each route that joins the saga can register its own.
- completion(uri): the endpoint to call when the saga succeeds, for example to turn a reservation into a final booking.
- option(name, expression): a value saved now and passed as a header to the compensation and completion calls later.
- propagation, completionMode and timeout: how a route relates to an existing saga, who decides that the saga is finished, and how long it may stay open.
The saga state is kept by a CamelSagaService
| Service | Module | State kept in | Best for |
|---|---|---|---|
InMemorySagaService | camel-support | This JVM's memory | Sagas whose steps all run in one application, tests |
LRASagaService | camel-lra | An external MicroProfile LRA coordinator, such as Narayana | Sagas across several services and restarts |
The in-memory service loses every open saga when the application stops, so a crash between a failure and its compensation leaves the data inconsistent with nothing left to fix it. The examples are complete programs for Camel 4.23 on Java 21 that use the in-memory service, with Camel's logging off. The LRA service needs a running coordinator, which was not available here; its configuration at the end of the page was not run.
A first saga: reserve, reserve, fail, compensate
An order reserves credit, reserves an item, then books shipping. The first order ships to France and succeeds; the second ships to Atlantis, where no courier goes, so the last step fails after the first two have changed data:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.SagaPropagation;
import org.apache.camel.saga.InMemorySagaService;
import org.slf4j.LoggerFactory;
public class OrderSaga {
// stand-ins for three services that each keep their own data
static final Map<String, Integer> credit = new ConcurrentHashMap<>(Map.of("alice", 100));
static final Map<String, String> stock = new ConcurrentHashMap<>();
static final List<String> events = new CopyOnWriteArrayList<>();
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
CamelContext context = new DefaultCamelContext();
context.addService(new InMemorySagaService());
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:placeOrder")
.saga()
.to("direct:reserveCredit")
.to("direct:reserveStock")
.to("direct:bookShipping");
from("direct:reserveCredit")
.saga().propagation(SagaPropagation.MANDATORY)
.compensation("direct:releaseCredit")
.option("customer", header("customer"))
.option("amount", header("amount"))
.process(e -> {
String customer = e.getMessage().getHeader("customer", String.class);
int amount = e.getMessage().getHeader("amount", Integer.class);
credit.merge(customer, -amount, Integer::sum);
events.add("credit reserved: " + amount);
});
from("direct:releaseCredit")
.process(e -> {
int amount = e.getMessage().getHeader("amount", Integer.class);
credit.merge(e.getMessage().getHeader("customer", String.class),
amount, Integer::sum);
events.add("COMPENSATE credit released: " + amount);
});
from("direct:reserveStock")
.saga().propagation(SagaPropagation.MANDATORY)
.compensation("direct:releaseStock")
.option("item", header("item"))
.process(e -> {
stock.put(e.getMessage().getHeader("item", String.class), "reserved");
events.add("stock reserved: " + e.getMessage().getHeader("item"));
});
from("direct:releaseStock")
.process(e -> {
stock.remove(e.getMessage().getHeader("item", String.class));
events.add("COMPENSATE stock released: "
+ e.getMessage().getHeader("item"));
});
from("direct:bookShipping")
.saga().propagation(SagaPropagation.MANDATORY)
.process(e -> {
if (e.getMessage().getHeader("country").equals("Atlantis")) {
throw new IllegalStateException("no courier to Atlantis");
}
events.add("shipping booked");
});
}
});
context.start();
ProducerTemplate template = context.createProducerTemplate();
run(template, Map.of("customer", "alice", "amount", 30, "item", "lamp",
"country", "France"));
run(template, Map.of("customer", "alice", "amount", 50, "item", "desk",
"country", "Atlantis"));
context.close();
}
static void run(ProducerTemplate template, Map<String, Object> order) throws Exception {
events.clear();
System.out.println("Order " + order.get("item") + " to " + order.get("country") + ":");
try {
template.sendBodyAndHeaders("direct:placeOrder", null, order);
System.out.println(" route result: completed");
} catch (Exception e) {
System.out.println(" route result: failed with "
+ e.getCause().getClass().getSimpleName());
}
Thread.sleep(500); // compensations run asynchronously
events.forEach(line -> System.out.println(" " + line));
System.out.println(" credit left: " + credit + ", stock: " + stock);
}
}
Order lamp to France:
route result: completed
credit reserved: 30
stock reserved: lamp
shipping booked
credit left: {alice=70}, stock: {lamp=reserved}
Order desk to Atlantis:
route result: failed with IllegalStateException
credit reserved: 50
stock reserved: desk
COMPENSATE stock released: desk
COMPENSATE credit released: 50
credit left: {alice=70}, stock: {lamp=reserved}
- The France order ran all three steps, and the saga completed: Alice's credit dropped from 100 to 70 and the lamp stayed reserved.
- The Atlantis order reserved 50 of credit and the desk, then failed on shipping. The route returned the
to the caller, and the saga called both compensations: the desk was released and the 50 returned. Afterwards the data is as it was before the order: credit 70, only the lamp reserved.IllegalStateException - The compensations ran in reverse order of the steps: stock first, then credit. The in-memory coordinator reverses its list of steps and calls one compensation after the other.
- Compensation is asynchronous: the caller got its exception before the compensations had finished, which is why the program waits half a second before printing.
The outer route starts the saga with the default propagation, REQUIREDMANDATORYbookShipping
Options: the compensation only sees what you saved
A compensation runs later, on another thread, with a new exchange. It does not see the body or the headers of the exchange that registered it. This program books two hotel rooms, one that succeeds and one that fails, and prints what the completion and compensation routes receive:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.saga.InMemorySagaService;
import org.slf4j.LoggerFactory;
public class SagaOptions {
// callbacks run on other threads, so their lines are printed at the end
static final List<String> callbacks = new CopyOnWriteArrayList<>();
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
CamelContext context = new DefaultCamelContext();
context.addService(new InMemorySagaService());
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:book")
.saga()
.compensation("direct:cancel")
.completion("direct:confirm")
.option("bookingId", header("bookingId"))
.process(e -> System.out.println("booking route: saga id header set: "
+ (e.getMessage().getHeader(Exchange.SAGA_LONG_RUNNING_ACTION)
!= null)
+ ", body '" + e.getMessage().getBody() + "'"))
.filter(header("fail"))
.throwException(new IllegalStateException("payment refused"));
from("direct:cancel").routeId("cancel")
.process(e -> print("cancel", e));
from("direct:confirm").routeId("confirm")
.process(e -> print("confirm", e));
}
});
NotifyBuilder bothCalled = new NotifyBuilder(context).fromRoute("c*").whenDone(2)
.create();
context.start();
ProducerTemplate template = context.createProducerTemplate();
template.sendBodyAndHeaders("direct:book", "room 12",
Map.of("bookingId", "B-1", "guest", "alice", "fail", false));
try {
template.sendBodyAndHeaders("direct:book", "room 14",
Map.of("bookingId", "B-2", "guest", "bob", "fail", true));
} catch (Exception e) {
System.out.println("booking B-2 failed: " + e.getCause().getMessage());
}
bothCalled.matches(5, TimeUnit.SECONDS);
context.close();
callbacks.stream().sorted().forEach(System.out::println);
}
static void print(String callback, Exchange e) {
var in = e.getMessage();
callbacks.add(callback + " route: bookingId=" + in.getHeader("bookingId")
+ ", guest=" + in.getHeader("guest") + ", body=" + in.getBody()
+ ", saga id present=" + (in.getHeader(Exchange.SAGA_LONG_RUNNING_ACTION) != null));
}
}
booking route: saga id header set: true, body 'room 12'
booking route: saga id header set: true, body 'room 14'
booking B-2 failed: payment refused
cancel route: bookingId=B-2, guest=null, body=null, saga id present=true
confirm route: bookingId=B-1, guest=null, body=null, saga id present=true
- Both callbacks received
, because the route saved it withbookingId .option("bookingId", header("bookingId")) - They did not receive
, which was a header on the original exchange but not an option, and the body wasguest , notnull orroom 12 .room 14 - The completion route ran for the successful booking B-1 and the compensation route for the failed booking B-2, each with the saga id in the
header.Long-Running-Action
Save in options everything a compensation needs to find and undo the change: an id, an amount, a key. Option values are evaluated when the step joins the saga, so they hold the values of that moment. A compensation that needs more than a few values should look the rest up by id.
Propagation: joining, starting or refusing a saga
Propagation decides what a route with saga()
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.Map;
import java.util.TreeMap;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.SagaPropagation;
import org.apache.camel.saga.InMemorySagaService;
import org.slf4j.LoggerFactory;
public class Propagation {
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
CamelContext context = new DefaultCamelContext();
context.addService(new InMemorySagaService());
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:outer").saga()
.process(e -> remember(e, "outer"))
.to("direct:step");
from("direct:noSaga")
.process(e -> remember(e, "outer"))
.to("direct:step");
for (SagaPropagation p : SagaPropagation.values()) {
from("direct:" + p.name()).saga().propagation(p)
.process(e -> remember(e, "step"));
}
from("direct:step").toD("direct:${header.mode}");
}
});
context.start();
ProducerTemplate template = context.createProducerTemplate();
System.out.printf("%-14s %-34s %s%n", "propagation", "called inside a saga",
"called without a saga");
for (SagaPropagation p : SagaPropagation.values()) {
System.out.printf("%-14s %-34s %s%n", p,
run(template, "direct:outer", p), run(template, "direct:noSaga", p));
}
context.close();
}
static String run(ProducerTemplate template, String from, SagaPropagation p) {
Map<String, Object> ids = new TreeMap<>();
try {
template.send(from, e -> {
e.getMessage().setHeader("mode", p.name());
e.setProperty("ids", ids);
});
} catch (Exception e) {
return "fails";
}
Object outer = ids.get("outer");
Object step = ids.get("step");
if (step == null) {
return "fails";
} else if (step.equals("none")) {
return "runs with no saga";
} else if (step.equals(outer)) {
return "joins the caller's saga";
}
return "runs in a new saga";
}
@SuppressWarnings("unchecked")
static void remember(Exchange e, String where) {
String id = e.getExchangeExtension().getSagaLongRunningAction();
e.getProperty("ids", Map.class).put(where, id == null ? "none" : id);
}
}
propagation called inside a saga called without a saga
REQUIRED joins the caller's saga runs in a new saga
REQUIRES_NEW runs in a new saga runs in a new saga
MANDATORY joins the caller's saga fails
SUPPORTS joins the caller's saga runs with no saga
NOT_SUPPORTED runs with no saga runs with no saga
NEVER fails runs with no saga
, the default, joined the caller's saga or started one. Most step routes want this orREQUIRED .MANDATORY always started its own saga, so its compensation is not called when the caller's saga fails, and the other way round.REQUIRES_NEW failed without a saga, which catches a step being called on its own by mistake.MANDATORY joined a saga if there was one and otherwise ran without, andSUPPORTS always ran outside any saga.NOT_SUPPORTED failed when called inside a saga.NEVER
The program reads the current saga id with getExchangeExtension().getSagaLongRunningAction()
Manual completion and timeouts
With the default completionModeAUTOMANUALsaga:completesaga:compensate
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.SagaCompletionMode;
import org.apache.camel.model.SagaPropagation;
import org.apache.camel.saga.InMemorySagaService;
import org.slf4j.LoggerFactory;
public class ManualTimeout {
static final List<String> events = new CopyOnWriteArrayList<>();
static final Map<String, String> sagaIds = new ConcurrentHashMap<>();
static long start;
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
CamelContext context = new DefaultCamelContext();
context.addService(new InMemorySagaService());
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
// the route ends while the saga stays open, waiting for the payment
from("direct:reserveSeat")
.saga()
.completionMode(SagaCompletionMode.MANUAL)
.timeout(1500, TimeUnit.MILLISECONDS)
.compensation("direct:releaseSeat")
.completion("direct:issueTicket")
.option("seat", header("seat"))
.process(e -> {
String seat = e.getMessage().getHeader("seat", String.class);
sagaIds.put(seat, e.getMessage().getHeader(
Exchange.SAGA_LONG_RUNNING_ACTION, String.class));
note("seat " + seat + " held, route finished, saga still open");
});
// a later message, here a payment confirmation, rejoins the saga and
// completes it. The in-memory service ignores the Long-Running-Action
// header, so the id is bound to the exchange before the saga route.
from("direct:paymentReceived")
.process(e -> e.getExchangeExtension().setSagaLongRunningAction(
e.getMessage().getHeader("sagaId", String.class)))
.to("direct:completeSaga");
from("direct:completeSaga")
.saga().propagation(SagaPropagation.MANDATORY)
.to("saga:complete");
from("direct:releaseSeat")
.process(e -> note("COMPENSATE seat "
+ e.getMessage().getHeader("seat") + " released"));
from("direct:issueTicket")
.process(e -> note("COMPLETE ticket issued for seat "
+ e.getMessage().getHeader("seat")));
}
});
context.start();
ProducerTemplate template = context.createProducerTemplate();
template.sendBodyAndHeader("direct:reserveSeat", null, "seat", "12A");
template.sendBodyAndHeader("direct:reserveSeat", null, "seat", "14C");
Thread.sleep(500);
note("payment for 12A arrives");
template.sendBodyAndHeader("direct:paymentReceived", null,
"sagaId", sagaIds.get("12A"));
Thread.sleep(2000); // no payment for 14C: its timeout expires
context.close();
events.forEach(System.out::println);
}
// records an event with the time since the first event, to the nearest 0.5 s
static synchronized void note(String event) {
if (start == 0) {
start = System.nanoTime();
}
long half = Math.round((System.nanoTime() - start) / 5e8);
events.add(String.format("%.1f s %s", half / 2.0, event));
}
}
0.0 s seat 12A held, route finished, saga still open
0.0 s seat 14C held, route finished, saga still open
0.5 s payment for 12A arrives
0.5 s COMPLETE ticket issued for seat 12A
1.5 s COMPENSATE seat 14C released
- Both reservation routes finished at once, leaving their sagas open.
- The payment for 12A arrived half a second later.
completed that saga, and the completion route issued the ticket.saga:complete - No payment came for 14C, so the timeout compensated its saga 1.5 seconds after it started and the seat was released.
The payment route has to tell Camel which saga it belongs to. With the LRA service, that is the Long-Running-ActionisLongRunningActionHeaderSupported()falsesaga()setSagaLongRunningActionsaga:camel-saga
Compensations that fail
A compensation is itself a call to a service, and it can fail. The in-memory service retries it. Here one compensation fails twice before it succeeds, and another fails every time:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.saga.InMemorySagaService;
import org.slf4j.LoggerFactory;
public class CompensationRetry {
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
AtomicInteger refundCalls = new AtomicInteger();
AtomicInteger voucherCalls = new AtomicInteger();
InMemorySagaService sagas = new InMemorySagaService();
System.out.println("defaults: maxRetryAttempts=" + sagas.getMaxRetryAttempts()
+ ", retryDelayInMilliseconds=" + sagas.getRetryDelayInMilliseconds());
sagas.setRetryDelayInMilliseconds(100);
CamelContext context = new DefaultCamelContext();
context.addService(sagas);
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:refundable").saga().compensation("direct:refund")
.throwException(new IllegalStateException("order failed"));
from("direct:refund").process(e -> {
int call = refundCalls.incrementAndGet();
System.out.println(" refund attempt " + call
+ (call < 3 ? ": payment service down" : ": refunded"));
if (call < 3) {
throw new IllegalStateException("payment service down");
}
});
from("direct:voucher").saga().compensation("direct:revokeVoucher")
.throwException(new IllegalStateException("order failed"));
from("direct:revokeVoucher").process(e -> {
voucherCalls.incrementAndGet();
throw new IllegalStateException("voucher already spent");
});
}
});
context.start();
ProducerTemplate template = context.createProducerTemplate();
System.out.println("Compensation that fails twice:");
send(template, "direct:refundable");
Thread.sleep(1500);
System.out.println("Compensation that always fails:");
send(template, "direct:voucher");
Thread.sleep(1500);
System.out.println(" revokeVoucher was called " + voucherCalls.get()
+ " times, then the saga service gave up");
context.close();
}
static void send(ProducerTemplate template, String uri) {
try {
template.sendBody(uri, null);
} catch (Exception e) {
// the route fails on purpose; the saga compensates
}
}
}
defaults: maxRetryAttempts=5, retryDelayInMilliseconds=5000
Compensation that fails twice:
refund attempt 1: payment service down
refund attempt 2: payment service down
refund attempt 3: refunded
Compensation that always fails:
revokeVoucher was called 5 times, then the saga service gave up
- By default the service tries a compensation up to 5 times, 5000 ms apart. The program shortened the delay to 100 ms.
- The refund failed twice and succeeded on the third attempt, so the saga ended consistent.
- The voucher compensation was called 5 times in all and then abandoned. The saga is finished, but the voucher it should have revoked is still valid: only a log line records the problem.
Write compensations so that they can be repeated safely, because a retry may follow an attempt that actually worked but timed out. And plan for the compensation that never succeeds: a monitored dead letter queue, an alert, or a table of failed compensations for a person to review. Retries and alerts for routes in general are covered on the
Sagas across services with LRA
When the steps run in different applications, the saga state must live outside all of them. camel-lraLRASagaService
LRASagaService sagaService = new LRASagaService();
sagaService.setCoordinatorUrl("http://lra-coordinator:8080");
sagaService.setCoordinatorContextPath("/lra-coordinator");
// where the coordinator calls this application back
sagaService.setLocalParticipantUrl("http://order-service:8080");
sagaService.setLocalParticipantContextPath("/lra-participant");
context.addService(sagaService);
- The application must be reachable over HTTP at the participant URL, so that the coordinator can call its compensations and completions.
- The saga id travels between services in the
HTTP header, and a route that receives it joins the same saga. This is the header that the in-memory service ignores.Long-Running-Action - The coordinator stores sagas durably, so compensations still happen after an application restarts.
The routes themselves do not change: saga()compensation()option()
Choosing saga settings
| Situation | Settings |
|---|---|
| All steps in one application, short-lived | InMemorySagaService |
| Steps in several services, or sagas that must survive restarts | LRASagaService |
| A step that changes data | compensation(uri)option() |
| Work to do only after the whole saga succeeded | completion(uri) |
| A step that must never run alone | propagation(MANDATORY) |
| A process that waits for an outside event | completionMode(MANUAL)saga:completetimeout |
| Compensations that call unreliable services | Repeatable compensations, retry settings and an alert for abandoned ones |
The traps to remember are compensations that see only their options, the in-memory service losing open sagas on restart and ignoring the Long-Running-Action