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 Total-requests mode: N messages per period Concurrent-requests mode: N messages in flight Rejecting instead of waiting A separate limit for each key Limits from a header, and asyncDelayed Throttling at the consumer instead Choosing a throttling approach
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 timePeriodMillisTotalRequeststhrottle(3)
| Option | Default | Meaning |
|---|---|---|
throttle(expression) | Required | The limit: requests per period, or concurrent requests |
totalRequestsMode()concurrentRequestsMode() | Total requests | Which measure the limit applies to |
timePeriodMillis | 1000 | The period for total-requests mode |
rejectExecution | false | Fail excess messages instead of making them wait |
asyncDelayed | false | Release the caller's thread while a message waits |
correlationExpression | None | Keep a separate limit for each key, such as each customer |
callerRunsWhenRejected | true | With asyncDelayed |
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:
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();
}
}
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
endpoint the waiting happens on the caller's thread, which is what slowed the loop.direct
Waiting messages are held in memory, each one occupying a thread unless asyncDelayed
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()
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();
}
}
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)ThrottlerRejectedExecutionException
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();
}
}
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)errorHandler(defaultErrorHandler().logExhausted(false))
A separate limit for each key
A single shared limit lets one busy client use up everyone's capacity. correlationExpression
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();
}
}
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
, 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.correlationExpression(header("customer"))
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()
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();
}
}
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
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.limit - Without
, the route continued onasyncDelayed : the caller's own thread had waited inside the throttler.main - With
, the second message, which had to wait half a second, continued onasyncDelayed() . 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 withCamel (camel-1) thread #N - Throttle , since it depends on how many threads Camel has created so far.N
asyncDelayedsedarequestBodythrottle(simple("${properties:api.limit}"))
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
- Consumer settings:
onconcurrentConsumers and JMS, orseda and the number of consumers on Kafka, cap the work entering a route.maxPollRecords - The splitter: a
split with its own small thread pool caps concurrency for the parts, as theparallelProcessing()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:
waits a fixed time for every message, whatever the load. It suits spacing out retries, not protecting a system from bursts.delay(ms)
Choosing a throttling approach
| Downstream limit | Use |
|---|---|
| A quota, such as 100 calls per minute | throttle(100).timePeriodMillis(60000) |
| A fixed number of connections or workers | throttle(n).concurrentRequestsMode() |
| Callers that should fail fast, such as web requests | rejectExecution(true)onException |
| A quota per customer or tenant | correlationExpression(header("tenant")) |
| A limit that changes at run time | throttle(header(...)) |
| Waiting messages should not hold threads | asyncDelayed() |
| Excess messages should stay in the broker | ThrottlingInflightRoutePolicy |
When upgrading from Camel 3 or Camel 4.3, check every throttletotalRequestsMode()concurrentRequestsMode()