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
A @KafkaListener
- A consumer thread: each container runs one
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.KafkaConsumer - Concurrency: a
withConcurrentMessageListenerContainer starts three child containers, so three consumers in the same group share the partitions.concurrency = "3" - Offset commits: after the method returns, the container commits offsets according to its
. Spring disables Kafka's own timer-based auto-commit, so an offset is committed only for records that were processed.AckMode - Conversion and errors: the container turns records into method arguments, and hands exceptions to an error handler, covered on the
error handling page.
| AckMode | When the offset is committed | Best for |
|---|---|---|
BATCH | After all records returned by one poll have been processed | Most listeners |
RECORD | After each record | Slow listeners where re-processing a batch is expensive |
TIMECOUNTCOUNT_TIME | After a time, a number of records, or whichever comes first | High throughput with fewer commits |
MANUAL | When your code calls acknowledge() | Listeners that hand records on asynchronously |
MANUAL_IMMEDIATE | Immediately 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-kafkaEmbeddedKafkaKraftBrokerspring-kafka-teststartBrokerspring.kafka.bootstrap-servers
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:
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);
}
}
}
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
listener received just theplain value. It ran on the threadString : the listener id, the child container index 0, and the consumer thread.plain-0-C-1 - The
listener took the key, partition and offset fromheaders 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.@Header - The
listener received the wholerecords , which also carries the timestamp, its type and the headers.ConsumerRecord - The plain listener has no
, so it usedgroupId , herespring.kafka.consumer.group-id . Without that property or agreeters , the listener'sgroupId is used as the group.id
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-resetearliest
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:
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);
}
}
}
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]
started three consumers in theconcurrency = "3" group, on threadsbilling tobilling-0-C-1 . Each received one partition, and together they covered partitions 0, 1 and 2.billing-2-C-1- The
group has a single consumer, which read all three partitions.audit - 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"spring.kafka.listener.concurrency
Manual acknowledgment and committed offsets
The committed offset is what makes a consumer resume where it left off after a restart. With AckMode.MANUAL_IMMEDIATEacknowledge()Admin
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);
}
}
}
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 Acknowledgmentnack(Duration)
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
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);
}
}
}
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
made the method receive abatch = "true" . The ten records arrived as batches of 4, 4 and 2, the limits set byList .max.poll.records kept the container stopped untilautoStartup = "false" started it through themain , after all ten records were written. Otherwise the first poll might have returned only the first record or two.KafkaListenerEndpointRegistry- With the default
ack mode, the offsets of each list are committed after the method returns.BATCH
A batch is not a fixed size: a poll returns what is available, up to max.poll.recordsmax.poll.interval.msBatchListenerFailedException
Typed payloads with a message converter
A listener can take a record type instead of a StringRecordMessageConverterStringJacksonJsonMessageConverter
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);
}
}
}
[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
record. The converter read the target type from the method parameter, so the producer needed no type header.OrderPlaced - Order o-2 had an extra
field thatcoupon does not declare. The converter ignored it rather than failing, which lets producers add fields without breaking consumers.OrderPlaced
The alternative is to deserialize in the Kafka consumer itself, with JacksonJsonDeserializerspring.kafka.consumer.value-deserializerErrorHandlingDeserializer
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
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);
}
}
}
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
group used the defaultwelcome-mail , 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.latest - The
group setanalytics through the annotation'sauto.offset.reset=earliest attribute, and read all four signups.properties , fromContainerTestUtils.waitForAssignment , waited until each consumer owned its partition before the fourth send. Without that wait, dee could also be missed by thespring-kafka-test group.latest
The setting matters only when the group has no committed offset: the first deployment of a new service, a renamed groupIdoffsets.retention.minutesearliestlatestspring.kafka.consumer.auto-offset-reset=earliest
Choosing listener settings
| Need | Setting |
|---|---|
| Process a topic faster | More partitions, and concurrency |
| Give another service its own copy of every record | A different groupId |
| Bulk database writes | batch = "true"max.poll.records |
| Commit only after work handed to another thread is done | AckMode.MANUALMANUAL_IMMEDIATEAcknowledgment |
| Objects instead of strings | A RecordMessageConverterErrorHandlingDeserializer |
| A new service that must see existing records | auto-offset-reset=earliest |
| Start a listener later, or pause it | autoStartup = "false"KafkaListenerEndpointRegistry |
| Safe re-processing after a crash | Idempotent processing, because delivery is at least once |
A listener that throws needs an error strategy, explained on