The Camel aggregator: many messages in, one message out
How Camel collects related messages that arrive separately and sends them on as one, explained with one running example: the items of an online order.
Contents
Introduction
Sometimes the pieces of one thing arrive as separate messages. Picture an online shop where every item of an order is sent as its own message. The book, the lamp and the desk of order A arrive one by one, mixed in with the items of order B. The rest of the system wants one message per order, not one per item. Camel's aggregator does exactly that: it collects related messages, and once a group is complete it sends them on as one message.
Look at the picture. The items of two orders come in mixed together. The aggregator keeps a separate group for each order and adds every item to its group. When a group holds all of its items, the aggregator sends it on as a single message. The rest of this page builds that up one step at a time, using the same orders in every example.
The examples were run with Camel 4.23.0 and Java 25. They need camel-corecamel-sql
Grouping items by order
Consider the following example scenario, where an aggregator groups the items by their order id and sends an order on once it has three items:
from("direct:items")
.aggregate(header("orderId"), AggregationStrategies.groupedBody())
.completionSize(3)
.to("mock:orders");
Three things in this route tell the aggregator what to do:
says which group an item belongs to. Each item carries anheader("orderId") header, and items with the same value go into the same group. This value is called the correlation key.orderId says how an item is added to its group. This one collects the item bodies into a list. The piece of code that does this is called an aggregation strategy.AggregationStrategies.groupedBody() says when a group is done: here, when it holds three items.completionSize(3)
There is a fourth question, where the groups wait while they are incomplete. You don't see it in the route because it has a default answer: in memory. We come back to it in
The full program below sends seven items: four for order A (book, lamp, desk, mug) and three for order B (pen, ink, pad), mixed together. Completed orders go to a mock endpoint, a Camel test endpoint that simply records what it receives, so the program can wait for the orders and print them:
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AggregationStrategies;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;
public class AggregateOrders {
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:items")
.aggregate(header("orderId"), AggregationStrategies.groupedBody())
.completionSize(3)
.to("mock:orders");
}
});
camel.start();
MockEndpoint orders = camel.getEndpoint("mock:orders", MockEndpoint.class);
orders.expectedMessageCount(2);
// Items of two orders, arriving mixed together.
String[][] items = {
{"A", "book"}, {"B", "pen"}, {"A", "lamp"}, {"B", "ink"},
{"A", "desk"}, {"B", "pad"}, {"A", "mug"},
};
ProducerTemplate template = camel.createProducerTemplate();
for (String[] item : items) {
template.sendBodyAndHeader("direct:items", item[1], "orderId", item[0]);
}
orders.assertIsSatisfied(2000); // wait until both orders have come out
for (Exchange order : orders.getExchanges()) {
System.out.println("order " + order.getMessage().getHeader("orderId")
+ ": " + order.getMessage().getBody());
}
camel.stop();
}
}
Running it prints:
order A: [book, lamp, desk]
order B: [pen, ink, pad]
Look at the output. Order A came out as [book, lamp, desk][pen, ink, pad]orderId
Now look at what is missing: order A had four items, and the mug is nowhere. A's group filled up with its first three items and was sent on. The mug then started a new group for order A, and that group is still waiting for two more items that will never come. With only a size rule, a group that never fills up waits forever. The next section fixes that.
Notice also that the program waits on the mock endpoint, not on the sends. Each send returns as soon as the item has been added to its group. The finished order is sent on later, from the aggregator's own thread, so the code that sends an item never gets the finished order back.
When an order never fills up
The usual fix is a second rule. Consider the same aggregator, now with a timeout of 500 ms: if no new item joins an order for 500 ms, the order is sent on with what it has:
.aggregate(header("orderId"), AggregationStrategies.groupedBody())
.completionSize(3)
.completionTimeout(500) // send the group on after 500 ms with no new item
Now a group completes when either rule is met, whichever comes first. Camel also records why each group completed, in a property named CamelAggregatedCompletedByExchange.AGGREGATED_COMPLETED_BY
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AggregationStrategies;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;
public class OrderTimeout {
static volatile long lastSent;
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:items")
.aggregate(header("orderId"), AggregationStrategies.groupedBody())
.completionSize(3)
.completionTimeout(500) // release a group after 500 ms with no new item
.process(e -> e.setProperty("msAfterLastItem",
(System.nanoTime() - lastSent) / 1000000))
.to("mock:orders");
}
});
camel.start();
MockEndpoint orders = camel.getEndpoint("mock:orders", MockEndpoint.class);
orders.expectedMessageCount(3);
String[][] items = {
{"A", "book"}, {"B", "pen"}, {"A", "lamp"}, {"B", "ink"},
{"A", "desk"}, {"B", "pad"}, {"A", "mug"},
};
ProducerTemplate template = camel.createProducerTemplate();
for (String[] item : items) {
lastSent = System.nanoTime();
template.sendBodyAndHeader("direct:items", item[1], "orderId", item[0]);
}
orders.assertIsSatisfied(3000);
for (Exchange order : orders.getExchanges()) {
String completedBy = order.getProperty(Exchange.AGGREGATED_COMPLETED_BY, String.class);
long ms = order.getProperty("msAfterLastItem", Long.class);
String when = completedBy.equals("timeout")
? (ms >= 500 ? ", 500 ms or more after the mug arrived" : ", too early?")
: "";
System.out.println("order " + order.getMessage().getHeader("orderId") + ": "
+ order.getMessage().getBody() + " (completed by " + completedBy + when + ")");
}
camel.stop();
}
}
Running it prints:
order A: [book, lamp, desk] (completed by size)
order B: [pen, ink, pad] (completed by size)
order A: [mug] (completed by timeout, 500 ms or more after the mug arrived)
Look at the last line. The mug now comes out on its own, as [mug]timeoutsize
Two details about timeouts are worth knowing:
- The timeout measures silence, not age. Every new item restarts the clock for its group, so if items keep trickling in, a group can stay open much longer than 500 ms. When there must be a hard limit on how long data waits, use
instead, which completes all groups on a fixed schedule.completionInterval(ms) - The timeout is not exact. A background task looks for expired groups once a second by default (
). In our runs the mug came out about 950 ms after it arrived, not at 500 ms.completionTimeoutCheckerInterval
When the last item says so
Sometimes the number of items is not known in advance, but the sender marks the last one. Consider the following example scenario, where order C has three items, pen, ink and pad, and pad carries a header last=true
.aggregate(header("orderId"), AggregationStrategies.string(","))
.completionPredicate(header("last").isEqualTo(true)) // done when an item has last=true
.eagerCheckCompletion() // check each item as it arrives
That last line matters more than it looks. The program below sends order C through two routes, one with eagerCheckCompletion()
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AggregationStrategies;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;
public class OrderEndMarker {
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:eager")
.aggregate(header("orderId"), AggregationStrategies.string(","))
.completionPredicate(header("last").isEqualTo(true))
.eagerCheckCompletion() // test each new item before it is merged
.to("mock:eager");
from("direct:notEager")
.aggregate(header("orderId"), AggregationStrategies.string(","))
.completionPredicate(header("last").isEqualTo(true))
.to("mock:notEager");
}
});
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
for (String route : new String[] {"eager", "notEager"}) {
for (String item : new String[] {"pen", "ink", "pad"}) {
template.send("direct:" + route, e -> {
e.getMessage().setBody(item);
e.getMessage().setHeader("orderId", "C");
e.getMessage().setHeader("last", item.equals("pad")); // pad is the last item
});
}
}
Thread.sleep(1000); // give both routes time to release order C
for (String route : new String[] {"eager", "notEager"}) {
MockEndpoint mock = camel.getEndpoint("mock:" + route, MockEndpoint.class);
System.out.println(route + ": " + (mock.getReceivedCounter() == 0
? "order C never completed"
: "order C completed as " + mock.getExchanges().get(0).getMessage().getBody()));
}
camel.stop();
}
}
Running it prints:
eager: order C completed as pen,ink,pad
notEager: order C never completed
Look at the second line: without eagerCheckCompletion()last=truestring(",")last=falseeagerCheckCompletion()last=true
So when the marker is on the incoming item, as it usually is, add eagerCheckCompletion()
An item with no order id
Consider an item that arrives without an orderIdignoreInvalidCorrelationKeys()
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AggregationStrategies;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class MissingOrderId {
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new RouteBuilder() {
@Override
public void configure() {
errorHandler(defaultErrorHandler().logExhausted(false));
from("direct:strict")
.aggregate(header("orderId"), AggregationStrategies.groupedBody())
.completionSize(3)
.to("mock:orders");
from("direct:lenient")
.aggregate(header("orderId"), AggregationStrategies.groupedBody())
.completionSize(3)
.ignoreInvalidCorrelationKeys() // drop items with no order id
.to("mock:orders");
}
});
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
for (String route : new String[] {"strict", "lenient"}) {
// an item sent without the orderId header
Exchange sent = template.send("direct:" + route, e -> e.getMessage().setBody("lamp"));
System.out.println(route + ": " + (sent.isFailed()
? "failed with \"" + sent.getException().getMessage() + "\""
: "no error, the item was dropped"));
}
camel.stop();
}
}
Running it prints:
strict: failed with "Invalid correlation key. Exchange[]"
lenient: no error, the item was dropped
With the default, the send fails with Invalid correlation keyignoreInvalidCorrelationKeys()
Building one invoice from the items
So far each order came out as a list of item names. Usually you want something more useful, such as one invoice per order. That is the job of the aggregation strategy: it decides what the group looks like.
In Camel, a message travelling through a route is wrapped in an exchange. A strategy is called once for each item, with two exchanges: newExchangeoldExchangeoldExchangenulloldExchange
Look at InvoiceStrategyInvoice
import java.math.BigDecimal;
import org.apache.camel.AggregationStrategy;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AggregationStrategies;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;
public class OrderInvoice {
record Invoice(String orderId, int items, BigDecimal total) {
}
// Called once per item. oldExchange is null for the first item of an order.
static class InvoiceStrategy implements AggregationStrategy {
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
BigDecimal price = newExchange.getMessage().getBody(BigDecimal.class);
String orderId = newExchange.getMessage().getHeader("orderId", String.class);
if (oldExchange == null) {
newExchange.getMessage().setBody(new Invoice(orderId, 1, price));
return newExchange;
}
Invoice soFar = oldExchange.getMessage().getBody(Invoice.class);
oldExchange.getMessage().setBody(
new Invoice(orderId, soFar.items() + 1, soFar.total().add(price)));
return oldExchange;
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:invoice")
.aggregate(header("orderId"), new InvoiceStrategy()).completionSize(3)
.to("mock:invoice");
from("direct:string")
.aggregate(header("orderId"), AggregationStrategies.string(" + "))
.completionSize(3)
.to("mock:string");
from("direct:latest")
.aggregate(header("orderId"), AggregationStrategies.useLatest())
.completionSize(3)
.to("mock:latest");
from("direct:grouped")
.aggregate(header("orderId"), AggregationStrategies.groupedExchange())
.completionSize(3)
.to("mock:grouped");
}
});
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
System.out.println("prices of order A: book 12.50, lamp 34.99, desk 52.51");
for (String route : new String[] {"invoice", "string", "latest", "grouped"}) {
MockEndpoint mock = camel.getEndpoint("mock:" + route, MockEndpoint.class);
mock.expectedMessageCount(1);
for (String price : new String[] {"12.50", "34.99", "52.51"}) {
template.sendBodyAndHeader("direct:" + route, price, "orderId", "A");
}
mock.assertIsSatisfied(2000);
System.out.printf(" %-8s -> %s%n", route,
mock.getExchanges().get(0).getMessage().getBody());
}
camel.stop();
}
}
Running it prints:
prices of order A: book 12.50, lamp 34.99, desk 52.51
invoice -> Invoice[orderId=A, items=3, total=100.00]
string -> 12.50 + 34.99 + 52.51
latest -> 52.51
grouped -> List<Exchange>(3 elements)
Look at the first result: one InvoiceBigDecimaldouble
joined the prices as text, with a separator.string(" + ") kept only the last item, 52.51. It suits cases where only the newest value matters, such as the latest stock level of a product.useLatest() kept the three exchanges themselves, so the body is a list of exchanges. Use it when the next step needs each item's headers as well as its body.groupedExchange()
A strategy must never return nullInvoiceStrategy
Stopping with an order half done
Remember the fourth question: incomplete groups wait in memory by default. So what happens when the application stops while an order is half done? Consider the following example scenario, where order A has received two of its three items when the application stops. The program below runs it twice, once with the default settings and once with forceCompletionOnStop()
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AggregationStrategies;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class StopTrap {
static class Routes extends RouteBuilder {
private final boolean completeOnStop;
Routes(boolean completeOnStop) {
this.completeOnStop = completeOnStop;
}
@Override
public void configure() {
var aggregate = from("direct:items")
.aggregate(header("orderId"), AggregationStrategies.string(","))
.completionSize(3).completionTimeout(60000);
if (completeOnStop) {
aggregate.forceCompletionOnStop();
}
aggregate.process(e -> System.out.println(" released " + e.getMessage().getBody()
+ " (by " + e.getProperty("CamelAggregatedCompletedBy") + ")"));
}
}
public static void main(String[] args) throws Exception {
for (boolean completeOnStop : new boolean[] {false, true}) {
System.out.println("forceCompletionOnStop = " + completeOnStop);
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes(completeOnStop));
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
template.sendBodyAndHeader("direct:items", "book", "orderId", "A");
template.sendBodyAndHeader("direct:items", "lamp", "orderId", "A");
System.out.println(" stopping with order A incomplete");
camel.stop();
System.out.println(" stopped");
}
}
}
Running it prints:
forceCompletionOnStop = false
stopping with order A incomplete
stopped
forceCompletionOnStop = true
stopping with order A incomplete
released book,lamp (by force)
stopped
Look at the first run: Camel stopped, and book,lampforceCompletionOnStop()force
completeAllOnStop()kill -9
Keeping groups in a database
The place where groups wait is called the aggregation repository. The camel-sql module has a JdbcAggregationRepository
.aggregate(header("orderId"), strategy)
.aggregationRepository(repository) // keep groups in the database, not in memory
.completionSize(3)
Consider the following example scenario: an application receives two items of order A and stops, and the restarted application receives the third. The program below plays both parts with an H2 database, and runs the whole thing twice, with two different strategies:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.camel.AggregationStrategy;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AggregationStrategies;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.processor.aggregate.jdbc.JdbcAggregationRepository;
import org.h2.jdbcx.JdbcDataSource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
public class JdbcRepository {
static final String TABLE = """
CREATE TABLE IF NOT EXISTS %s (
id VARCHAR(255) NOT NULL PRIMARY KEY,
exchange BLOB NOT NULL,
version BIGINT NOT NULL)
""";
static final AggregationStrategy JOIN_BODIES = (oldExchange, newExchange) -> {
if (oldExchange == null) {
return newExchange;
}
oldExchange.getMessage().setBody(oldExchange.getMessage().getBody(String.class)
+ "," + newExchange.getMessage().getBody(String.class));
return oldExchange;
};
static CamelContext startApp(JdbcDataSource dataSource, AggregationStrategy strategy)
throws Exception {
JdbcAggregationRepository repository = new JdbcAggregationRepository(
new DataSourceTransactionManager(dataSource), "orders_agg", dataSource);
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:items")
.aggregate(header("orderId"), strategy)
.aggregationRepository(repository).completionSize(3)
.to("mock:released");
}
});
camel.start();
return camel;
}
static int rows(JdbcDataSource dataSource, String table) throws Exception {
try (Connection c = dataSource.getConnection(); Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT COUNT(*) FROM " + table)) {
rs.next();
return rs.getInt(1);
}
}
static void run(JdbcDataSource dataSource, String name, AggregationStrategy strategy)
throws Exception {
System.out.println(name + ":");
CamelContext first = startApp(dataSource, strategy);
ProducerTemplate template = first.createProducerTemplate();
template.sendBodyAndHeader("direct:items", "book", "orderId", "A");
template.sendBodyAndHeader("direct:items", "lamp", "orderId", "A");
first.stop();
System.out.println(" first run stopped after 2 items, rows in orders_agg: "
+ rows(dataSource, "orders_agg"));
CamelContext second = startApp(dataSource, strategy);
MockEndpoint released = second.getEndpoint("mock:released", MockEndpoint.class);
released.expectedMessageCount(1);
second.createProducerTemplate().sendBodyAndHeader("direct:items", "desk",
"orderId", "A");
released.assertIsSatisfied(2000);
System.out.println(" second run got the 3rd item and released: "
+ released.getExchanges().get(0).getMessage().getBody());
while (second.getInflightRepository().size() > 0) {
Thread.sleep(10);
}
System.out.println(" rows in orders_agg now: " + rows(dataSource, "orders_agg"));
second.stop();
}
public static void main(String[] args) throws Exception {
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL("jdbc:h2:mem:camel;DB_CLOSE_DELAY=-1");
try (Connection c = dataSource.getConnection(); Statement s = c.createStatement()) {
s.execute(TABLE.formatted("orders_agg"));
s.execute(TABLE.formatted("orders_agg_completed"));
}
run(dataSource, "strategy that keeps the result in the body", JOIN_BODIES);
run(dataSource, "AggregationStrategies.string(\",\")", AggregationStrategies.string(","));
}
}
Running it prints:
strategy that keeps the result in the body:
first run stopped after 2 items, rows in orders_agg: 1
second run got the 3rd item and released: book,lamp,desk
rows in orders_agg now: 0
AggregationStrategies.string(","):
first run stopped after 2 items, rows in orders_agg: 1
second run got the 3rd item and released: ,desk
rows in orders_agg now: 0
Look at the first run. After the first application stopped, the table orders_aggbook,lamp,desk
Now look at the second run. With AggregationStrategies.string(","),desk
The repository needs two tables with the columns idexchangeversion_completed_completedversionoptimisticLocking()
A version note: Camel 4.23 deprecated MemoryAggregationRepositoryKeyValueAggregationRepositoryMemoryKeyValueRepository
A few more options
completes all groups on a fixed schedule, for example to write one batch per second.completionInterval(ms) completes a group when a batch from a consumer such as the file component is done, for example all the files of one poll.completionFromBatchConsumer() remembers the last n completed orders and rejects late items for them withcloseCorrelationKeyOnCompletion(n) , instead of starting a new group like the mug did inClosedCorrelationKeyExceptionGrouping items by order . throws away groups that time out instead of sending them on, for cases where a partial order is worthless.discardOnCompletionTimeout() completes the current group as soon as an item with a different key arrives, for input that is already sorted by order.completionOnNewCorrelationGroup() lets code outside the route complete groups, for example from an admin endpoint.aggregateController(...)
Recap
| Situation | Settings |
|---|---|
| Groups of known size | completionSize(n)completionTimeout |
| The last message marks the end | completionPredicateeagerCheckCompletion() |
| Batch writes on a schedule | completionIntervalcompletionSize |
| Only the latest value matters | AggregationStrategies.useLatest() |
| The next step needs every message's headers | AggregationStrategies.groupedExchange() |
| Groups must survive a clean shutdown | forceCompletionOnStop()completeAllOnStop() |
| Groups must survive a crash, or be shared by several instances | A database repository such as JdbcAggregationRepository |
When the related messages all come from one message, the