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

The Kafka component, in camel-kafka, connects routes to Apache Kafka topics. The endpoint URI is kafka:topicName?options. In to() it is a producer that turns each message into a Kafka record; in from() it is a consumer that turns each record into an exchange. Underneath, it uses the plain Kafka Java client: Camel 4.23 ships with kafka-clients 4.2.

The consumer side works like this:

  1. The route starts consumersCount threads (1 by default). Each one creates its own KafkaConsumer, joins the consumer group named by groupId, and receives some of the topic's partitions.
  2. Each thread calls poll() in a loop, gets up to maxPollRecords records (500 by default), and runs the route once per record, in offset order.
  3. Offsets are committed by the Kafka client every 5 seconds by default (autoCommitEnable=true, autoCommitIntervalMs=5000), or by the route itself with manual commits.
  4. If the route fails for a record, breakOnFirstError decides whether the thread moves on to the next record or goes back and tries again.

The producer side is simpler: the body becomes the record value, the CamelKafkaKey header becomes the key, other headers become Kafka record headers, and the producer sends asynchronously, continuing the route when the broker acknowledges. Camel's defaults match Kafka's safe defaults: requestRequiredAcks=all and enableIdempotence=true.

Headers set and read by the Kafka component
HeaderDirectionMeaning
CamelKafkaKeyBothThe record key
CamelKafkaPartitionKeyProducerAn explicit partition number
CamelKafkaOverrideTopicProducerSend to this topic instead of the endpoint's
CamelKafkaTopic, CamelKafkaPartition, CamelKafkaOffsetConsumerWhere the record came from
CamelKafkaTimestampConsumerThe record timestamp
CamelKafkaManualCommitConsumerThe commit handle, with allowManualCommit=true
CamelKafkaRecordMetaProducerPartition and offset of sent records, with recordMetadata=true

Older Camel releases used other names for these headers, such as kafka.KEY. Refer to them through the KafkaConstants class rather than as string literals, so that code keeps working across upgrades.

Every program on this page starts its own single-node Kafka 4.2 broker in KRaft mode, inside the same JVM, with EmbeddedKafkaKraftBroker from spring-kafka-test. That is only the test harness: the routes use plain camel-kafka and would run unchanged against a real cluster, which has three or more brokers and topics with three replicas. The programs turn logging off and create their topics with the Kafka Admin client, so the partition counts are fixed.

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:

Java
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);
        }
    }
}
Output
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 recordMetadata=true, the producer put the broker's answer in the CamelKafkaRecordMeta header. orders-0@0 means topic orders, partition 0, offset 0.
  • The consumer received each record as a String, because the default deserializers are StringDeserializer for both key and value. Use valueDeserializer for other types.
  • 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 CamelKafkaKey was null.
  • The program set the broker list once, on the component configuration, so the endpoints need only the topic and the consumer options.

autoOffsetReset=earliest matters here. The consumer group billing had no committed offset, and the default, latest, starts at the end of the partition. A new group with the default would see only records sent after it joined; in this program, depending on timing, that could be none of them.

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:

Java
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);
        }
    }
}
Output
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 c2's payments went to partition 1, and c1, c3 and c4 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.
  • 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 source arrived as a byte[], the bytes of web, not as a String. Kafka headers are byte arrays, and the default header deserializer does not convert them back. getHeader("source", String.class) or a custom headerDeserializer does.
  • The header attempt was the Integer 1, so the producer wrote four bytes, [0, 0, 0, 1]. Read as a String, that is unprintable control characters; read as an int, it is 1. Send header values as strings when other programs will read them.
  • CamelFileName did not arrive: headers starting with Camel are filtered out on the way in and out.

As with HTTP, every other message header becomes a Kafka header, including ones left by earlier steps of the route. Use removeHeaders() before to("kafka:...") when the route carries headers that other consumers should not see.

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:

Java
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);
        }
    }
}
Output
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 bad, the error handler logged it, and the consumer went on to ok-2. After a restart with the same group id, nothing came back, because the committed offset had moved past bad. The failed order was lost, and only a log line recorded it.
  • Dead letter channel: errorHandler(deadLetterChannel("kafka:orders.DLT")) sent the failed exchange to another topic, and the program read bad back from orders.DLT. The consumer then went on to ok-2. Nothing was lost, and the failed record can be inspected or replayed later.
  • breakOnFirstError=true: after bad 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 processed ok-1 a second time before failing on bad again. It would keep doing so; the program stopped after four exchanges.

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=true only together with retries that eventually give up, such as an onException with maximumRedeliveries followed by a dead letter channel, and with processing that is safe to repeat. The Camel error handling page covers redelivery and dead letter channels in general.

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:

Java
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);
        }
    }
}
Output
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
  • allowManualCommit=true put a KafkaManualCommit in the CamelKafkaManualCommit header of each exchange, and autoCommitEnable=false stopped the client from committing on its own.
  • 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 invoice-3 and invoice-4 again: everything after the last commit is redelivered.

The default commit factory commits synchronously, waiting for the broker; DefaultKafkaManualAsyncCommitFactory commits in the background, which is faster but can lose the last commits on a crash. Committing after each record is slow at high volume, so many routes commit only the last record of each poll, which the CamelKafkaLastPollRecord header marks. Either way, delivery is at least once, so the route must cope with seeing a record twice, for example with the idempotent repository on the Camel JDBC page.

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:

Java
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);
        }
    }
}
Output
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 consumersCount=1, one thread read all three partitions.
  • 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=3 on a three-partition topic leave three consumers idle. The program waits for the group with Admin.describeConsumerGroups because, without that, the first consumer to join can read every record before the others are assigned anything, which is what happens in a real deployment at startup too. To process one partition's records in parallel, hand them to a thread pool inside the route, at the cost of their order.

Configuration in Spring Boot and real clusters

With camel-kafka-starter in a Spring Boot application, the component options become properties under camel.component.kafka. This configuration was not run here; the property names and defaults come from the starter's configuration metadata for Camel 4.23:

Properties
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 securityProtocol, saslMechanism and saslJaasConfig for SASL, or sslTruststoreLocation for TLS, which this page does not run. Kafka client properties that Camel has no option for go in additionalProperties: additionalProperties.max.partition.fetch.bytes=2097152 in an endpoint URI, or camel.component.kafka.additional-properties[max.partition.fetch.bytes]=2097152 in application.properties.

The brokers list needs only some of the brokers: the client asks them for the rest of the cluster. List more than one, so that the application can still start when one broker is down. The Spring KafkaTemplate and Spring Kafka listener pages show the same producer and consumer ideas with Spring for Apache Kafka instead of Camel.

Choosing consumer and producer settings

Common situations and the settings that fit them
SituationSettings
A new consumer group that must see existing recordsautoOffsetReset=earliest
Related records that must stay in orderThe same CamelKafkaKey for all of them
Headers read by programs that are not CamelString header values, and removeHeaders() for the rest
Records that fail now and thenRedelivery, then a dead letter channel to a .DLT topic
Every record must be processed before its offset is committedautoCommitEnable=false, allowManualCommit=true, and an idempotent route
Stop the partition on failurebreakOnFirstError=true, with retries that end
More throughput from one instanceconsumersCount up to the number of partitions
Many records per exchange, such as bulk insertsbatching=true, which puts up to maxPollRecords records in one List body
Confirm where a record was writtenrecordMetadata=true

The traps to remember are the latest default for new groups, header values that arrive as bytes, failed records that the default settings silently skip, and breakOnFirstError processing earlier records twice. Kafka itself runs only in KRaft mode since 4.0, without ZooKeeper, so old options and guides that mention a ZooKeeper address no longer apply.