Spring Kafka: consuming messages with @KafkaListener

A @KafkaListener method looks like a simple callback, but behind it a listener container runs a Kafka consumer, takes part in a consumer group and commits offsets. This page explains that machinery, then runs each important listener feature against a real Kafka broker inside the program, including the offset settings that silently skip messages.

Contents

What runs behind a @KafkaListener

A Kafka consumer reads records by polling: it asks the brokers for new records in the partitions it owns, processes them, and records how far it got by committing an offset. Consumers that share a group.id form a consumer group. Kafka gives each partition of a topic to exactly one consumer of the group, so the group shares the work, and two different groups each read every record.

A @KafkaListener method hides the poll loop. Spring for Apache Kafka builds a listener container for it, and the container does the rest:

  • A consumer thread: each container runs one KafkaConsumer on its own thread, because a Kafka consumer must not be used by two threads at once. The thread polls, then calls your method for each record.
  • Concurrency: a ConcurrentMessageListenerContainer with concurrency = "3" starts three child containers, so three consumers in the same group share the partitions.
  • Offset commits: after the method returns, the container commits offsets according to its AckMode. Spring disables Kafka's own timer-based auto-commit, so an offset is committed only for records that were processed.
  • Conversion and errors: the container turns records into method arguments, and hands exceptions to an error handler, covered on the error handling page.
Acknowledgment modes of the listener container
AckModeWhen the offset is committedBest for
BATCH (default)After all records returned by one poll have been processedMost listeners
RECORDAfter each recordSlow listeners where re-processing a batch is expensive
TIME, COUNT, COUNT_TIMEAfter a time, a number of records, or whichever comes firstHigh throughput with fewer commits
MANUALWhen your code calls acknowledge(), committed with the next batchListeners that hand records on asynchronously
MANUAL_IMMEDIATEImmediately when your code calls acknowledge()Precise control over what counts as done

Every example is a Spring Boot 4.1 application with spring-boot-starter-kafka (Spring for Apache Kafka 4.1, Kafka client 4.2). Each starts a one-node Kafka broker inside the JVM with EmbeddedKafkaKraftBroker from spring-kafka-test, in the startBroker method at the end of the program, and points spring.kafka.bootstrap-servers at it. Producing is explained on the KafkaTemplate page.

A first listener: value, headers or the whole record

A listener method can ask for as little or as much of the record as it needs. Three listeners read the same topic here, each in its own consumer group, so each receives all three greetings. The keys were chosen so that the records fall into both of the topic's two partitions:

Java
package demo.kafka.basic;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class BasicListener {

    static final CountDownLatch DONE = new CountDownLatch(9);
    // each listener collects its lines, printed together at the end
    static final Map<String, List<String>> LINES = new ConcurrentHashMap<>();

    static void log(String listener, String line) {
        LINES.computeIfAbsent(listener, k -> new CopyOnWriteArrayList<>()).add(line);
        DONE.countDown();
    }

    @Bean
    NewTopic greetings() {
        return TopicBuilder.name("greetings").partitions(2).replicas(1).build();
    }

    @Component
    static class Listeners {
        // the simplest form: only the value
        @KafkaListener(id = "plain", topics = "greetings")
        void plain(String value) {
            log("plain", value + " on thread " + Thread.currentThread().getName());
        }

        // metadata as method parameters, with a different consumer group
        @KafkaListener(id = "headers", topics = "greetings", groupId = "header-readers")
        void withHeaders(@Payload String value,
                         @Header(KafkaHeaders.RECEIVED_KEY) String key,
                         @Header(KafkaHeaders.RECEIVED_PARTITION) int partition,
                         @Header(KafkaHeaders.OFFSET) long offset) {
            log("headers", "key " + key + ", partition " + partition + ", offset " + offset
                    + ": " + value);
        }
    }

    // the whole record, in a third consumer group
    @Component
    static class RecordListener {
        @KafkaListener(id = "records", topics = "greetings", groupId = "record-readers")
        void onRecord(ConsumerRecord<String, String> record) {
            log("records", record.topic() + "-" + record.partition() + "@" + record.offset()
                    + ", key " + record.key() + ", timestamp type " + record.timestampType());
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(BasicListener.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.group-id", "greeters",
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "ERROR"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            // keys chosen so that the records land in both partitions
            template.send("greetings", "anna", "hello").get();
            template.send("greetings", "carl", "hola").get();
            template.send("greetings", "anna", "ciao").get();
            System.out.println("all received: " + DONE.await(30, TimeUnit.SECONDS));
            for (String listener : List.of("plain", "headers", "records")) {
                System.out.println("[" + listener + "]");
                LINES.get(listener).stream().sorted()
                        .forEach(line -> System.out.println("  " + line));
            }
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
all received: true
[plain]
  ciao on thread plain-0-C-1
  hello on thread plain-0-C-1
  hola on thread plain-0-C-1
[headers]
  key anna, partition 1, offset 0: hello
  key anna, partition 1, offset 1: ciao
  key carl, partition 0, offset 0: hola
[records]
  greetings-0@0, key carl, timestamp type CreateTime
  greetings-1@0, key anna, timestamp type CreateTime
  greetings-1@1, key anna, timestamp type CreateTime
  • The plain listener received just the String value. It ran on the thread plain-0-C-1: the listener id, the child container index 0, and the consumer thread.
  • The headers listener took the key, partition and offset from @Header parameters. anna's two records are in partition 1 at offsets 0 and 1, and carl's record is in partition 0 at offset 0.
  • The records listener received the whole ConsumerRecord, which also carries the timestamp, its type and the headers.
  • The plain listener has no groupId, so it used spring.kafka.consumer.group-id, here greeters. Without that property or a groupId, the listener's id is used as the group.

Each listener collected its lines and the program prints them sorted, because a consumer reads its two partitions in no fixed order relative to each other. Within one partition, records always arrive in offset order. The auto-offset-reset property is set to earliest so that records sent before the consumers joined are still read; the last section shows what happens without it.

Consumer groups and concurrency

To process a topic faster, add consumers to the group; to give another service its own copy of the data, use another group. This program runs both at once against a topic with three partitions and six records, two per partition:

Java
package demo.kafka.groups;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class ConsumerGroups {

    static final CountDownLatch DONE = new CountDownLatch(12);
    // group -> thread -> partitions that thread received records from
    static final Map<String, Map<String, TreeSet<Integer>>> SEEN = new ConcurrentHashMap<>();

    @Bean
    NewTopic orders() {
        return TopicBuilder.name("orders").partitions(3).replicas(1).build();
    }

    static void record(String group, ConsumerRecord<String, String> r) {
        SEEN.computeIfAbsent(group, g -> new ConcurrentHashMap<>())
                .computeIfAbsent(Thread.currentThread().getName(), t -> new TreeSet<>())
                .add(r.partition());
        DONE.countDown();
    }

    @Component
    static class Billing {
        // three consumers in one group: the partitions are shared out between them
        @KafkaListener(id = "billing", topics = "orders", groupId = "billing", concurrency = "3")
        void on(ConsumerRecord<String, String> r) {
            record("billing", r);
        }
    }

    @Component
    static class Audit {
        // a separate group with one consumer: it gets every record of every partition
        @KafkaListener(id = "audit", topics = "orders", groupId = "audit")
        void on(ConsumerRecord<String, String> r) {
            record("audit", r);
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(ConsumerGroups.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "ERROR"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            for (int i = 0; i < 6; i++) {
                template.send("orders", i % 3, "k" + i, "order " + i).get(); // 2 per partition
            }
            System.out.println("all 12 deliveries done: " + DONE.await(60, TimeUnit.SECONDS));
            for (String group : new String[] {"billing", "audit"}) {
                Map<String, TreeSet<Integer>> byThread = new TreeMap<>(SEEN.get(group));
                TreeSet<Integer> all = new TreeSet<>();
                byThread.values().forEach(all::addAll);
                System.out.println("group " + group + ": threads " + byThread.keySet()
                        + ", partitions per thread " + byThread.values().stream()
                                .map(TreeSet::size).toList()
                        + ", partitions covered " + all);
            }
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
all 12 deliveries done: true
group billing: threads [billing-0-C-1, billing-1-C-1, billing-2-C-1], partitions per thread [1, 1, 1], partitions covered [0, 1, 2]
group audit: threads [audit-0-C-1], partitions per thread [3], partitions covered [0, 1, 2]
  • concurrency = "3" started three consumers in the billing group, on threads billing-0-C-1 to billing-2-C-1. Each received one partition, and together they covered partitions 0, 1 and 2.
  • The audit group has a single consumer, which read all three partitions.
  • Both groups received all six records, 12 deliveries in all: groups are independent, and each keeps its own committed offsets.

Which billing thread got which partition varies from run to run, so the program prints only the counts. Concurrency is limited by the partition count: with concurrency = "5" on this topic, two consumers would sit idle. Records with the same key always go to the same partition, so they are always processed by one thread at a time and in order, which is why the key matters as much on the consumer side as on the producer side. Boot's spring.kafka.listener.concurrency sets a default for all listeners.

Manual acknowledgment and committed offsets

The committed offset is what makes a consumer resume where it left off after a restart. With AckMode.MANUAL_IMMEDIATE, the offset moves only when the listener calls acknowledge(). This job listener acknowledges the first three jobs, then stops acknowledging, as if it crashed. The program then stops the container, reads the group's committed offset with the Kafka Admin client, and starts the container again:

Java
package demo.kafka.manualack;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaAdmin;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class ManualAck {

    static volatile boolean crashAfterThree = true;
    static volatile CountDownLatch received = new CountDownLatch(5);

    @Bean
    NewTopic jobs() {
        return TopicBuilder.name("jobs").partitions(1).replicas(1).build();
    }

    @Component
    static class JobListener {
        @KafkaListener(id = "jobs", topics = "jobs", groupId = "workers")
        void on(ConsumerRecord<String, String> record, Acknowledgment ack) {
            boolean acked = !(crashAfterThree && record.offset() >= 3);
            System.out.println("  offset " + record.offset() + " " + record.value()
                    + (acked ? ", acknowledged" : ", NOT acknowledged"));
            if (acked) {
                ack.acknowledge();
            }
            received.countDown();
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(ManualAck.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.kafka.listener.ack-mode", "manual_immediate",
                "spring.main.banner-mode", "off", "logging.level.root", "ERROR"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            KafkaListenerEndpointRegistry registry =
                    context.getBean(KafkaListenerEndpointRegistry.class);

            System.out.println("First run: the listener stops acknowledging after offset 2");
            for (int i = 0; i < 5; i++) {
                template.send("jobs", "job " + i).get();
            }
            received.await(30, TimeUnit.SECONDS);
            registry.getListenerContainer("jobs").stop(); // like a crash or a redeploy
            System.out.println("Committed offset for group workers: "
                    + committed(context.getBean(KafkaAdmin.class)));

            System.out.println("Second run: the container starts from the committed offset");
            crashAfterThree = false;
            received = new CountDownLatch(2);
            registry.getListenerContainer("jobs").start();
            received.await(30, TimeUnit.SECONDS);
            Thread.sleep(500);
            System.out.println("Committed offset for group workers: "
                    + committed(context.getBean(KafkaAdmin.class)));
        } finally {
            broker.destroy();
        }
    }

    static long committed(KafkaAdmin kafkaAdmin) throws Exception {
        try (Admin admin = Admin.create(kafkaAdmin.getConfigurationProperties())) {
            Map<TopicPartition, OffsetAndMetadata> offsets = admin
                    .listConsumerGroupOffsets("workers").partitionsToOffsetAndMetadata().get();
            return offsets.get(new TopicPartition("jobs", 0)).offset();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
First run: the listener stops acknowledging after offset 2
  offset 0 job 0, acknowledged
  offset 1 job 1, acknowledged
  offset 2 job 2, acknowledged
  offset 3 job 3, NOT acknowledged
  offset 4 job 4, NOT acknowledged
Committed offset for group workers: 3
Second run: the container starts from the committed offset
  offset 3 job 3, acknowledged
  offset 4 job 4, acknowledged
Committed offset for group workers: 5
  • Offsets 0, 1 and 2 were acknowledged, so the committed offset is 3. A committed offset is the position of the next record to read, not the last one processed.
  • Offsets 3 and 4 were delivered but not acknowledged. When the container started again, it resumed at the committed offset and received jobs 3 and 4 a second time.
  • After they were acknowledged, the committed offset became 5, the end of the partition.

This is Kafka's at-least-once delivery: after a failure, records since the last commit are delivered again, so listeners must tolerate duplicates, for example by storing a processed id or by using idempotent writes. The Acknowledgment also has nack(Duration), which re-delivers from the current record after a pause.

Batch listeners

Inserting records into a database one at a time is slow; a batch listener receives everything one poll returned, as a list. Here ten sensor readings are already in the topic when the listener starts, and max.poll.records is set to 4:

Java
package demo.kafka.batch;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class BatchListener {

    static final CountDownLatch DONE = new CountDownLatch(10);

    @Bean
    NewTopic readings() {
        return TopicBuilder.name("readings").partitions(1).replicas(1).build();
    }

    @Component
    static class Readings {
        // autoStartup false: started by main once all 10 records are in the topic
        @KafkaListener(id = "readings", topics = "readings", groupId = "loader",
                batch = "true", autoStartup = "false")
        void onBatch(List<ConsumerRecord<String, String>> batch) {
            System.out.println("batch of " + batch.size() + ": offsets "
                    + batch.getFirst().offset() + ".." + batch.getLast().offset()
                    + " -> one INSERT with " + batch.size() + " rows");
            batch.forEach(r -> DONE.countDown());
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(BatchListener.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.kafka.consumer.max-poll-records", "4",
                "spring.main.banner-mode", "off", "logging.level.root", "ERROR"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            for (int i = 0; i < 10; i++) {
                template.send("readings", "sensor-1", "21." + i).get();
            }
            context.getBean(KafkaListenerEndpointRegistry.class)
                    .getListenerContainer("readings").start();
            System.out.println("all 10 processed: " + DONE.await(30, TimeUnit.SECONDS));
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
batch of 4: offsets 0..3 -> one INSERT with 4 rows
batch of 4: offsets 4..7 -> one INSERT with 4 rows
batch of 2: offsets 8..9 -> one INSERT with 2 rows
all 10 processed: true
  • batch = "true" made the method receive a List. The ten records arrived as batches of 4, 4 and 2, the limits set by max.poll.records.
  • autoStartup = "false" kept the container stopped until main started it through the KafkaListenerEndpointRegistry, after all ten records were written. Otherwise the first poll might have returned only the first record or two.
  • With the default BATCH ack mode, the offsets of each list are committed after the method returns.

A batch is not a fixed size: a poll returns what is available, up to max.poll.records, which defaults to 500. All records of one poll must also be processed within max.poll.interval.ms, five minutes by default, or the broker assumes the consumer is dead and gives its partitions to another member. If one record in a batch fails, the listener should throw BatchListenerFailedException with the index, so that the error handler knows which records succeeded.

Typed payloads with a message converter

A listener can take a record type instead of a String. With Spring Boot, the simplest way is a RecordMessageConverter bean, which Boot passes to its listener container factory. StringJacksonJsonMessageConverter converts the JSON text into the parameter type of each method:

Java
package demo.kafka.typed;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.converter.RecordMessageConverter;
import org.springframework.kafka.support.converter.StringJacksonJsonMessageConverter;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class TypedPayload {

    static final CountDownLatch DONE = new CountDownLatch(3);

    record OrderPlaced(String orderId, int totalCents) { }

    record OrderCancelled(String orderId, String reason) { }

    @Bean
    NewTopic orders() {
        return TopicBuilder.name("orders").partitions(1).replicas(1).build();
    }

    // Boot passes a RecordMessageConverter bean to its listener container factory
    @Bean
    RecordMessageConverter converter() {
        return new StringJacksonJsonMessageConverter();
    }

    @Component
    static class Totals {
        @KafkaListener(id = "totals", topics = "orders")
        void on(OrderPlaced order) {
            System.out.println("[totals] " + order.orderId() + " for "
                    + order.totalCents() / 100.0 + " EUR (" + order.getClass().getSimpleName()
                    + ")");
            DONE.countDown();
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(TypedPayload.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.group-id", "shop",
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "ERROR"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            template.send("orders", "o-1", "{\"orderId\":\"o-1\",\"totalCents\":2599}").get();
            template.send("orders", "o-2", "{\"orderId\":\"o-2\",\"totalCents\":1000,"
                    + "\"coupon\":\"SPRING\"}").get();
            template.send("orders", "o-3", "{\"orderId\":\"o-3\",\"totalCents\":450}").get();
            System.out.println("all converted: " + DONE.await(30, TimeUnit.SECONDS));
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
[totals] o-1 for 25.99 EUR (OrderPlaced)
[totals] o-2 for 10.0 EUR (OrderPlaced)
[totals] o-3 for 4.5 EUR (OrderPlaced)
all converted: true
  • Each JSON value became an OrderPlaced record. The converter read the target type from the method parameter, so the producer needed no type header.
  • Order o-2 had an extra coupon field that OrderPlaced does not declare. The converter ignored it rather than failing, which lets producers add fields without breaking consumers.

The alternative is to deserialize in the Kafka consumer itself, with JacksonJsonDeserializer as spring.kafka.consumer.value-deserializer. A value that cannot be deserialized then fails before your code runs, so it must be wrapped in ErrorHandlingDeserializer; the error handling page shows that poison-pill case. The converter approach keeps the consumer on plain strings or bytes, and turns conversion problems into ordinary listener exceptions.

Where a new group starts: auto.offset.reset

A consumer group that has never committed an offset needs a starting point, and Kafka's default, latest, means "only records that arrive from now on". In this program three users sign up before two listeners have ever run. Then both listeners start, and one more user signs up:

Java
package demo.kafka.reset;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.MessageListenerContainer;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.kafka.test.utils.ContainerTestUtils;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class OffsetReset {

    static final List<String> LATEST = new CopyOnWriteArrayList<>();
    static final List<String> EARLIEST = new CopyOnWriteArrayList<>();

    @Bean
    NewTopic signups() {
        return TopicBuilder.name("signups").partitions(1).replicas(1).build();
    }

    @Component
    static class Listeners {
        // no auto.offset.reset given: the Kafka default, latest
        @KafkaListener(id = "welcome-mail", topics = "signups", groupId = "welcome-mail",
                autoStartup = "false")
        void latest(String user) {
            LATEST.add(user);
        }

        @KafkaListener(id = "analytics", topics = "signups", groupId = "analytics",
                autoStartup = "false", properties = "auto.offset.reset=earliest")
        void earliest(String user) {
            EARLIEST.add(user);
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(OffsetReset.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.main.banner-mode", "off", "logging.level.root", "ERROR"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            System.out.println("3 users sign up before the listeners have ever run");
            for (String user : List.of("ann", "bob", "cid")) {
                template.send("signups", user).get();
            }

            KafkaListenerEndpointRegistry registry =
                    context.getBean(KafkaListenerEndpointRegistry.class);
            for (MessageListenerContainer container : registry.getListenerContainers()) {
                container.start();
                ContainerTestUtils.waitForAssignment(container, 1);
            }
            System.out.println("listeners started and assigned; 1 more user signs up");
            template.send("signups", "dee").get();
            Thread.sleep(2000);

            System.out.println("welcome-mail (latest)  : " + LATEST);
            System.out.println("analytics   (earliest): " + EARLIEST);
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
3 users sign up before the listeners have ever run
listeners started and assigned; 1 more user signs up
welcome-mail (latest)  : [dee]
analytics   (earliest): [ann, bob, cid, dee]
  • The welcome-mail group used the default latest, so it began at the end of the partition. It received only dee. ann, bob and cid never got a welcome mail, and nothing reported an error.
  • The analytics group set auto.offset.reset=earliest through the annotation's properties attribute, and read all four signups.
  • ContainerTestUtils.waitForAssignment, from spring-kafka-test, waited until each consumer owned its partition before the fourth send. Without that wait, dee could also be missed by the latest group.

The setting matters only when the group has no committed offset: the first deployment of a new service, a renamed groupId, or offsets that expired after offsets.retention.minutes, seven days by default. Choose it deliberately per listener: earliest for consumers that must see every record, latest for ones that only care about live data. Many teams set spring.kafka.consumer.auto-offset-reset=earliest globally for that reason.

Choosing listener settings

Common needs and the listener settings that fit them
NeedSetting
Process a topic fasterMore partitions, and concurrency up to the partition count
Give another service its own copy of every recordA different groupId
Bulk database writesbatch = "true" with a sensible max.poll.records
Commit only after work handed to another thread is doneAckMode.MANUAL or MANUAL_IMMEDIATE with Acknowledgment
Objects instead of stringsA RecordMessageConverter bean, or a JSON deserializer wrapped in ErrorHandlingDeserializer
A new service that must see existing recordsauto-offset-reset=earliest
Start a listener later, or pause itautoStartup = "false" and KafkaListenerEndpointRegistry
Safe re-processing after a crashIdempotent processing, because delivery is at least once

A listener that throws needs an error strategy, explained on Kafka error handling and retries and dead letter topics. To watch consumer lag and listener timing, see Kafka monitoring. For the latch used to wait for listeners in these programs, see CountDownLatch and CyclicBarrier.