Sub topic 7
Consuming messages with @KafkaListener
This chapter assumes you have read the earlier chapters on consumer groups, the Spring Boot Kafka setup and JSON serialization. You should already have a running broker and an orders topic carrying OrderEvent JSON.
What @KafkaListener does
@KafkaListener marks a method as a message consumer. At startup, Spring Kafka finds each annotated method and builds a listener container for it. The container is a managed object that owns one or more Kafka consumers and runs the poll loop on its own threads. You write the business logic, and the container handles polling, deserializing, calling your method and committing offsets.
Spring Boot enables this automatically when spring-kafka is on the classpath, so you do not need @EnableKafka.
package com.example.orders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class OrderListener {
private static final Logger log = LoggerFactory.getLogger(OrderListener.class);
@KafkaListener(topics = "orders", groupId = "order-service")
public void onOrder(OrderEvent event) {
log.info("Received order {} for {} cents", event.orderId(), event.amountCents());
}
}The class must be a Spring bean, because Spring scans bean methods for the annotation. A plain object you create with new is never registered.
The poll loop behind your method
The listener method does not poll. The container does, and it calls your method on the container thread.
Three consequences follow from this model:
- Records from one partition reach your method in offset order. That ordering holds only within a partition.
- While your method runs, the thread is not polling. If processing takes longer than
max.poll.interval.ms(five minutes by default), the broker assumes the consumer is dead and triggers a rebalance. - Throwing an exception does not stop the container. It hands the failure to the error handler, which a later chapter covers.
Topics, groups and ids
The annotation has several attributes that control where records come from.
| Attribute | Purpose |
|---|---|
| `topics` | One or more topic names. |
| `topicPattern` | A regular expression, for example `orders\\..*`. |
| `topicPartitions` | Fixed partitions, which bypasses group assignment. |
| `groupId` | Overrides `spring.kafka.consumer.group-id` for this listener. |
| `id` | A name for the container, used to look it up at runtime. |
| `autoStartup` | Set to `"false"` to create the container without starting it. |
| `concurrency` | Number of consumer threads for this listener. |
Two behaviors cause most surprises.
First, if you set id but not groupId, Spring uses the id as the consumer group. Set idIsGroup = false or give an explicit groupId to avoid an accidental new group, which would re-read the topic from the start.
Second, two listeners in the same group split the partitions between them, so each record goes to only one of them. Listeners in different groups each receive every record. Use different groups for independent consumers such as an order service and an audit service.
@KafkaListener(id = "order-audit-listener", topics = "orders", groupId = "order-audit")
public void audit(OrderEvent event) {
// Receives every order, independently of order-service.
}Method parameters
Spring resolves arguments by type and annotation. You choose how much of the record you want to see.
| Parameter | What you get |
|---|---|
| `OrderEvent event` | The deserialized value only. |
| `ConsumerRecord<String, OrderEvent> record` | The full record: key, value, topic, partition, offset, timestamp, headers. |
| `@Payload OrderEvent event` | The value, stated explicitly. Useful when mixing with `@Header`. |
| `@Header(KafkaHeaders.RECEIVED_KEY) String key` | The record key. |
| `@Header(KafkaHeaders.RECEIVED_PARTITION) int partition` | The partition number. |
| `@Header(KafkaHeaders.OFFSET) long offset` | The record's offset. |
| `Acknowledgment ack` | A handle for manual commits, covered in the offset chapter. |
Use ConsumerRecord when you need several metadata fields at once. Use @Header when you need one or two.
package com.example.orders;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
@Component
public class OrderMetadataListener {
private static final Logger log = LoggerFactory.getLogger(OrderMetadataListener.class);
@KafkaListener(id = "order-meta-listener", topics = "orders", groupId = "order-meta")
public void withHeaders(@Payload OrderEvent event,
@Header(KafkaHeaders.RECEIVED_KEY) String key,
@Header(KafkaHeaders.RECEIVED_PARTITION) int partition,
@Header(KafkaHeaders.OFFSET) long offset) {
log.info("key={} partition={} offset={} amount={}",
key, partition, offset, event.amountCents());
}
@KafkaListener(id = "order-record-listener", topics = "orders", groupId = "order-record")
public void withRecord(ConsumerRecord<String, OrderEvent> record) {
log.info("topic={} timestamp={} value={}",
record.topic(), record.timestamp(), record.value());
}
}Deserialization happens before your method
The container deserializes each record before calling your method, using the deserializers from your configuration. Your parameter type must match what the deserializer produces. With the JsonDeserializer configured earlier, spring.json.value.default.type tells it to build OrderEvent objects, and spring.json.trusted.packages restricts which classes it may instantiate.
Batch listeners
By default the container calls your method once per record. A batch listener receives everything returned by one poll() in a single call. This suits bulk database inserts.
Set the listener type globally in application.yml:
spring:
kafka:
listener:
type: batch
consumer:
max-poll-records: 100Then declare a list parameter:
package com.example.orders;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class OrderBatchListener {
private static final Logger log = LoggerFactory.getLogger(OrderBatchListener.class);
@KafkaListener(id = "order-batch-listener", topics = "orders", groupId = "order-batch")
public void onBatch(List<OrderEvent> events) {
log.info("Received a batch of {} orders", events.size());
}
}max-poll-records caps the batch size. Because type: batch is global in this configuration, every listener in the application must accept lists. If you mix styles, set batch = "true" on the individual annotation and use a container factory that supports it.
Starting and stopping listeners at runtime
Giving a listener an id lets you control its container through KafkaListenerEndpointRegistry. This is useful for pausing consumption during maintenance or while a downstream system is unavailable.
package com.example.orders;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.listener.MessageListenerContainer;
import org.springframework.stereotype.Service;
@Service
public class ListenerControl {
private final KafkaListenerEndpointRegistry registry;
public ListenerControl(KafkaListenerEndpointRegistry registry) {
this.registry = registry;
}
public void pauseOrders() {
MessageListenerContainer container = registry.getListenerContainer("order-audit-listener");
if (container != null) {
container.pause();
}
}
public void resumeOrders() {
MessageListenerContainer container = registry.getListenerContainer("order-audit-listener");
if (container != null) {
container.resume();
}
}
}A paused container keeps polling, so it stays in the group and does not trigger a rebalance, but it fetches no new records. stop() leaves the group and does cause a rebalance. Prefer pause() for short interruptions.
Common errors
- Nothing is consumed. Check the group id first. A new group with
auto-offset-reset: latestignores records already in the topic. Next, check that the listener class is a bean and that the topic name matches. - Records processed twice after a delay. The method exceeded
max.poll.interval.ms, the group rebalanced, and another consumer re-read the uncommitted records. Reducemax-poll-recordsor move slow work off the container thread. - Some partitions never receive traffic. A consumer group has at most one active consumer per partition. Running more consumers than partitions leaves the extras idle.
ClassNotFoundExceptionor "not in the trusted packages". The producer's type header names a class the consumer does not trust or does not have. Setspring.json.value.default.typeandspring.json.trusted.packagesas in the setup chapter.- Slow listeners block each other. All listener methods in one container share its thread. Separate containers, or higher concurrency, give you parallelism. That is the subject of the next chapter.
Exercise
Two @KafkaListener methods consume the same topic. The first uses groupId = "billing". The second uses groupId = "billing" as well. The topic has four partitions and each listener has concurrency 1. What does each listener see, and how does that change if the second listener's groupId becomes "audit"?
Show answer
With the same group "billing", the four partitions are divided between the two consumers, so each listener receives only the records from its own partitions (typically two each), and each record reaches exactly one of them. With groupId "audit" on the second listener, the groups are independent: both listeners receive every record on all four partitions.
Exercise
A listener method calls a slow external API and sometimes takes six minutes per poll batch. Records are processed repeatedly, and the logs show frequent rebalances. Why does this happen, and name two changes that would fix it.
Show answer
The container thread does not call poll() while the method runs, so after max.poll.interval.ms (default five minutes) the broker treats the consumer as failed, removes it from the group and reassigns its partitions. The uncommitted records are then redelivered. Fixes: lower max-poll-records so each batch finishes sooner, raise max.poll.interval.ms, or move the slow work off the container thread.