Spring Kafka Annotations
Spring Kafka annotations turn ordinary Spring beans into Kafka consumers, retry pipelines and request–reply handlers. With @KafkaListener and a handful of related annotations you declare what to consume and how to handle it, and Spring for Apache Kafka creates and manages the listener containers, threads, offset commits and retries for you.
This tutorial describes every annotation in Spring for Apache Kafka 4.x, grouped by purpose: enabling the infrastructure, defining listeners, binding message data to method parameters, assigning partitions explicitly, routing replies, non-blocking retries with dead-letter topics, Kafka Streams and testing. Each section shows a practical example and the mistakes to avoid.
1. All Spring Kafka Annotations at a Glance
| Annotation | Package | Placed on | Purpose |
|---|---|---|---|
@EnableKafka | o.s.kafka.annotation | Configuration class | Turns on processing of @KafkaListener (automatic in Spring Boot) |
@KafkaListener | o.s.kafka.annotation | Method, class or annotation | Declares a Kafka consumer endpoint |
@KafkaListeners | o.s.kafka.annotation | Method or class | Container for repeated @KafkaListener annotations |
@KafkaHandler | o.s.kafka.annotation | Method in a class-level listener | Chooses the handler method by payload type |
@TopicPartition | o.s.kafka.annotation | Inside @KafkaListener | Assigns specific partitions instead of using group management |
@PartitionOffset | o.s.kafka.annotation | Inside @TopicPartition | Sets the initial offset for an assigned partition |
@RetryableTopic | o.s.kafka.annotation | Listener method or class | Non-blocking retries through retry topics and a dead-letter topic |
@BackOff | o.s.kafka.annotation | Inside @RetryableTopic | Delay between retry attempts (new in 4.0) |
@DltHandler | o.s.kafka.annotation | Method in the listener’s class | Processes records that reach the dead-letter topic |
@EnableKafkaRetryTopic | o.s.kafka.annotation | Configuration class | Enables global configuration of the retry-topic feature |
@EnableKafkaStreams | o.s.kafka.annotation | Configuration class | Creates the default StreamsBuilderFactoryBean for Kafka Streams |
@Payload, @Header, @Headers | o.s.messaging.handler.annotation | Listener method parameters | Bind the value, single headers or all headers |
@SendTo | o.s.messaging.handler.annotation | Listener method | Sends the method’s return value to a reply topic |
@EmbeddedKafka | o.s.kafka.test.context | Test class | Starts an embedded KRaft broker for tests |
All string attributes of the Kafka annotations accept property placeholders (${...}) and SpEL expressions (#{...}), so topic names and group IDs can come from configuration.
2. How @KafkaListener Works Internally
Because the method is called from container threads, the annotations configure how the container behaves (topics, group, concurrency, acknowledgement) and what your method receives. The container factory, usually the one Spring Boot auto-configures from spring.kafka.listener.*, supplies everything the annotation does not override.
3. Enabling Annotations: @EnableKafka and Friends
@EnableKafkaregisters the bean post-processor that detects@KafkaListener. In a plain Spring application you add it to a@Configurationclass. Spring Boot enables it automatically when Spring Kafka is on the classpath, so Boot applications do not need it.@EnableKafkaRetryTopicenables the retry-topic feature’s components for injection and global configuration (for example by extendingRetryTopicConfigurationSupport). It is meta-annotated with@EnableKafka, so you never need both.@EnableKafkaStreamscreates aStreamsBuilderFactoryBeanso you can define Kafka Streams topologies as beans (see section 11).
@Configuration
@EnableKafka
public class KafkaConfig {
@Bean
ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(
ConsumerFactory<String, String> consumerFactory) {
var factory = new ConcurrentKafkaListenerContainerFactory<String, String>();
factory.setConsumerFactory(consumerFactory);
return factory;
}
}
4. @KafkaListener and Its Attributes
The simplest listener needs only a topic and a group:
@Component
public class OrderListener {
@KafkaListener(id = "order-billing", topics = "${app.topics.orders}", groupId = "billing",
concurrency = "3")
public void onOrder(String order) {
System.out.println("Billing order " + order);
}
}
The attributes override the container factory’s defaults for this listener only:
| Attribute | What it does |
|---|---|
id | Unique container ID, used to look up the container in the KafkaListenerEndpointRegistry (for example to start or stop it). Also the group ID unless groupId is set or idIsGroup = false |
topics / topicPattern / topicPartitions | What to consume: topic names, a regular expression, or explicitly assigned partitions (use exactly one) |
groupId | Consumer group for this listener, overriding group.id |
containerFactory | Bean name of the factory to use; default kafkaListenerContainerFactory |
concurrency | Number of consumer threads (useful only up to the number of partitions) |
autoStartup | "false" creates the container without starting it, for example to start it after a warm-up |
batch | "true" delivers a List of records per poll instead of one record per call |
ackMode | Overrides the factory’s acknowledgement mode, for example "MANUAL_IMMEDIATE" |
properties | Kafka consumer properties for this listener, such as "max.poll.records=50" |
errorHandler | Bean name of a KafkaListenerErrorHandler that handles exceptions from this method |
filter | Bean name of a RecordFilterStrategy that discards records before the method is called |
clientIdPrefix | Prefix for the consumer’s client.id, which makes metrics and broker logs easier to read |
containerGroup | Adds the container to a named group of containers that can be managed together |
info | Static text added to every record as the KafkaHeaders.LISTENER_INFO header |
splitIterables, contentTypeConverter, beanRef, containerPostProcessor | Advanced: reply splitting, conversion, SpEL bean reference and per-container customisation |
5. Method Parameters: @Payload, @Header and @Headers
A listener method can declare the record value and any metadata it needs; Spring resolves each parameter:
@KafkaListener(topics = "payments", groupId = "ledger", ackMode = "MANUAL_IMMEDIATE")
public void onPayment(@Payload Payment payment, // converted value
@Header(KafkaHeaders.RECEIVED_KEY) String paymentId,
@Header(KafkaHeaders.RECEIVED_PARTITION) int partition,
@Header(KafkaHeaders.OFFSET) long offset,
@Header(name = "correlation-id", required = false) String correlationId,
@Headers Map<String, Object> allHeaders,
Acknowledgment ack) {
ledger.book(paymentId, payment);
ack.acknowledge(); // commit this record's offset now
}
@Payloadmarks the value. It is optional for a single unannotated parameter, but needed withrequired = falseto acceptnullvalues (tombstones) and with@Validfor validation.@Headerbinds one header.KafkaHeadersprovides constants for the record metadata:RECEIVED_KEY,RECEIVED_TOPIC,RECEIVED_PARTITION,OFFSET,RECEIVED_TIMESTAMPand more. Custom headers are referenced by name.@Headersbinds all headers as aMap.- Without annotations you can also declare
ConsumerRecord,Acknowledgment(with a manual ack mode) andConsumer.
@Payload @Valid Payment payment only validates if a validator is registered with the listener registrar, by implementing KafkaListenerConfigurer and calling registrar.setValidator(...). With the Spring Boot validation starter you can inject the auto-configured LocalValidatorFactoryBean and pass it on.6. @TopicPartition and @PartitionOffset
Normally the consumer group assigns partitions. With topicPartitions you assign them yourself, which suits tools, replays and single-instance consumers that must read a known partition:
@KafkaListener(id = "audit-replay", groupId = "audit-replay",
topicPartitions = @TopicPartition(topic = "audit-events",
partitions = "0",
partitionOffsets = @PartitionOffset(partition = "1", initialOffset = "500")))
public void replay(ConsumerRecord<String, String> record) {
// partition 0 starts from the committed offset; partition 1 starts at offset 500
}
With manual assignment there is no rebalancing: if this instance stops, nobody else takes over its partitions. Offsets are still committed to the groupId unless you disable commits. To reposition dynamically instead, implement ConsumerSeekAware; see message replay.
7. Class-Level Listeners with @KafkaHandler
When one topic carries several event types, put @KafkaListener on the class and mark one method per type with @KafkaHandler. Spring chooses the method by the converted payload’s type:
@Component
@KafkaListener(id = "order-events", topics = "order-events", groupId = "shipping")
public class OrderEventsListener {
@KafkaHandler
public void placed(OrderPlaced event) { shipping.prepare(event.orderId()); }
@KafkaHandler
public void cancelled(OrderCancelled event) { shipping.cancel(event.orderId()); }
@KafkaHandler(isDefault = true)
public void unknown(Object event) { log.warn("Ignoring unknown event {}", event); }
}
This only works if the deserializer produces the concrete types, for example JSON with type information in headers (JacksonJsonDeserializer with type mapping) or Avro with specific records. At most one method can be the default handler.
8. @KafkaListeners and Custom Meta-Annotations
@KafkaListener is repeatable: placing it twice on a method creates two independent containers, for example to consume one topic in two groups. The compiler wraps repeated annotations in @KafkaListeners automatically, so you rarely write that annotation yourself.
Because @KafkaListener can be used as a meta-annotation, teams can define their own listener annotations with sensible defaults:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@KafkaListener(containerFactory = "shopContainerFactory")
public @interface ShopListener {
@AliasFor(annotation = KafkaListener.class, attribute = "id")
String id();
@AliasFor(annotation = KafkaListener.class, attribute = "topics")
String[] topics();
@AliasFor(annotation = KafkaListener.class, attribute = "concurrency")
String concurrency() default "3";
}
// usage
@ShopListener(id = "stock-updates", topics = "stock")
public void onStock(StockChanged event) { ... }
At least one of topics, topicPattern or topicPartitions must be aliased.
9. @SendTo: Replying to Another Topic
With @SendTo, the listener’s return value is sent to another topic, which is a compact way to build a processing step:
@KafkaListener(topics = "payments", groupId = "fraud-check")
@SendTo("payments-checked")
public PaymentChecked check(Payment payment) {
return new PaymentChecked(payment.id(), fraudModel.score(payment));
}
The destination can be a literal topic, a SpEL expression evaluated at startup (#{...}), or one evaluated per record at runtime (!{...}). Without a value, @SendTo replies to the topic named in the request’s KafkaHeaders.REPLY_TOPIC header, which is how ReplyingKafkaTemplate request–reply works. The container factory needs a reply template; Spring Boot sets the auto-configured KafkaTemplate for this.
10. @RetryableTopic, @BackOff and @DltHandler
@RetryableTopic implements non-blocking retries: a failed record is forwarded to a retry topic and processed again after a delay, while the main topic keeps flowing. After the last attempt it goes to a dead-letter topic (DLT), where an @DltHandler method can handle it:
import org.springframework.kafka.annotation.BackOff;
import org.springframework.kafka.annotation.DltHandler;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.annotation.RetryableTopic;
@Component
public class InvoiceListener {
@RetryableTopic(attempts = "4",
backOff = @BackOff(delay = 2000, multiplier = 2.0, maxDelay = 20000),
exclude = InvalidInvoiceException.class)
@KafkaListener(topics = "invoices", groupId = "invoice-sender")
public void send(Invoice invoice) {
mailService.send(invoice); // a timeout here triggers a delayed retry
}
@DltHandler
public void failed(Invoice invoice, @Header(KafkaHeaders.RECEIVED_TOPIC) String dltTopic) {
alerts.invoiceFailed(invoice.id(), dltTopic); // exception details are in the DLT_* headers
}
}
| Setting | Default | Notes |
|---|---|---|
attempts | "3" | Total attempts including the first one, before the DLT |
backOff | Fixed 1000 ms | @BackOff(delay, multiplier, maxDelay, jitter); with only delay it is a fixed delay, otherwise exponential |
retryTopicSuffix / dltTopicSuffix | -retry / -dlt | Topics such as invoices-retry-0 and invoices-dlt; since 4.1 one retry topic is reused for attempts with the same delay |
include / exclude | All exceptions retried | Exclude errors that will never succeed, such as validation failures |
autoCreateTopics | "true" | Creates the retry and DLT topics; turn off where topics are managed centrally |
@BackOff is Spring Kafka’s own annotation (org.springframework.kafka.annotation.BackOff), introduced in 4.0. Older examples use @Backoff from Spring Retry, which Spring Kafka no longer depends on. Retries through retry topics change the processing order, so do not use them for events that must stay in order; see retry and backoff.11. @EnableKafkaStreams and @EmbeddedKafka
@EnableKafkaStreams on a configuration class registers a StreamsBuilderFactoryBean, so a @Bean method can take a StreamsBuilder and define a topology; Spring starts and stops the KafkaStreams instance with the application context. Spring Boot reads the settings from spring.kafka.streams.*. The KStream, KTable and windowing tutorial shows a complete example.
@EmbeddedKafka from spring-kafka-test starts a KRaft broker inside the test JVM and points spring.kafka.bootstrap-servers at it:
@SpringBootTest(properties = "spring.kafka.consumer.auto-offset-reset=earliest")
@EmbeddedKafka(partitions = 1, topics = "invoices")
class InvoiceListenerTest {
// send with KafkaTemplate, then assert with Awaitility
}
See testing Kafka applications for complete tests.
12. Common Mistakes
- Reusing an
idon two listeners. Container IDs must be unique; the application fails at startup. - Forgetting that
idbecomes the group ID. Renaming a listener’sidwithout agroupIdsilently moves it to a new consumer group, which starts from the reset position. - Setting
concurrencyabove the partition count. Extra threads stay idle. - Calling
Acknowledgmentwithout a manual ack mode. The parameter is only available when the container usesMANUALorMANUAL_IMMEDIATE. - Expecting
@Validto work without registering a validator. - Using Spring Retry’s
@Backoffwith Spring Kafka 4. Useorg.springframework.kafka.annotation.BackOff. - Using
@KafkaHandlerwith a plainStringDeserializer. Every payload is aString, so only the default handler is called.
13. Best Practices
- Always set an explicit
groupIdand a stableid, so renaming code never changes consumer groups by accident. - Read topic names from configuration with
${...}placeholders. - Keep listener methods thin: convert, validate and delegate to a service that can be unit-tested.
- Define team-wide meta-annotations for repeated settings such as container factory and concurrency.
- Use
@RetryableTopiconly for unordered work, and blocking retries withDefaultErrorHandlerwhere order matters.
14. Summary
Spring for Apache Kafka builds its consumer model on annotations. @EnableKafka (automatic in Spring Boot) activates them, @KafkaListener declares endpoints whose attributes override the container factory, and @Payload, @Header and @Headers bind record data to method parameters. @TopicPartition and @PartitionOffset assign partitions explicitly, @KafkaHandler dispatches by payload type, @SendTo forwards results, and @RetryableTopic with @BackOff and @DltHandler adds non-blocking retries with a dead-letter topic. @EnableKafkaStreams and @EmbeddedKafka cover Kafka Streams and testing.
15. Related Reading
- Spring Kafka introduction: producers, consumers and auto-configuration
- Kafka error handling: DefaultErrorHandler and blocking retries
- Retry and backoff: non-blocking retries in depth
- Spring Boot annotations: the core Spring annotations used alongside these
16. References
- Spring for Apache Kafka: @KafkaListener annotation
- Spring for Apache Kafka: @KafkaListener on a class
- Spring for Apache Kafka: @KafkaListener as a meta-annotation
- Spring for Apache Kafka: Forwarding listener results using @SendTo
- Spring for Apache Kafka: Retry topic configuration
- Spring for Apache Kafka API: org.springframework.kafka.annotation
Spring Kafka Annotations Interview Questions and Answers
Common interview questions on Spring Kafka Annotations, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. Do you need @EnableKafka in a Spring Boot application?
Answer: No. Spring Boot’s Kafka auto-configuration enables annotation processing whenever Spring for Apache Kafka is on the classpath, so any bean can use @KafkaListener. @EnableKafka is needed in plain Spring applications, where it registers the bean post-processor that turns annotated methods into listener containers. @EnableKafkaRetryTopic already includes it.
Q. How do you read the record key, partition and offset inside a @KafkaListener method?
Answer: Add parameters annotated with @Header and the KafkaHeaders constants: @Header(KafkaHeaders.RECEIVED_KEY), @Header(KafkaHeaders.RECEIVED_PARTITION), @Header(KafkaHeaders.OFFSET), and so on. Alternatively, declare a ConsumerRecord parameter and read everything from it, or @Headers Map<String, Object> for all headers.
Intermediate questions
Q. What is the relationship between the id and groupId attributes of @KafkaListener?
Answer: id names the listener container, so it can be found in the KafkaListenerEndpointRegistry and must be unique. If groupId is not set, the id is also used as the consumer group ID, because idIsGroup defaults to true. Setting groupId explicitly decouples the two, so renaming a container never moves it to a new consumer group.
Q. When would you use @TopicPartition instead of subscribing with topics?
Answer: When a listener must read specific partitions regardless of group membership: replay tools, partition-specific workers, or starting a partition at a known offset with @PartitionOffset. The trade-off is that there is no rebalancing, so if the instance stops, nobody else consumes those partitions. For normal scalable consumers, subscribe with topics and let the group assign partitions.
Q. How do @RetryableTopic and @DltHandler work together?
Answer: @RetryableTopic creates retry topics and a dead-letter topic for the listener. A failed record is forwarded to a retry topic and consumed again after the @BackOff delay, while the main topic keeps flowing. After the configured attempts (3 by default) it is sent to the DLT, whose records are delivered to the @DltHandler method in the same class. Excluded exceptions go straight to the DLT.
Tricky and scenario questions
Q. After upgrading to Spring Kafka 4, code using @RetryableTopic(backoff = @Backoff(delay = 1000)) no longer compiles. Why?
Answer: In Spring Kafka 3, the backoff used Spring Retry’s @Backoff annotation. Spring Kafka 4 dropped the Spring Retry dependency and introduced its own org.springframework.kafka.annotation.BackOff, used as backOff = @BackOff(delay = 1000). Update the attribute name and import; delay, multiplier and maximum delay work as before.
Q. A class-level @KafkaListener with three @KafkaHandler methods always calls the default handler. What is wrong?
Answer: The handler is chosen by the type of the converted payload, so the deserializer must produce the concrete event types. With a StringDeserializer, or JSON without type information, every payload has the same type and only the default handler matches. Configure the JSON deserializer with type headers or type mappings, or use Avro specific records, so each event arrives as its own class.