Sub topic 7
Consuming messages with @KafkaListener
This chapter assumes you know how topics, partitions, offsets and consumer groups work, and that your Spring Boot application already has the spring.kafka.* configuration from the setup chapter. Here you will write a consumer, see how Spring turns records into Java objects, and learn the errors people hit most often.
What @KafkaListener does
@KafkaListener marks a method as a message handler. At startup, Spring for Apache Kafka finds each annotated method and builds a listener container for it. The container does the following:
- Creates a Kafka consumer with your configured group ID.
- Subscribes it to the topics you named.
- Runs a loop that polls the broker for records.
- Deserializes each record and calls your method.
- Commits offsets after your method returns.
You write only the handler. The polling loop and the offset commits are the container's job.
A basic listener
The listener below reads from the orders topic as part of the order-service group.
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, so @Component is required. If the annotated class is not a bean, the listener is never registered and you get no error.
The OrderEvent parameter works because of this configuration from the setup chapter:
spring:
kafka:
consumer:
group-id: order-service
auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
properties:
spring.json.trusted.packages: com.example.orders
spring.json.value.default.type: com.example.orders.OrderEventThe JsonDeserializer converts the JSON bytes into an OrderEvent. It only builds classes from packages listed in spring.json.trusted.packages. This stops a producer from making your consumer instantiate arbitrary classes.
Reading more than the payload
Sometimes you need the key, partition or offset. Wrap the payload in a ConsumerRecord, or add annotated parameters.
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.stereotype.Component;
@Component
public class OrderAuditListener {
private static final Logger log = LoggerFactory.getLogger(OrderAuditListener.class);
@KafkaListener(topics = "orders", groupId = "order-audit")
public void audit(ConsumerRecord<String, OrderEvent> record) {
log.info("key={} partition={} offset={} amount={}",
record.key(), record.partition(), record.offset(),
record.value().amountCents());
}
}This listener uses a different group ID, order-audit. Each group tracks its own offsets, so both listeners receive every record on the topic. Two listeners in the same group would instead split the partitions between them.
Where the first read starts
auto-offset-reset applies only when a group has no committed offset yet. With earliest, a new group reads the topic from the beginning. With latest, which is the Kafka default, it sees only records sent after it joins. Once the group has committed offsets, this setting is ignored and the group resumes from its last commit.
Common errors
| Symptom | Likely cause |
|---|---|
| Listener never runs | The class is not a Spring bean, or the topic name is misspelled. |
| New group sees no old records | `auto-offset-reset` is `latest`. Use `earliest`. |
| `IllegalArgumentException: The class ... is not in the trusted packages` | The payload's package is missing from `spring.json.trusted.packages`. |
| Deserialization fails for every record | The producer wrote a different type than the consumer expects. Align the types or the type headers. |
| Records are processed twice after a restart | The listener threw an exception or the app stopped before the commit. Make handlers idempotent. |
Ordering and exceptions
Kafka orders records only within a partition. Because the producer uses the order ID as the key, all events for one order reach the same partition and one listener thread reads them in order.
If a listener method throws, the container's error handler decides what happens next. By default it retries the failed record. The error handling chapters cover retries and dead-letter topics.
Exercise
You add a second listener to the topic orders with the same groupId = "order-service", and the topic has three partitions. Does the second listener receive a copy of every record? Explain.
Show answer
No. Listeners in the same group share the partitions, so each record goes to only one member of the group. To give the second listener its own copy of every record, put it in a different group, such as order-audit.
Exercise
A new consumer group starts with auto-offset-reset: latest on a topic that already holds 1,000 records. How many of those records does it read, and why?
Show answer
None of the existing 1,000. The group has no committed offset, so latest starts it at the end of the log. It reads only records that arrive after it joins.