Apache Camel Kafka component: producing, consuming and committing
The Kafka component turns Camel messages into Kafka records and records into exchanges. Its defaults decide where a new consumer group starts, what happens to a record that fails, and when offsets are committed. This page explains how the consumer and producer work, then runs each important case against a real Kafka 4.2 broker started inside the program.
Contents
How the Kafka component maps records to exchanges A first producer and consumer Keys, partitions and record headers When the route fails: skipped, dead-lettered or retried Committing offsets yourself Parallel consumers and partitions Configuration in Spring Boot and real clusters Choosing consumer and producer settings
How the Kafka component maps records to exchanges
The Kafka component, in camel-kafkakafka:topicName?optionsto()from()kafka-clients
The consumer side works like this:
- The route starts
threads (1 by default). Each one creates its ownconsumersCount , joins the consumer group named byKafkaConsumer , and receives some of the topic's partitions.groupId - Each thread calls
in a loop, gets up topoll() records (500 by default), and runs the route once per record, in offset order.maxPollRecords - Offsets are committed by the Kafka client every 5 seconds by default (
,autoCommitEnable=true ), or by the route itself with manual commits.autoCommitIntervalMs=5000 - If the route fails for a record,
decides whether the thread moves on to the next record or goes back and tries again.breakOnFirstError
The producer side is simpler: the body becomes the record value, the CamelKafkaKeyrequestRequiredAcks=allenableIdempotence=true
| Header | Direction | Meaning |
|---|---|---|
CamelKafkaKey | Both | The record key |
CamelKafkaPartitionKey | Producer | An explicit partition number |
CamelKafkaOverrideTopic | Producer | Send to this topic instead of the endpoint's |
CamelKafkaTopicCamelKafkaPartitionCamelKafkaOffset | Consumer | Where the record came from |
CamelKafkaTimestamp | Consumer | The record timestamp |
CamelKafkaManualCommit | Consumer | The commit handle, with allowManualCommit=true |
CamelKafkaRecordMeta | Producer | Partition and offset of sent records, with recordMetadata=true |
Older Camel releases used other names for these headers, such as kafka.KEYKafkaConstants
Every program on this page starts its own single-node Kafka 4.2 broker in KRaft mode, inside the same JVM, with EmbeddedKafkaKraftBrokerspring-kafka-testcamel-kafkaAdmin
A first producer and consumer
One route sends three orders to a topic with one partition, two with keys and one without, and a second route reads them back as the consumer group billing
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.kafka.KafkaComponent;
import org.apache.camel.component.kafka.KafkaConstants;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class FirstRoute {
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
EmbeddedKafkaBroker broker = startBroker();
String brokers = broker.getBrokersAsString();
try (Admin admin = Admin.create(Map.of(
AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, brokers))) {
admin.createTopics(List.of(new NewTopic("orders", 1, (short) 1))).all().get();
}
CamelContext context = new DefaultCamelContext();
// every kafka: endpoint in this context uses this broker list
context.getComponent("kafka", KafkaComponent.class).getConfiguration()
.setBrokers(brokers);
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:placeOrder")
.to("kafka:orders?recordMetadata=true");
from("kafka:orders?groupId=billing&autoOffsetReset=earliest")
.routeId("billing")
.process(e -> {
var in = e.getMessage();
System.out.println("billing got '" + in.getBody()
+ "' (" + in.getBody().getClass().getSimpleName()
+ ") from topic " + in.getHeader(KafkaConstants.TOPIC)
+ ", partition " + in.getHeader(KafkaConstants.PARTITION)
+ ", offset " + in.getHeader(KafkaConstants.OFFSET)
+ ", key " + in.getHeader(KafkaConstants.KEY));
});
}
});
NotifyBuilder threeRead = new NotifyBuilder(context).fromRoute("billing")
.whenDone(3).create();
context.start();
ProducerTemplate template = context.createProducerTemplate();
var sent = template.request("direct:placeOrder", e -> {
e.getMessage().setBody("order 1: 2 x book");
e.getMessage().setHeader(KafkaConstants.KEY, "customer-7");
});
@SuppressWarnings("unchecked")
List<RecordMetadata> metadata = sent.getMessage()
.getHeader(KafkaConstants.KAFKA_RECORD_META, List.class);
System.out.println("sent: " + metadata);
template.sendBodyAndHeader("direct:placeOrder", "order 2: 1 x pen",
KafkaConstants.KEY, "customer-9");
template.sendBody("direct:placeOrder", "order 3: no key");
System.out.println("all three read: " + threeRead.matches(20, TimeUnit.SECONDS));
context.close();
broker.destroy();
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream())); // storage format log
try {
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
sent: [orders-0@0]
billing got 'order 1: 2 x book' (String) from topic orders, partition 0, offset 0, key customer-7
billing got 'order 2: 1 x pen' (String) from topic orders, partition 0, offset 1, key customer-9
billing got 'order 3: no key' (String) from topic orders, partition 0, offset 2, key null
all three read: true
- With
, the producer put the broker's answer in therecordMetadata=true header.CamelKafkaRecordMeta means topicorders-0@0 , partition 0, offset 0.orders - The consumer received each record as a
, because the default deserializers areString for both key and value. UseStringDeserializer for other types.valueDeserializer - The headers show where each record came from: partition 0 and offsets 0, 1 and 2, in the order sent. The third record had no key, so
wasCamelKafkaKey .null - The program set the broker list once, on the component configuration, so the endpoints need only the topic and the consumer options.
autoOffsetReset=earliestbillinglatest
Keys, partitions and record headers
Records with the same key always go to the same partition, which is how Kafka keeps them in order. This program sends three payments for each of four customers to a topic with three partitions, and puts three extra headers on each message:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.kafka.KafkaComponent;
import org.apache.camel.component.kafka.KafkaConstants;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class KeysAndHeaders {
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
EmbeddedKafkaBroker broker = startBroker();
try (Admin admin = Admin.create(Map.of(
AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, broker.getBrokersAsString()))) {
admin.createTopics(List.of(new NewTopic("payments", 3, (short) 1))).all().get();
}
Map<String, List<String>> byPartition = new TreeMap<>();
CamelContext context = new DefaultCamelContext();
context.getComponent("kafka", KafkaComponent.class).getConfiguration()
.setBrokers(broker.getBrokersAsString());
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("kafka:payments?groupId=ledger&autoOffsetReset=earliest")
.routeId("ledger")
.process(e -> {
var in = e.getMessage();
byPartition.computeIfAbsent("partition "
+ in.getHeader(KafkaConstants.PARTITION),
p -> new ArrayList<>()).add(in.getBody(String.class));
if (in.getBody(String.class).equals("c1 #1")) {
byte[] source = in.getHeader("source", byte[].class);
byte[] attempt = in.getHeader("attempt", byte[].class);
System.out.println("headers on 'c1 #1' as received:");
System.out.println(" source: type "
+ in.getHeader("source").getClass().getSimpleName()
+ ", bytes " + Arrays.toString(source)
+ ", as String '" + new String(source,
StandardCharsets.UTF_8) + "'");
System.out.println(" attempt: bytes "
+ Arrays.toString(attempt) + ", as int "
+ ByteBuffer.wrap(attempt).getInt());
System.out.println(" CamelFileName: "
+ in.getHeader("CamelFileName"));
}
});
}
});
NotifyBuilder all = new NotifyBuilder(context).fromRoute("ledger").whenDone(12).create();
context.start();
ProducerTemplate template = context.createProducerTemplate();
for (int i = 1; i <= 3; i++) {
for (String customer : new String[] {"c1", "c2", "c3", "c4"}) {
template.sendBodyAndHeaders("kafka:payments", customer + " #" + i, Map.of(
KafkaConstants.KEY, customer,
"source", "web",
"attempt", 1,
"CamelFileName", "in.csv"));
}
}
System.out.println("all 12 read: " + all.matches(20, TimeUnit.SECONDS));
byPartition.forEach((partition, values) ->
System.out.println(partition + ": " + values));
context.close();
broker.destroy();
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream())); // storage format log
try {
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
headers on 'c1 #1' as received:
source: type byte[], bytes [119, 101, 98], as String 'web'
attempt: bytes [0, 0, 0, 1], as int 1
CamelFileName: null
all 12 read: true
partition 1: [c2 #1, c2 #2, c2 #3]
partition 2: [c1 #1, c3 #1, c4 #1, c1 #2, c3 #2, c4 #2, c1 #3, c3 #3, c4 #3]
- All of
's payments went to partition 1, andc2 ,c1 andc3 all went to partition 2, each customer's payments in the order sent. The default partitioner hashes the key with murmur2 and takes it modulo the number of partitions.c4 - Partition 0 received nothing. With few keys, hashing can be very uneven. It evens out with many keys, but a topic with a handful of hot keys keeps its hot partitions.
- The header
arrived as asource , the bytes ofbyte[] , not as aweb . Kafka headers are byte arrays, and the default header deserializer does not convert them back.String or a customgetHeader("source", String.class) does.headerDeserializer - The header
was theattempt 1, so the producer wrote four bytes,Integer . Read as a[0, 0, 0, 1] , that is unprintable control characters; read as an int, it is 1. Send header values as strings when other programs will read them.String did not arrive: headers starting withCamelFileName are filtered out on the way in and out.Camel
As with HTTP, every other message header becomes a Kafka header, including ones left by earlier steps of the route. Use removeHeaders()to("kafka:...")
When the route fails: skipped, dead-lettered or retried
A consumer that fails on one record has three choices: skip it and go on, put it somewhere for later, or stop and try again. Three records, one of which always fails, show what Camel does in each case:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.kafka.KafkaComponent;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class ConsumerErrors {
static String brokers;
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
EmbeddedKafkaBroker broker = startBroker();
brokers = broker.getBrokersAsString();
try (Admin admin = Admin.create(Map.of(
AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, brokers))) {
admin.createTopics(List.of(new NewTopic("orders", 1, (short) 1),
new NewTopic("orders.DLT", 1, (short) 1))).all().get();
}
CamelContext sender = context();
sender.start();
ProducerTemplate template = sender.createProducerTemplate();
for (String order : new String[] {"ok-1", "bad", "ok-2"}) {
template.sendBody("kafka:orders", order);
}
sender.close();
System.out.println("1. Default settings:");
consume("group-a", "", false, 3);
System.out.println(" restarted with the same group id:");
consume("group-a", "", false, 0);
System.out.println("2. Dead letter channel to orders.DLT:");
consume("group-b", "", true, 3);
CamelContext dltReader = context();
dltReader.start();
Object dead = dltReader.createConsumerTemplate().receiveBody(
"kafka:orders.DLT?groupId=dlt-reader&autoOffsetReset=earliest", 20000);
System.out.println(" orders.DLT holds: " + dead);
dltReader.close();
System.out.println("3. breakOnFirstError=true:");
consume("group-c", "&breakOnFirstError=true", false, 4);
broker.destroy();
}
// runs one consumer until it has finished 'exchanges' exchanges (or 8 seconds pass)
static void consume(String group, String options, boolean deadLetter, int exchanges)
throws Exception {
CamelContext context = context();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
if (deadLetter) {
errorHandler(deadLetterChannel("kafka:orders.DLT"));
}
from("kafka:orders?autoOffsetReset=earliest&groupId=" + group + options)
.routeId("consumer")
.process(e -> {
String order = e.getMessage().getBody(String.class);
System.out.println(" processing " + order);
if (order.equals("bad")) {
throw new IllegalArgumentException("cannot bill " + order);
}
});
}
});
NotifyBuilder done = new NotifyBuilder(context).fromRoute("consumer")
.whenDone(Math.max(exchanges, 1)).create();
context.start();
boolean finished = done.matches(exchanges == 0 ? 8 : 20, TimeUnit.SECONDS);
if (exchanges == 0) {
System.out.println(" nothing delivered in 8 seconds: " + !finished);
}
context.close();
}
static CamelContext context() {
CamelContext context = new DefaultCamelContext();
context.getComponent("kafka", KafkaComponent.class).getConfiguration()
.setBrokers(brokers);
return context;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream())); // storage format log
try {
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
1. Default settings:
processing ok-1
processing bad
processing ok-2
restarted with the same group id:
nothing delivered in 8 seconds: true
2. Dead letter channel to orders.DLT:
processing ok-1
processing bad
processing ok-2
orders.DLT holds: bad
3. breakOnFirstError=true:
processing ok-1
processing bad
processing ok-1
processing bad
- Default settings: the route failed on
, the error handler logged it, and the consumer went on tobad . After a restart with the same group id, nothing came back, because the committed offset had moved pastok-2 . The failed order was lost, and only a log line recorded it.bad - Dead letter channel:
sent the failed exchange to another topic, and the program readerrorHandler(deadLetterChannel("kafka:orders.DLT")) back frombad . The consumer then went on toorders.DLT . Nothing was lost, and the failed record can be inspected or replayed later.ok-2 - breakOnFirstError=true: after
failed, the consumer went back to the last committed offset and polled again. No offset had been committed yet, since the automatic commit runs every 5 seconds, so it processedbad a second time before failing onok-1 again. It would keep doing so; the program stopped after four exchanges.bad
The third case shows two problems at once. A record that can never succeed blocks its partition forever, and records before it may be processed twice. Use breakOnFirstError=trueonExceptionmaximumRedeliveries
Committing offsets yourself
With automatic commits, the Kafka client commits the offsets it has polled every five seconds, whether or not the route has finished with those records. A crash can therefore lose records or deliver them twice. Manual commits tie the commit to the route's work. This program commits after the first two of four invoices only, then restarts with the same group id:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.kafka.KafkaComponent;
import org.apache.camel.component.kafka.KafkaConstants;
import org.apache.camel.component.kafka.consumer.KafkaManualCommit;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class ManualCommit {
static String brokers;
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
EmbeddedKafkaBroker broker = startBroker();
brokers = broker.getBrokersAsString();
try (Admin admin = Admin.create(Map.of(
AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, brokers))) {
admin.createTopics(List.of(new NewTopic("invoices", 1, (short) 1))).all().get();
}
CamelContext sender = context();
sender.start();
ProducerTemplate template = sender.createProducerTemplate();
for (int i = 1; i <= 4; i++) {
template.sendBody("kafka:invoices", "invoice-" + i);
}
sender.close();
System.out.println("First run: commits after invoice-1 and invoice-2 only");
run(4);
System.out.println("Second run, same group id:");
run(2);
broker.destroy();
}
static void run(int expected) throws Exception {
CamelContext context = context();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("kafka:invoices?groupId=archiver&autoOffsetReset=earliest"
+ "&autoCommitEnable=false&allowManualCommit=true")
.routeId("archiver")
.process(e -> {
String invoice = e.getMessage().getBody(String.class);
long offset = e.getMessage().getHeader(KafkaConstants.OFFSET,
Long.class);
KafkaManualCommit commit = e.getMessage().getHeader(
KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class);
if (offset < 2) {
commit.commit();
System.out.println(" " + invoice + " at offset " + offset
+ ": stored, committed");
} else {
System.out.println(" " + invoice + " at offset " + offset
+ ": stored, not committed");
}
});
}
});
NotifyBuilder done = new NotifyBuilder(context).fromRoute("archiver")
.whenDone(expected).create();
context.start();
done.matches(20, TimeUnit.SECONDS);
context.close();
}
static CamelContext context() {
CamelContext context = new DefaultCamelContext();
context.getComponent("kafka", KafkaComponent.class).getConfiguration()
.setBrokers(brokers);
return context;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream())); // storage format log
try {
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
First run: commits after invoice-1 and invoice-2 only
invoice-1 at offset 0: stored, committed
invoice-2 at offset 1: stored, committed
invoice-3 at offset 2: stored, not committed
invoice-4 at offset 3: stored, not committed
Second run, same group id:
invoice-3 at offset 2: stored, not committed
invoice-4 at offset 3: stored, not committed
put aallowManualCommit=true in theKafkaManualCommit header of each exchange, andCamelKafkaManualCommit stopped the client from committing on its own.autoCommitEnable=false- The first run processed all four invoices but committed only after offsets 0 and 1.
- The second run, in the same group, started at offset 2 and received
andinvoice-3 again: everything after the last commit is redelivered.invoice-4
The default commit factory commits synchronously, waiting for the broker; DefaultKafkaManualAsyncCommitFactoryCamelKafkaLastPollRecord
Parallel consumers and partitions
Parallelism in a Kafka consumer group comes from partitions: each partition is read by exactly one consumer in the group at a time. This program reads 300 records spread over three partitions with one, three and four consumer threads, using a new topic for each run. It waits until the group is stable before sending, so that every consumer has its partitions first:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.kafka.KafkaComponent;
import org.apache.camel.component.kafka.KafkaConstants;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.ConsumerGroupDescription;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.GroupState;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class ConsumersCount {
static String brokers;
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
EmbeddedKafkaBroker broker = startBroker();
brokers = broker.getBrokersAsString();
try (Admin admin = Admin.create(Map.of(
AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, brokers))) {
// one topic per run, so that each run reads only its own 300 records
admin.createTopics(List.of(new NewTopic("clicks-1", 3, (short) 1),
new NewTopic("clicks-3", 3, (short) 1),
new NewTopic("clicks-4", 3, (short) 1))).all().get();
}
for (int consumers : new int[] {1, 3, 4}) {
run(consumers);
}
broker.destroy();
}
static void run(int consumers) throws Exception {
Map<String, Set<Integer>> partitionsByThread = new ConcurrentHashMap<>();
CamelContext context = context();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("kafka:clicks-" + consumers + "?groupId=counter-" + consumers
+ "&autoOffsetReset=earliest&consumersCount=" + consumers)
.routeId("counter")
.process(e -> partitionsByThread.computeIfAbsent(
Thread.currentThread().getName(),
t -> ConcurrentHashMap.newKeySet())
.add(e.getMessage().getHeader(KafkaConstants.PARTITION,
Integer.class)));
}
});
NotifyBuilder all = new NotifyBuilder(context).fromRoute("counter")
.whenDone(300).create();
context.start();
waitForGroup("counter-" + consumers, consumers);
// records are sent only once every consumer has its partitions
ProducerTemplate template = context.createProducerTemplate();
for (int i = 0; i < 300; i++) {
template.sendBodyAndHeader("kafka:clicks-" + consumers, "click " + i,
KafkaConstants.PARTITION_KEY, i % 3);
}
all.matches(30, TimeUnit.SECONDS);
context.close();
List<String> perThread = partitionsByThread.values().stream()
.map(partitions -> new TreeSet<>(partitions).toString()).sorted().toList();
System.out.println("consumersCount=" + consumers + ": " + perThread.size()
+ " thread(s) received records, partitions per thread " + perThread);
}
static void waitForGroup(String group, int members) throws Exception {
try (Admin admin = Admin.create(Map.of(
AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, brokers))) {
while (true) {
ConsumerGroupDescription description = admin
.describeConsumerGroups(List.of(group)).all().get().get(group);
if (description.groupState() == GroupState.STABLE
&& description.members().size() == members) {
return;
}
Thread.sleep(100);
}
}
}
static CamelContext context() {
CamelContext context = new DefaultCamelContext();
context.getComponent("kafka", KafkaComponent.class).getConfiguration()
.setBrokers(brokers);
return context;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream())); // storage format log
try {
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
consumersCount=1: 1 thread(s) received records, partitions per thread [[0, 1, 2]]
consumersCount=3: 3 thread(s) received records, partitions per thread [[0], [1], [2]]
consumersCount=4: 3 thread(s) received records, partitions per thread [[0], [1], [2]]
- With
, one thread read all three partitions.consumersCount=1 - With 3, each thread got one partition. Records within a partition were still processed in order, by a single thread.
- With 4, still only three threads received records. The fourth consumer joined the group and got no partition, so it stayed idle.
The partition count is the upper limit on useful consumers in a group, across all application instances together: two instances with consumersCount=3Admin.describeConsumerGroups
Configuration in Spring Boot and real clusters
With camel-kafka-startercamel.component.kafka
camel.component.kafka.brokers=kafka-1:9092,kafka-2:9092,kafka-3:9092
camel.component.kafka.group-id=billing
camel.component.kafka.auto-offset-reset=earliest
camel.component.kafka.consumers-count=3
camel.component.kafka.break-on-first-error=false
camel.component.kafka.allow-manual-commit=false
camel.component.kafka.auto-commit-enable=true
Endpoint options in the URI override the component settings, so one route can use a different group or offset policy. A real cluster also needs security settings, such as securityProtocolsaslMechanismsaslJaasConfigsslTruststoreLocationadditionalPropertiesadditionalProperties.max.partition.fetch.bytes=2097152camel.component.kafka.additional-properties[max.partition.fetch.bytes]=2097152application.properties
The brokers
Choosing consumer and producer settings
| Situation | Settings |
|---|---|
| A new consumer group that must see existing records | autoOffsetReset=earliest |
| Related records that must stay in order | The same CamelKafkaKey |
| Headers read by programs that are not Camel | String header values, and removeHeaders() |
| Records that fail now and then | Redelivery, then a dead letter channel to a .DLT |
| Every record must be processed before its offset is committed | autoCommitEnable=falseallowManualCommit=true |
| Stop the partition on failure | breakOnFirstError=true |
| More throughput from one instance | consumersCount |
| Many records per exchange, such as bulk inserts | batching=truemaxPollRecordsList |
| Confirm where a record was written | recordMetadata=true |
The traps to remember are the latestbreakOnFirstError