00:00

Spring Kafka Annotations

Last updated:

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

AnnotationPackagePlaced onPurpose
@EnableKafkao.s.kafka.annotationConfiguration classTurns on processing of @KafkaListener (automatic in Spring Boot)
@KafkaListenero.s.kafka.annotationMethod, class or annotationDeclares a Kafka consumer endpoint
@KafkaListenerso.s.kafka.annotationMethod or classContainer for repeated @KafkaListener annotations
@KafkaHandlero.s.kafka.annotationMethod in a class-level listenerChooses the handler method by payload type
@TopicPartitiono.s.kafka.annotationInside @KafkaListenerAssigns specific partitions instead of using group management
@PartitionOffseto.s.kafka.annotationInside @TopicPartitionSets the initial offset for an assigned partition
@RetryableTopico.s.kafka.annotationListener method or classNon-blocking retries through retry topics and a dead-letter topic
@BackOffo.s.kafka.annotationInside @RetryableTopicDelay between retry attempts (new in 4.0)
@DltHandlero.s.kafka.annotationMethod in the listener’s classProcesses records that reach the dead-letter topic
@EnableKafkaRetryTopico.s.kafka.annotationConfiguration classEnables global configuration of the retry-topic feature
@EnableKafkaStreamso.s.kafka.annotationConfiguration classCreates the default StreamsBuilderFactoryBean for Kafka Streams
@Payload, @Header, @Headerso.s.messaging.handler.annotationListener method parametersBind the value, single headers or all headers
@SendToo.s.messaging.handler.annotationListener methodSends the method’s return value to a reply topic
@EmbeddedKafkao.s.kafka.test.contextTest classStarts 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

From @KafkaListener annotation to running consumerAt startup, the KafkaListenerAnnotationBeanPostProcessor finds methods annotated with @KafkaListener and registers an endpoint for each. The endpoint registry uses the listener container factory, by default kafkaListenerContainerFactory, to create a ConcurrentMessageListenerContainer with the configured concurrency. Each container thread runs a KafkaConsumer that polls records, converts them with the message converter and invokes the annotated method with the resolved parameters, then commits offsets according to the AckMode. @KafkaListenermethod on aSpring bean Bean post-processorregisters an endpointat startup Container factorykafkaListener-ContainerFactory ConcurrentMessageListenerContainer consumerthread 1 consumerthread 2 consumerthread n Your method is invokedpoll → convert value and headers → resolve @Payload,@Header, Acknowledgment → call method → commit (AckMode) creates (concurrency = n)
Annotations are metadata; at startup Spring builds a listener container per endpoint, and the container’s threads call your method.

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

  • @EnableKafka registers the bean post-processor that detects @KafkaListener. In a plain Spring application you add it to a @Configuration class. Spring Boot enables it automatically when Spring Kafka is on the classpath, so Boot applications do not need it.
  • @EnableKafkaRetryTopic enables the retry-topic feature’s components for injection and global configuration (for example by extending RetryTopicConfigurationSupport). It is meta-annotated with @EnableKafka, so you never need both.
  • @EnableKafkaStreams creates a StreamsBuilderFactoryBean so you can define Kafka Streams topologies as beans (see section 11).
KafkaConfig.java (plain Spring, without Boot)
@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:

OrderListener.java
@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:

AttributeWhat it does
idUnique 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 / topicPartitionsWhat to consume: topic names, a regular expression, or explicitly assigned partitions (use exactly one)
groupIdConsumer group for this listener, overriding group.id
containerFactoryBean name of the factory to use; default kafkaListenerContainerFactory
concurrencyNumber 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
ackModeOverrides the factory’s acknowledgement mode, for example "MANUAL_IMMEDIATE"
propertiesKafka consumer properties for this listener, such as "max.poll.records=50"
errorHandlerBean name of a KafkaListenerErrorHandler that handles exceptions from this method
filterBean name of a RecordFilterStrategy that discards records before the method is called
clientIdPrefixPrefix for the consumer’s client.id, which makes metrics and broker logs easier to read
containerGroupAdds the container to a named group of containers that can be managed together
infoStatic text added to every record as the KafkaHeaders.LISTENER_INFO header
splitIterables, contentTypeConverter, beanRef, containerPostProcessorAdvanced: 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:

PaymentListener.java
@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
}
  • @Payload marks the value. It is optional for a single unannotated parameter, but needed with required = false to accept null values (tombstones) and with @Valid for validation.
  • @Header binds one header. KafkaHeaders provides constants for the record metadata: RECEIVED_KEY, RECEIVED_TOPIC, RECEIVED_PARTITION, OFFSET, RECEIVED_TIMESTAMP and more. Custom headers are referenced by name.
  • @Headers binds all headers as a Map.
  • Without annotations you can also declare ConsumerRecord, Acknowledgment (with a manual ack mode) and Consumer.
Validation: @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:

AuditReplayListener.java
@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:

OrderEventsListener.java
@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:

ShopListener.java
@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:

FraudCheckListener.java
@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:

InvoiceListener.java
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
    }
}
SettingDefaultNotes
attempts"3"Total attempts including the first one, before the DLT
backOffFixed 1000 ms@BackOff(delay, multiplier, maxDelay, jitter); with only delay it is a fixed delay, otherwise exponential
retryTopicSuffix / dltTopicSuffix-retry / -dltTopics such as invoices-retry-0 and invoices-dlt; since 4.1 one retry topic is reused for attempts with the same delay
include / excludeAll exceptions retriedExclude errors that will never succeed, such as validation failures
autoCreateTopics"true"Creates the retry and DLT topics; turn off where topics are managed centrally
Spring Kafka 4 change: @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:

InvoiceListenerTest.java
@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 id on two listeners. Container IDs must be unique; the application fails at startup.
  • Forgetting that id becomes the group ID. Renaming a listener’s id without a groupId silently moves it to a new consumer group, which starts from the reset position.
  • Setting concurrency above the partition count. Extra threads stay idle.
  • Calling Acknowledgment without a manual ack mode. The parameter is only available when the container uses MANUAL or MANUAL_IMMEDIATE.
  • Expecting @Valid to work without registering a validator.
  • Using Spring Retry’s @Backoff with Spring Kafka 4. Use org.springframework.kafka.annotation.BackOff.
  • Using @KafkaHandler with a plain StringDeserializer. Every payload is a String, so only the default handler is called.

13. Best Practices

  • Always set an explicit groupId and a stable id, 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 @RetryableTopic only for unordered work, and blocking retries with DefaultErrorHandler where 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.

16. References