Enterprise Integration Patterns in Camel, shown running

Camel implements the Enterprise Integration Patterns catalogue as DSL methods, so most integration problems have a ready-made step. This page explains how the patterns are grouped, then runs six of the most used ones with Camel 4.23: multicast, wire tap, content enricher, idempotent consumer, resequencer and load balancer, including the copy and duplicate traps that catch people out.

Contents

What the Enterprise Integration Patterns are

Enterprise Integration Patterns, the 2003 book by Gregor Hohpe and Bobby Woolf, named the recurring problems of connecting systems through messages: how to send one message to several places, how to combine replies, how to drop duplicates, how to restore order. Camel was built around that catalogue. Each pattern is a DSL method, and each method becomes a processor that works on the exchange.

The patterns fall into a few groups, and knowing the group helps you find the right one:

Common EIPs in Camel by group
GroupPatterns (Camel DSL)Solves
Routingchoice, filter, recipientList, routingSlip, dynamicRouterWhere a message goes
Fan-out and fan-inmulticast, split, aggregate, wireTapOne message to many, or many to one
Transformationtransform, enrich, pollEnrich, marshal, claimCheckChanging or completing the content
Flow controlthrottle, delay, resequence, loop, sampleRate, timing and order
ReliabilityidempotentConsumer, circuitBreaker, loadBalance, sagaDuplicates, failures and spreading load

Almost every pattern makes the same three decisions, and most surprises come from the defaults:

  • Copies: does each branch get its own copy of the exchange, and how deep is that copy?
  • Threads: do the branches run one after another on the caller's thread, or in parallel on a pool?
  • Result: which message continues afterwards? Patterns that fan out take an AggregationStrategy to decide.

Routing, splitting, aggregating and throttling have their own pages, linked at the end. This page covers the other patterns most applications need. The examples run with Camel 4.23 on Java 21, with camel-main and the core components on the classpath.

Multicast: the same message to several endpoints

Multicast sends a copy of the message to a fixed list of endpoints and combines their replies. A product page needing stock, price and reviews from three services is the classic case. Each service here takes 300 ms, so the effect of parallelProcessing() shows in the timing:

Java
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.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class MulticastDemo {

    static class JoinReplies implements AggregationStrategy {
        @Override
        public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
            if (oldExchange == null) {
                return newExchange;
            }
            String joined = oldExchange.getMessage().getBody(String.class) + " | "
                + newExchange.getMessage().getBody(String.class);
            oldExchange.getMessage().setBody(joined);
            return oldExchange;
        }
    }

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:sequential")
                .multicast(new JoinReplies())
                    .to("direct:stock", "direct:price", "direct:reviews")
                .end();
            from("direct:parallel")
                .multicast(new JoinReplies()).parallelProcessing()
                    .to("direct:stock", "direct:price", "direct:reviews")
                .end();

            from("direct:stock").delay(300).syncDelayed().setBody(simple("stock(${body})=12"));
            from("direct:price").delay(300).syncDelayed().setBody(simple("price(${body})=9.99"));
            from("direct:reviews").delay(300).syncDelayed().setBody(simple("reviews(${body})=4.5"));
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new Routes());
        camel.start();
        ProducerTemplate template = camel.createProducerTemplate();
        template.requestBody("direct:parallel", "warm-up");

        for (String mode : new String[] {"sequential", "parallel"}) {
            long start = System.nanoTime();
            String reply = template.requestBody("direct:" + mode, "book-7", String.class);
            long ms = (System.nanoTime() - start) / 1000000;
            System.out.println(mode + ": " + reply);
            System.out.println("  took about " + Math.round(ms / 300.0) + " x 300 ms");
        }
        camel.stop();
    }
}
Output
sequential: stock(book-7)=12 | price(book-7)=9.99 | reviews(book-7)=4.5
  took about 3 x 300 ms
parallel: stock(book-7)=12 | price(book-7)=9.99 | reviews(book-7)=4.5
  took about 1 x 300 ms
  • Both runs produced the same reply, joined in the order of the to(...) list. With parallelProcessing(), replies arrive in any order, but Camel still aggregates them in list order unless streaming() is set.
  • Sequential multicast took about three times 300 ms, because each call waited for the previous one. In parallel, the three calls overlapped and the whole multicast took about 300 ms (rough comparison, on a shared Linux container).
  • JoinReplies receives null as oldExchange for the first reply, then the result so far together with each further reply. That is the contract of every AggregationStrategy in Camel.

Without a strategy, the body that continues after the multicast is the reply of the last endpoint, not the original message, which surprises people who use multicast only to notify other routes. Use AggregationStrategies.useOriginal() when the route should go on with the message it had before. stopOnException() stops at the first failing branch; without it, the remaining branches still run after one has failed.

Wire tap: a side copy that does not wait

A wire tap sends a copy of the exchange to another endpoint on a separate thread, and the main route carries on without waiting for it. It suits auditing and monitoring. The tap here changes a header and empties the body, which is a mutable List; the main route waits for the tap only so that the output is in a fixed order:

Java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class WireTapDemo {

    static final CountDownLatch TAPPED = new CountDownLatch(1);

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:order")
                .setHeader("stage", constant("received"))
                .wireTap("direct:audit")
                .process(e -> {
                    TAPPED.await(5, TimeUnit.SECONDS);
                    System.out.println("main route thread : " + Thread.currentThread().getName());
                    System.out.println("main route header : " + e.getMessage().getHeader("stage"));
                    System.out.println("main route body   : " + e.getMessage().getBody());
                });

            from("direct:audit")
                .process(e -> {
                    System.out.println("audit thread      : " + Thread.currentThread().getName());
                    e.getMessage().setHeader("stage", "audited");
                    List<?> lines = e.getMessage().getBody(List.class);
                    System.out.println("audit sees body   : " + lines);
                    lines.clear();
                    TAPPED.countDown();
                });
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new Routes());
        camel.start();
        ProducerTemplate template = camel.createProducerTemplate();

        List<String> lines = new ArrayList<>(List.of("book", "pen"));
        template.sendBody("direct:order", lines);
        System.out.println("caller's list now : " + lines);
        camel.stop();
    }
}
Output
audit thread      : Camel (camel-1) thread #1 - WireTap
audit sees body   : [book, pen]
main route thread : main
main route header : received
main route body   : []
caller's list now : []
  • The audit route ran on Camel (camel-1) thread #1 - WireTap, while the main route stayed on main.
  • The tap set the header stage to audited, but the main route still saw received. The copy has its own headers map.
  • The tap cleared the list, and the main route and the caller both saw []. The copy is shallow: both exchanges point to the same body object, so a change to a mutable body is visible everywhere.

Keep tapped bodies immutable, such as a String, a byte[] that no one modifies, or a Java record. Otherwise make a deep copy in the tap with onPrepare(...), a processor that runs on the copy before it is sent. A stream body, such as an InputStream from a file or HTTP call, can be read only once; enable stream caching, on by default in Camel 4, or convert the body to a String before the tap.

Content enricher: enrich and pollEnrich

The content enricher calls another endpoint and merges its result into the current message. The difference from a plain to() is the merge: to() replaces the message with the reply, while enrich() passes both to an aggregation strategy. This program looks up a customer name both ways, then reads from a queue with pollEnrich():

Java
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class EnricherDemo {

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:withEnrich")
                .enrich("direct:customerService", (original, resource) -> {
                    String name = resource.getMessage().getBody(String.class);
                    original.getMessage().setHeader("customerName", name);
                    return original;
                })
                .setBody(simple("${body} for ${header.customerName}"));

            from("direct:withTo")
                .to("direct:customerService")
                .setBody(simple("${body} for ${header.customerName}"));

            from("direct:customerService")
                .setBody(simple("Customer ${header.customerId}"));

            from("direct:withPollEnrich")
                .pollEnrich("seda:latestRates", 500)
                .setBody(simple("rate=${body}"));
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new Routes());
        camel.start();
        ProducerTemplate template = camel.createProducerTemplate();

        System.out.println("enrich    : " + template.requestBodyAndHeader("direct:withEnrich",
            "order 17", "customerId", "c-42"));
        System.out.println("to        : " + template.requestBodyAndHeader("direct:withTo",
            "order 17", "customerId", "c-42"));

        template.sendBody("seda:latestRates", "1.09");
        System.out.println("pollEnrich: " + template.requestBody("direct:withPollEnrich", "x"));
        long start = System.nanoTime();
        Object empty = template.requestBody("direct:withPollEnrich", "x");
        long ms = (System.nanoTime() - start) / 1000000;
        String waited = ms >= 500 ? "the full" : "less than";
        System.out.println("pollEnrich: " + empty + " (waited " + waited + " 500 ms timeout)");
        camel.stop();
    }
}
Output
enrich    : order 17 for Customer c-42
to        : Customer c-42 for 
pollEnrich: rate=1.09
pollEnrich: rate= (waited the full 500 ms timeout)
  • With enrich(), the strategy copied the customer name into a header and kept the original body, so the result is order 17 for Customer c-42.
  • With to(), the customer service's reply replaced the body, and nothing set the header, so the result is Customer c-42 for : the order text is lost and the name is empty.
  • The first pollEnrich took the message waiting on seda:latestRates. The second found the queue empty, waited the full 500 ms, and continued with an empty body.

enrich() sends the current exchange to a producer, such as an HTTP call or a database query. pollEnrich() instead reads from a consumer endpoint, such as a file, an FTP server or a queue, which is how a route started by one event reads data from somewhere else. Its timeout matters: a negative value, the default, waits until a message arrives, and 0 does not wait at all. Always set a timeout and handle the empty case, as a route waiting forever on an empty directory is hard to spot.

Idempotent consumer: processing each message once

Most transports deliver at least once: a broker redelivers after a timeout, a partner resends a file, a user clicks twice. An idempotent consumer keeps the keys it has seen in a repository and skips messages whose key is already there. This program sends a duplicate, a payment that fails and is retried, and a duplicate that is flagged instead of dropped:

Java
import java.util.TreeSet;
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.support.KeyValueIdempotentRepository;
import org.apache.camel.support.MemoryKeyValueRepository;

public class IdempotentDemo {

    static final MemoryKeyValueRepository STORE = new MemoryKeyValueRepository();
    static final KeyValueIdempotentRepository SEEN = new KeyValueIdempotentRepository(STORE);

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            errorHandler(defaultErrorHandler().logExhausted(false));

            from("direct:payments")
                .idempotentConsumer(header("paymentId"), SEEN)
                    .process(e -> {
                        String body = e.getMessage().getBody(String.class);
                        if (body.contains("fail")) {
                            throw new IllegalStateException("bank timeout");
                        }
                        System.out.println("  charged " + e.getMessage().getHeader("paymentId"));
                    })
                .end();

            from("direct:flagged")
                .idempotentConsumer(header("paymentId"), SEEN).skipDuplicate(false)
                    .filter(exchangeProperty(Exchange.DUPLICATE_MESSAGE).isEqualTo(true))
                        .process(e -> System.out.println("  duplicate flagged: "
                            + e.getMessage().getHeader("paymentId")))
                        .stop()
                    .end()
                    .process(e -> System.out.println("  charged " + e.getMessage()
                        .getHeader("paymentId")))
                .end();
        }
    }

    static void send(ProducerTemplate template, String endpoint, String id, String body) {
        try {
            template.sendBodyAndHeader(endpoint, body, "paymentId", id);
        } catch (Exception e) {
            System.out.println("  " + id + " failed: " + e.getCause().getMessage());
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new Routes());
        camel.start();
        ProducerTemplate template = camel.createProducerTemplate();

        System.out.println("p-1 twice, p-2 once:");
        send(template, "direct:payments", "p-1", "ok");
        send(template, "direct:payments", "p-1", "ok");
        send(template, "direct:payments", "p-2", "ok");
        System.out.println("p-3 fails, then is retried:");
        send(template, "direct:payments", "p-3", "fail");
        send(template, "direct:payments", "p-3", "ok");
        System.out.println("skipDuplicate(false):");
        send(template, "direct:flagged", "p-2", "ok");
        send(template, "direct:flagged", "p-4", "ok");
        System.out.println("keys in repository: " + new TreeSet<>(STORE.keys()));
        camel.stop();
    }
}
Output
p-1 twice, p-2 once:
  charged p-1
  charged p-2
p-3 fails, then is retried:
  p-3 failed: bank timeout
  charged p-3
skipDuplicate(false):
  duplicate flagged: p-2
  charged p-4
keys in repository: [idempotent:p-1, idempotent:p-2, idempotent:p-3, idempotent:p-4]
  • The second p-1 was skipped without any output, and the caller got no error: duplicates are dropped silently.
  • p-3 failed, and its retry was charged. When an exchange fails, the consumer removes its key again (removeOnFailure defaults to true), so a failed message can be retried.
  • With skipDuplicate(false), the duplicate p-2 was not skipped but went through with the property CamelDuplicateMessage set to true, so the route could log it and stop. p-4 was new and was charged.
  • The repository held four keys at the end. KeyValueIdempotentRepository stored them with the prefix idempotent: in a MemoryKeyValueRepository.

Camel 4.23 deprecated MemoryIdempotentRepository in favour of KeyValueIdempotentRepository, built on the new KeyValueRepository interface. The old class still works but compiles with a deprecation warning. Its in-memory store has no size setting, so plan for growth when keys never repeat. An in-memory repository forgets everything on restart and is not shared between instances; for a service with several replicas, use a shared store such as the JDBC, Redis or Infinispan repositories from their component jars.

The key is added when the message arrives (eager is true by default), so a duplicate that arrives while the first is still being processed is also skipped. The key must identify the business event, such as a payment id, not the transport message, because a redelivered message may get a new message id.

Resequencer: putting messages back in order

Parallel processing and partitioned transports deliver messages out of order. The resequencer holds messages and releases them sorted by an expression, here a sequence number header. The batch mode collects a group and sorts it; the stream mode releases each message as soon as its predecessor has gone, and has to decide how long to wait for a missing one:

Java
import java.util.List;
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.component.mock.MockEndpoint;

public class ResequencerDemo {

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:batch")
                .resequence(header("seq")).batch().size(5).timeout(1000)
                .to("mock:batchOut");

            from("direct:stream")
                .resequence(header("seq")).stream().capacity(100).timeout(300)
                .to("mock:streamOut");
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new Routes());
        camel.start();
        ProducerTemplate template = camel.createProducerTemplate();

        MockEndpoint batchOut = camel.getEndpoint("mock:batchOut", MockEndpoint.class);
        batchOut.setExpectedCount(5);
        MockEndpoint streamOut = camel.getEndpoint("mock:streamOut", MockEndpoint.class);
        streamOut.setExpectedCount(4);

        long batchStart = System.nanoTime();
        List<Long> arrival = List.of(3L, 1L, 5L, 2L, 4L);
        System.out.println("arrival order : " + arrival);
        for (long seq : arrival) {
            template.sendBodyAndHeader("direct:batch", "msg" + seq, "seq", seq);
        }
        batchOut.assertIsSatisfied(3000);
        long batchMs = (System.nanoTime() - batchStart) / 1000000;
        System.out.println("batch output  : " + bodies(batchOut));
        System.out.println("released before the 1000 ms timeout: " + (batchMs < 1000));

        List<Long> withGap = List.of(2L, 1L, 4L, 5L);
        System.out.println("stream input  : " + withGap + " (3 never arrives)");
        long start = System.nanoTime();
        for (long seq : withGap) {
            template.sendBodyAndHeader("direct:stream", "msg" + seq, "seq", seq);
        }
        streamOut.assertIsSatisfied(3000);
        long ms = (System.nanoTime() - start) / 1000000;
        System.out.println("stream output : " + bodies(streamOut));
        System.out.println("waited for the gap: " + (ms >= 300 ? "yes, at least" : "no, under")
            + " the 300 ms timeout");
        camel.stop();
    }

    static List<String> bodies(MockEndpoint mock) {
        return mock.getExchanges().stream()
            .map(e -> e.getMessage().getBody(String.class)).toList();
    }
}
Output
arrival order : [3, 1, 5, 2, 4]
batch output  : [msg1, msg2, msg3, msg4, msg5]
released before the 1000 ms timeout: true
stream input  : [2, 1, 4, 5] (3 never arrives)
stream output : [msg1, msg2, msg4, msg5]
waited for the gap: yes, at least the 300 ms timeout
  • The batch resequencer received 3, 1, 5, 2, 4 and released 1 to 5 in order. It released them as soon as the batch held its size(5), before the 1000 ms timeout.
  • The stream resequencer released 1 and 2 at once. Number 3 never arrived, so it held 4 and 5 until the 300 ms timeout passed, then released them, skipping the gap.

Batch mode suits reports and other cases where a group of messages arrives together. Stream mode suits continuous flows with gap-free sequence numbers; its expression must return a number, and its capacity bounds how many messages it holds. Both keep messages in memory, so a crash loses the held messages. When the transport can keep order itself, as Kafka does within one partition for messages with the same key, that is usually cheaper than resequencing.

Load balancer: spreading work across endpoints

The load balancer sends each message to one of several endpoints. Three strategies show the common choices: round robin, weighted round robin with weights 3 and 1, and failover from a server that always fails:

Java
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class LoadBalancerDemo {

    static final List<String> LOG = new ArrayList<>();

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            errorHandler(defaultErrorHandler().logExhausted(false));

            from("direct:roundRobin")
                .loadBalance().roundRobin()
                    .to("direct:a", "direct:b", "direct:c")
                .end();

            from("direct:weighted")
                .loadBalance().weighted(true, "3,1")
                    .to("direct:a", "direct:b")
                .end();

            from("direct:failover")
                .loadBalance().failover(IllegalStateException.class)
                    .to("direct:down", "direct:b")
                .end();

            from("direct:a").process(e -> LOG.add("a"));
            from("direct:b").process(e -> LOG.add("b"));
            from("direct:c").process(e -> LOG.add("c"));
            from("direct:down").process(e -> {
                LOG.add("down!");
                throw new IllegalStateException("server down");
            });
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new Routes());
        camel.start();
        ProducerTemplate template = camel.createProducerTemplate();

        for (String balancer : new String[] {"roundRobin", "weighted", "failover"}) {
            LOG.clear();
            int count = balancer.equals("failover") ? 3 : 8;
            for (int i = 0; i < count; i++) {
                template.sendBody("direct:" + balancer, i);
            }
            System.out.printf("%-10s %d messages -> %s%n", balancer, count, LOG);
        }
        camel.stop();
    }
}
Output
roundRobin 8 messages -> [a, b, c, a, b, c, a, b]
weighted   8 messages -> [a, b, a, a, a, b, a, a]
failover   3 messages -> [down!, b, down!, b, down!, b]
  • Round robin sent eight messages to a, b, c in turn, so a and b got three each and c two.
  • Weighted round robin with "3,1" sent six messages to a and two to b, the 3:1 ratio of the weights.
  • Failover tried down for every message, caught the IllegalStateException and moved to b. Every message ended up at b, but each one paid for a failed attempt first.

Plain failover() always starts with the first endpoint. Pass failover(-1, false, true) for round-robin failover, which spreads the first attempts and keeps trying until one endpoint works; its arguments are the maximum failover attempts, whether to use the route's error handler, and round robin. The routes in this program call errorHandler(defaultErrorHandler().logExhausted(false)), because the failing route's error handler would otherwise log an ERROR with a stack trace for every attempt that failover then recovers from. Other strategies are random, sticky (by a key, such as a session id) and topic, which sends to all endpoints.

Choosing a pattern

Which pattern fits which problem
ProblemPatternWatch out for
Call several services and combine the answersmulticast() with parallelProcessing() and a strategyWithout a strategy, the last reply continues
Audit or monitor without slowing the routewireTap()Shallow copy of mutable bodies
Add data from another service to the messageenrich() with a strategyto() replaces the message instead
Read a file or queue in the middle of a routepollEnrich() with a timeoutThe default waits forever
Ignore redelivered or resent messagesidempotentConsumer() with a shared repositoryIn-memory keys are lost on restart
Restore order after parallel processingresequence()Held messages are lost on a crash
Spread load or survive one endpoint failingloadBalance()Plain failover always tries the first endpoint first

The remaining core patterns have their own pages: routing with choice, filter and recipient list, the splitter, the aggregator and the throttler. Failures inside any of them are handled as described on the error handling page, which also covers the circuit breaker.