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.

Items of orders A and B arrive mixed together; the aggregator keeps one group per order and sends each complete group 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-core; the database example also needs camel-sql, Spring JDBC and H2.

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:

Java
from("direct:items")
    .aggregate(header("orderId"), AggregationStrategies.groupedBody())
        .completionSize(3)
    .to("mock:orders");

Three things in this route tell the aggregator what to do:

  • header("orderId") says which group an item belongs to. Each item carries an orderId header, and items with the same value go into the same group. This value is called the correlation key.
  • AggregationStrategies.groupedBody() 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.
  • completionSize(3) says when a group is done: here, when it holds three items.

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 Stopping with an order half done.

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:

Java
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:

Output
order A: [book, lamp, desk]
order B: [pen, ink, pad]

Look at the output. Order A came out as [book, lamp, desk] and order B as [pen, ink, pad]. The items arrived mixed, but the orderId header kept them apart, and each list keeps the items in the order they arrived.

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:

Java
.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 CamelAggregatedCompletedBy (Exchange.AGGREGATED_COMPLETED_BY in code). The program prints it next to each order:

Java
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:

Output
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], and the reason is timeout instead of size. A route can check that reason to treat partial orders differently, for example to send them for review.

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 completionInterval(ms) instead, which completes all groups on a fixed schedule.
  • The timeout is not exact. A background task looks for expired groups once a second by default (completionTimeoutCheckerInterval). In our runs the mug came out about 950 ms after it arrived, not at 500 ms.

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. Instead of a size, the aggregator uses a condition, called a predicate, that is checked for each item:

Java
.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() and one without it:

Java
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:

Output
eager: order C completed as pen,ink,pad
notEager: order C never completed

Look at the second line: without eagerCheckCompletion(), order C never completed, even though pad arrived with last=true. The reason is what the predicate looks at. By default it is checked on the group after the new item has been added. string(",") keeps the first item's message as the group, so the header the predicate sees is pen's, and pen has last=false. With eagerCheckCompletion() the predicate is checked on each incoming item before it is added, so it sees pad's 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 orderId header. The aggregator has no way to tell which group it belongs to. The program below sends one such item to two aggregators: the one from the start of the page, and a copy of it with ignoreInvalidCorrelationKeys():

Java
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:

Output
strict: failed with "Invalid correlation key. Exchange[]"
lenient: no error, the item was dropped

With the default, the send fails with Invalid correlation key, so the problem is visible. With ignoreInvalidCorrelationKeys(), the item is dropped silently. Only use it when such items really are worthless; otherwise keep the error, so that missing data gets noticed.

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: newExchange is the item that just arrived, and oldExchange is the group so far. For an order's first item there is no group yet, so oldExchange is null. The method returns the exchange that holds the result so far, and the aggregator passes it back in as oldExchange for the next item.

Look at InvoiceStrategy in the program below. For the first item it turns the price into an Invoice with one item; for each later item it adds the price to the invoice so far. The program sends the three prices of order A through this strategy, and through three built-in strategies for comparison:

Java
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:

Output
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 Invoice with 3 items and a total of 100.00. The prices are added as BigDecimal, which keeps money amounts exact; double would not. The other three lines show what the built-in strategies make of the same prices:

  • string(" + ") joined the prices as text, with a separator.
  • useLatest() 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.
  • groupedExchange() 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.

A strategy must never return null to the aggregator. Return the exchange that holds the result, as InvoiceStrategy does in both branches.

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():

Java
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:

Output
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,lamp simply disappeared, with no error and no log line. In the second run, forceCompletionOnStop() made the aggregator send the incomplete group on during shutdown, marked as completed by force, so the rest of the route still got to handle it.

completeAllOnStop() is the stricter alternative: shutdown waits until the pending groups complete by their own rules, up to the shutdown timeout. Both only help with a clean stop. A crash, a kill -9 or an out-of-memory error still loses every group held in memory. Surviving those needs the groups stored outside the JVM, which is the next section.

Keeping groups in a database

The place where groups wait is called the aggregation repository. The camel-sql module has a JdbcAggregationRepository that keeps each group as a row in a database table, so groups survive a restart. You plug it in with one extra line on the aggregator:

Java
.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:

Java
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:

Output
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_agg held one row: order A with its two items. The second application loaded that row, added the desk and sent on book,lamp,desk, and the row was deleted.

Now look at the second run. With AggregationStrategies.string(",") the order came out as ,desk: the book and the lamp were lost. That strategy builds its text in an exchange property and only writes it into the body when the group completes, and the JDBC repository saves the body and headers but not exchange properties. So a strategy used with a database repository must keep everything in the body or in headers, and the body must be serializable, meaning Java can turn it into bytes to store it.

The repository needs two tables with the columns id, exchange and version: one named after the repository, and one with the suffix _completed, where completed groups wait until the rest of the route has handled them. If that fails, the group is recovered from _completed and sent again. The version column lets several instances share the same tables safely when the aggregator uses optimisticLocking().

A version note: Camel 4.23 deprecated MemoryAggregationRepository, the default in-memory store, in favour of KeyValueAggregationRepository with a MemoryKeyValueRepository. Nothing in the behaviour above changes; groups in memory are still lost when the JVM stops.

A few more options

  • completionInterval(ms) completes all groups on a fixed schedule, for example to write one batch per second.
  • completionFromBatchConsumer() completes a group when a batch from a consumer such as the file component is done, for example all the files of one poll.
  • closeCorrelationKeyOnCompletion(n) remembers the last n completed orders and rejects late items for them with ClosedCorrelationKeyException, instead of starting a new group like the mug did in Grouping items by order.
  • discardOnCompletionTimeout() throws away groups that time out instead of sending them on, for cases where a partial order is worthless.
  • completionOnNewCorrelationGroup() completes the current group as soon as an item with a different key arrives, for input that is already sorted by order.
  • aggregateController(...) lets code outside the route complete groups, for example from an admin endpoint.

Recap

Aggregator settings for common situations
SituationSettings
Groups of known sizecompletionSize(n) plus completionTimeout for groups that never fill up
The last message marks the endcompletionPredicate with eagerCheckCompletion()
Batch writes on a schedulecompletionInterval, with completionSize as an upper bound
Only the latest value mattersAggregationStrategies.useLatest()
The next step needs every message's headersAggregationStrategies.groupedExchange()
Groups must survive a clean shutdownforceCompletionOnStop() or completeAllOnStop()
Groups must survive a crash, or be shared by several instancesA database repository such as JdbcAggregationRepository, with a strategy that keeps its state in the body

When the related messages all come from one message, the splitter can split it and recombine the parts itself, which is simpler because nothing has to wait between messages. For the patterns that send messages out to several places in the first place, see multicast and the other EIPs, and for testing aggregators with mock endpoints, see the Camel testing page.