The Camel throttler: protecting slow systems from too many calls

The throttler limits how fast messages pass a point in a route, so that a partner API, a database or a legacy system receives only what it can handle. Camel 4 has two throttling modes that measure different things. This page explains both, then runs each with Camel 4.23, along with rejection, per-customer limits, limits taken from a header and asynchronous delays.

Contents

What the throttler does and how it measures load

Integration routes often feed systems that are slower than the routes themselves. A partner API allows 100 calls per minute, a mainframe accepts five connections, a database falls over under a burst of inserts. The throttler sits in front of such a system and holds messages back when they arrive too fast, so the system sees a steady load instead of the burst.

A throttler needs a measure of load, and Camel 4 offers two:

  • Total requests: at most N messages may pass in each time period, such as 3 per second. This is a rate limit, the right model for APIs with a quota.
  • Concurrent requests: at most N messages may be past the throttler and not yet finished at the same time. This is a concurrency limit, the right model for systems with a fixed number of connections or workers.

The two modes have a history worth knowing when you read older examples. Up to Camel 4.2, the throttler only counted requests per period. Camel 4.3 replaced that with the concurrent-requests model and removed timePeriodMillis. Camel 4.4 brought both back as two modes. In Camel 4.23 the default mode is TotalRequests, as the throttle definition's metadata in the camel-core-model jar shows, so throttle(3) means three per second.

Throttle options in Camel 4.23
OptionDefaultMeaning
throttle(expression)RequiredThe limit: requests per period, or concurrent requests
totalRequestsMode(), concurrentRequestsMode()Total requestsWhich measure the limit applies to
timePeriodMillis1000The period for total-requests mode
rejectExecutionfalseFail excess messages instead of making them wait
asyncDelayedfalseRelease the caller's thread while a message waits
correlationExpressionNoneKeep a separate limit for each key, such as each customer
callerRunsWhenRejectedtrueWith asyncDelayed, run on the caller's thread when the pool is full

The examples run with Camel 4.23 on Java 21, with camel-main and the core components. They measure time, so their output prints rounded values and comparisons rather than milliseconds (rough measurements, on a shared Linux container).

Total-requests mode: N messages per period

Ten messages are sent as fast as the caller can, through a throttle of 3 per second. The program records the second in which each message got through:

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

public class TotalRequests {

    static final Map<Long, List<Integer>> BY_SECOND = new TreeMap<>();
    static long start;

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:api")
                .throttle(3).timePeriodMillis(1000)
                .process(e -> {
                    long second = (System.nanoTime() - start) / 1000000000L;
                    BY_SECOND.computeIfAbsent(second, s -> new ArrayList<>())
                        .add(e.getMessage().getBody(Integer.class));
                });
        }
    }

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

        start = System.nanoTime();
        for (int i = 1; i <= 10; i++) {
            template.sendBody("direct:api", i);
        }
        long totalMs = (System.nanoTime() - start) / 1000000;
        BY_SECOND.forEach((second, ids) ->
            System.out.println("second " + second + ": messages " + ids));
        System.out.println("10 messages took more than 3 s: " + (totalMs > 3000));
        camel.stop();
    }
}
Output
second 0: messages [1, 2, 3]
second 1: messages [4, 5, 6]
second 2: messages [7, 8, 9]
second 3: messages [10]
10 messages took more than 3 s: true
  • Messages 1 to 3 passed at once, in second 0. Message 4 had to wait for the next period, and so on, three per second.
  • Message 10 passed in second 3, so the ten messages took more than three seconds although the work itself took almost nothing.
  • The caller was blocked while each message waited. With a direct endpoint the waiting happens on the caller's thread, which is what slowed the loop.

Waiting messages are held in memory, each one occupying a thread unless asyncDelayed is set. A throttle that is much slower than the incoming rate builds an ever-growing backlog, so the producer has to slow down too. A consumer that takes the next message only when the route is free, such as JMS or Kafka, adapts on its own. An HTTP endpoint that keeps accepting requests does not.

Concurrent-requests mode: N messages in flight

Six callers hit a service that takes 300 ms per call, first without a throttle and then with throttle(2).concurrentRequestsMode(). The service counts how many calls run at the same moment:

Java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
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;

public class ConcurrentRequests {

    static final AtomicInteger ACTIVE = new AtomicInteger();
    static final AtomicInteger PEAK = new AtomicInteger();

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:unlimited")
                .to("direct:slowService");
            from("direct:throttled")
                .throttle(2).concurrentRequestsMode()
                .to("direct:slowService");

            from("direct:slowService")
                .process(e -> {
                    int now = ACTIVE.incrementAndGet();
                    PEAK.accumulateAndGet(now, Math::max);
                    Thread.sleep(300);
                    ACTIVE.decrementAndGet();
                });
        }
    }

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

        for (String route : new String[] {"unlimited", "throttled"}) {
            PEAK.set(0);
            ExecutorService callers = Executors.newFixedThreadPool(6);
            long start = System.nanoTime();
            for (int i = 0; i < 6; i++) {
                callers.submit(() -> template.sendBody("direct:" + route, "call"));
            }
            callers.shutdown();
            callers.awaitTermination(10, TimeUnit.SECONDS);
            long ms = (System.nanoTime() - start) / 1000000;
            System.out.printf("%-9s 6 callers: at most %d calls at once, about %d x 300 ms%n",
                route, PEAK.get(), Math.round(ms / 300.0));
        }
        camel.stop();
    }
}
Output
unlimited 6 callers: at most 6 calls at once, about 1 x 300 ms
throttled 6 callers: at most 2 calls at once, about 3 x 300 ms
  • Without the throttle, all six calls ran at once and the whole batch took about one call's time.
  • With the throttle, never more than two calls ran at once. The six calls went through in three waves of two, about three times 300 ms.

The concurrent mode needs no time period. A slot is freed when an exchange finishes the rest of the route, so the limit adapts to how fast the downstream system answers: if calls slow down to 3 s, throughput drops by itself, where a per-second limit would keep sending and pile up calls inside the slow system. Use concurrent mode when the downstream limit is about connections or threads, and total-requests mode when it is a quota per unit of time.

Rejecting instead of waiting

Waiting is not always better. A web request held for seconds ties up a server thread and probably times out anyway. rejectExecution(true) fails excess messages at once with ThrottlerRejectedExecutionException, which the caller can turn into an HTTP 429 or a retry later. Both modes are shown:

Java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
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 RejectExcess {

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

            from("direct:totalMode")
                .throttle(3).timePeriodMillis(1000).rejectExecution(true)
                .setBody(constant("accepted"));

            from("direct:concurrentMode")
                .throttle(2).concurrentRequestsMode().rejectExecution(true)
                .process(e -> Thread.sleep(300))
                .setBody(constant("accepted"));
        }
    }

    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("total mode, 5 calls in a row:");
        for (int i = 1; i <= 5; i++) {
            Exchange result = template.send("direct:totalMode", e -> e.getMessage().setBody("x"));
            System.out.println("  call " + i + ": " + (result.isFailed()
                ? result.getException().getClass().getSimpleName()
                : result.getMessage().getBody()));
        }

        AtomicInteger accepted = new AtomicInteger();
        AtomicInteger rejected = new AtomicInteger();
        ExecutorService callers = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            callers.submit(() -> {
                Exchange result = template.send("direct:concurrentMode",
                    e -> e.getMessage().setBody("x"));
                (result.isFailed() ? rejected : accepted).incrementAndGet();
            });
        }
        callers.shutdown();
        callers.awaitTermination(10, TimeUnit.SECONDS);
        System.out.println("concurrent mode, 5 calls at once: " + accepted + " accepted, "
            + rejected + " rejected");
        camel.stop();
    }
}
Output
total mode, 5 calls in a row:
  call 1: accepted
  call 2: accepted
  call 3: accepted
  call 4: ThrottlerRejectedExecutionException
  call 5: ThrottlerRejectedExecutionException
concurrent mode, 5 calls at once: 2 accepted, 3 rejected
  • In total-requests mode with a limit of 3, calls 1 to 3 were accepted and calls 4 and 5, in the same second, failed with ThrottlerRejectedExecutionException.
  • In concurrent mode with a limit of 2, five simultaneous callers got 2 acceptances and 3 rejections, because the first two were still running when the other three arrived.

A rejected exchange is a failed exchange, so it goes through the error handler like any other failure. Redelivery with a delay longer than the throttle period turns a rejection into a later retry; an onException(ThrottlerRejectedExecutionException.class) clause can reply with a "try again later" message instead. The routes in this program call errorHandler(defaultErrorHandler().logExhausted(false)), so that the expected rejections are not logged with a stack trace each.

A separate limit for each key

A single shared limit lets one busy client use up everyone's capacity. correlationExpression keeps a separate limit for each value of an expression. One big customer sends six orders and a small customer sends one, through a limit of 2 per second, first shared and then per customer:

Java
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
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 PerKeyThrottle {

    static final Map<String, Long> LAST_DONE_MS = new ConcurrentHashMap<>();
    static long start;

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:shared")
                .throttle(2).timePeriodMillis(1000)
                .to("direct:record");
            from("direct:perCustomer")
                .throttle(2).timePeriodMillis(1000).correlationExpression(header("customer"))
                .to("direct:record");

            from("direct:record")
                .process(e -> LAST_DONE_MS.merge(e.getMessage().getHeader("customer",
                    String.class), (System.nanoTime() - start) / 1000000, Math::max));
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new Routes());
        camel.start();
        ProducerTemplate template = camel.createProducerTemplate();
        List<String> customers = List.of("big", "big", "big", "big", "big", "big", "small");

        for (String route : new String[] {"shared", "perCustomer"}) {
            LAST_DONE_MS.clear();
            ExecutorService callers = Executors.newFixedThreadPool(customers.size());
            start = System.nanoTime();
            for (String customer : customers) {
                callers.submit(() -> template.sendBodyAndHeader("direct:" + route, "order",
                    "customer", customer));
                Thread.sleep(20);
            }
            callers.shutdown();
            callers.awaitTermination(10, TimeUnit.SECONDS);
            System.out.printf("%-11s big done after about %d s, small done after about %d s%n",
                route, Math.round(LAST_DONE_MS.get("big") / 1000.0),
                Math.round(LAST_DONE_MS.get("small") / 1000.0));
        }
        camel.stop();
    }
}
Output
shared      big done after about 2 s, small done after about 3 s
perCustomer big done after about 2 s, small done after about 0 s
  • With a shared limit, the small customer's single order queued behind the big customer's six and finished after about 3 s.
  • With correlationExpression(header("customer")), the small customer had its own limit, and its order went through at once. The big customer's six orders still took about 2 s, the same as before.

Each key gets its own throttling state in memory. Keys with a few values, such as customer tiers or tenants, suit this well. A key with millions of values, such as a user id, keeps state for each of them, so throttle on a coarser key or put the limit in an API gateway.

Limits from a header, and asyncDelayed

The limit is an expression, evaluated per message, so it can come from a header or a property and change at run time. The same program also shows which thread carries on after a message has waited, with and without asyncDelayed():

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 DynamicAndAsync {

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:dynamic")
                .throttle(header("limit")).timePeriodMillis(1000)
                .process(e -> e.getMessage().setBody(Thread.currentThread().getName()));

            from("direct:async")
                .throttle(1).timePeriodMillis(500).asyncDelayed()
                .process(e -> e.getMessage().setBody(Thread.currentThread().getName()));
        }
    }

    static long timed(ProducerTemplate template, String uri, int count, Object limit) {
        long start = System.nanoTime();
        for (int i = 0; i < count; i++) {
            template.requestBodyAndHeader(uri, "x", "limit", limit);
        }
        return (System.nanoTime() - start) / 1000000;
    }

    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("limit header 10: 10 messages took under 1 s: "
            + (timed(template, "direct:dynamic", 10, 10) < 1000));
        System.out.println("limit header 2 : 6 messages took over 2 s: "
            + (timed(template, "direct:dynamic", 6, 2) > 2000));

        System.out.println("without asyncDelayed, continued on: "
            + template.requestBodyAndHeader("direct:dynamic", "x", "limit", 100));
        template.requestBody("direct:async", "first");
        System.out.println("with asyncDelayed, a delayed one continued on: "
            + template.requestBody("direct:async", "second", String.class)
                .replaceAll("#\\d+", "#N"));
        camel.stop();
    }
}
Output
limit header 10: 10 messages took under 1 s: true
limit header 2 : 6 messages took over 2 s: true
without asyncDelayed, continued on: main
with asyncDelayed, a delayed one continued on: Camel (camel-1) thread #N - Throttle
  • With the header limit set to 10, ten messages passed in under a second. Set to 2, six messages took more than two seconds, so the new value took effect without restarting the route. When the header is missing, the throttler keeps its previous limit.
  • Without asyncDelayed, the route continued on main: the caller's own thread had waited inside the throttler.
  • With asyncDelayed(), the second message, which had to wait half a second, continued on Camel (camel-1) thread #N - Throttle. The caller's thread was handed back while the message waited, and a scheduler thread picked the message up when its turn came. The program replaces the thread number with N, since it depends on how many threads Camel has created so far.

asyncDelayed matters for consumers that can do something else while a message waits, such as an asynchronous HTTP server or a seda consumer. Here the requestBody caller still waited for its reply, so the total time was the same. Read the limit from configuration, for example throttle(simple("${properties:api.limit}")), to tune it per environment.

Throttling at the consumer instead

The throttler limits messages already inside a route. Sometimes it is better not to take them in at all. ThrottlingInflightRoutePolicy watches how many exchanges a route has in flight and suspends the route's consumer when there are too many, resuming it when the number falls. For a JMS or Kafka consumer, that leaves the excess messages safely in the broker instead of in the JVM's memory. Other places to control rate:

  • Consumer settings: concurrentConsumers on seda and JMS, or maxPollRecords and the number of consumers on Kafka, cap the work entering a route.
  • The splitter: a parallelProcessing() split with its own small thread pool caps concurrency for the parts, as the splitter page shows.
  • A circuit breaker: when the downstream system is failing rather than slow, stop calling it for a while. The error handling page covers the circuit breaker EIP.
  • The delayer: delay(ms) waits a fixed time for every message, whatever the load. It suits spacing out retries, not protecting a system from bursts.

Choosing a throttling approach

Throttling approaches for common limits
Downstream limitUse
A quota, such as 100 calls per minutethrottle(100).timePeriodMillis(60000)
A fixed number of connections or workersthrottle(n).concurrentRequestsMode()
Callers that should fail fast, such as web requestsrejectExecution(true) plus an onException reply
A quota per customer or tenantcorrelationExpression(header("tenant"))
A limit that changes at run timethrottle(header(...)) or a property placeholder
Waiting messages should not hold threadsasyncDelayed()
Excess messages should stay in the brokerThrottlingInflightRoutePolicy or consumer settings

When upgrading from Camel 3 or Camel 4.3, check every throttle call: the same line can mean a per-second limit in one version and a concurrency limit in another. Writing the mode explicitly, with totalRequestsMode() or concurrentRequestsMode(), makes the intent clear in any version from 4.4 on. For the other flow-control patterns, see the EIP patterns page, and for scheduled work, the timer page.