StackPractices
intermediate By Mathias Paulenko

Consume Kafka Topics with Spring Boot Stream Listeners

Build reliable Kafka consumers in Spring Boot with @KafkaListener: concurrency, manual acks, retries with dead-letter topics, and batch listeners.

Topics: messaging

Overview

Spring Kafka turns Kafka consumption into an annotation problem: mark a method with @KafkaListener, point it at a topic, and a listener container handles polling, partition assignment, and offset commits for you. The catch is that the defaults aren’t right for production — auto-commit loses messages, no error handler stops your consumer on the first poison pill, and a mismatched concurrency wastes threads.

This recipe covers the pieces you’ll actually configure: the container factory, manual acknowledgment, retry with dead-letter topics, batch listeners, and header-based routing. Every example targets Spring Boot 3.x with Spring Kafka 3.x.

When to Use This

  • Spring Boot microservices that consume domain events from Kafka
  • Services needing typed deserialization (JSON straight into POJOs)
  • Workloads that can’t afford message loss — manual acks and dead-letter topics
  • High-throughput consumers that benefit from batch processing

If your service is a simple task queue with one consumer, RabbitMQ with pika or Spring AMQP is less machinery. For JVM apps already on Spring, @KafkaListener is the right level of abstraction — for raw control in Python, see Kafka Consumer Groups with Python, and for the JavaScript equivalent, Kafka Event Streaming.

Prerequisites

  • Java 17+
  • Spring Boot 3.x
  • spring-kafka dependency (spring-boot-starter pulls the right version)
  • A running Kafka broker (the companion repo ships a KRaft docker-compose.yml)

Solution

1. Configuration

# application.yml
spring:
  kafka:
    bootstrap-servers: localhost:9092
    consumer:
      group-id: order-service
      auto-offset-reset: earliest
      enable-auto-commit: false
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
      properties:
        spring.json.trusted.packages: "com.example.events"
    listener:
      ack-mode: manual
      concurrency: 3

Two settings matter most here. enable-auto-commit: false stops the client from committing offsets on a timer regardless of whether processing finished — that’s the classic silent data-loss bug. spring.json.trusted.packages restricts which classes JsonDeserializer will instantiate, closing a deserialization attack surface.

2. Basic Kafka Listener

package com.example.kafka;

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

@Service
public class OrderConsumer {

    @KafkaListener(
        topics = "orders",
        groupId = "order-service",
        containerFactory = "kafkaListenerContainerFactory"
    )
    public void handleOrder(OrderEvent event) {
        log.info("Received order {}", event.getOrderId());
        processOrder(event);
    }

    private void processOrder(OrderEvent event) {
        // Business logic
    }
}

Spring scans the context for @KafkaListener methods at startup and registers each one with a MessageListenerContainer. One method can listen to several topics, and several methods can share a groupId — though each method then becomes a separate consumer group member competing for partitions.

3. Consumer Configuration Bean

package com.example.config;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.support.serializer.JsonDeserializer;
import java.util.HashMap;
import java.util.Map;

@EnableKafka
@Configuration
public class KafkaConsumerConfig {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Bean
    public ConsumerFactory<String, Object> consumerFactory() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "order-service");
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);
        props.put(JsonDeserializer.TRUSTED_PACKAGES, "com.example.events");
        props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 500);
        return new DefaultKafkaConsumerFactory<>(props);
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, Object> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, Object> factory =
            new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        factory.setConcurrency(3);
        factory.getContainerProperties().setAckMode(
            org.springframework.kafka.listener.ContainerProperties.AckMode.MANUAL
        );
        return factory;
    }
}

You don’t strictly need this bean — application.yml already configures the default factory — but the moment you need different settings per listener (batch vs. single-record, different deserializers), an explicit factory bean is how you scope them.

4. Error Handling with a Dead-Letter Topic

The naive pattern — catching the exception and publishing to a DLQ yourself — has a trap: with ack-mode: manual you must still acknowledge after the DLQ send, or the offset never commits and the poison pill loops forever.

package com.example.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Service;

@Service
public class OrderConsumerWithDlq {

    private final KafkaTemplate<String, Object> kafkaTemplate;

    public OrderConsumerWithDlq(KafkaTemplate<String, Object> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    @KafkaListener(topics = "orders", groupId = "order-service")
    public void handleOrder(ConsumerRecord<String, OrderEvent> record, Acknowledgment ack) {
        try {
            processOrder(record.value());
        } catch (Exception e) {
            kafkaTemplate.send("orders.dlq", record.key(), record.value());
            log.error("Sent record at offset {} to DLQ", record.offset(), e);
        } finally {
            // Commit either way: the record was processed or parked in the DLQ.
            ack.acknowledge();
        }
    }

    private void processOrder(OrderEvent event) {
        if (event.getOrderId() == null) {
            throw new IllegalArgumentException("Missing orderId");
        }
        // Business logic
    }
}

Hand-rolled DLQs work, but they skip retries entirely and lose the original headers. In most services you’ll want the framework-managed version from the Variants section instead — DeadLetterPublishingRecoverer preserves the source topic, partition, and offset in DLQ headers.

5. Batch Listener

package com.example.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class BatchOrderConsumer {

    @KafkaListener(
        topics = "orders",
        groupId = "order-batch-service",
        batch = "true"
    )
    public void handleBatch(List<ConsumerRecord<String, OrderEvent>> records, Acknowledgment ack) {
        log.info("Processing batch of {} records", records.size());
        for (ConsumerRecord<String, OrderEvent> record : records) {
            try {
                processOrder(record.value());
            } catch (Exception e) {
                log.error("Failed record at offset {}: {}", record.offset(), e.getMessage());
            }
        }
        ack.acknowledge();
    }

    private void processOrder(OrderEvent event) {
        // Business logic
    }
}

Batch listeners shine when each record triggers a database write — you can collect valid records and do one bulk insert instead of N round-trips. The trade-off is replay scope: if the consumer dies mid-batch after committing nothing, the whole batch is redelivered, so keep max.poll.records sized to what you can process inside max.poll.interval.ms.

6. Manual Acknowledgment per Record

@Service
public class ManualAckConsumer {

    @KafkaListener(topics = "orders", groupId = "order-manual-service")
    public void handleOrder(
        ConsumerRecord<String, OrderEvent> record,
        Acknowledgment acknowledgment
    ) {
        try {
            processOrder(record.value());
            acknowledgment.acknowledge();
        } catch (Exception e) {
            log.error("Processing failed, offset {} not committed", record.offset(), e);
            // Don't acknowledge: the record will be redelivered after a rebalance
            // or poll timeout. Make sure an error handler bounds the retries.
        }
    }

    private void processOrder(OrderEvent event) {
        // Business logic
    }
}

Not acknowledging is a deliberate choice — it means “give me this record again.” Without a DefaultErrorHandler or @RetryableTopic in place, an unacknowledged poison pill will stall that partition indefinitely.

7. Header-Based Routing

@Service
public class RoutingConsumer {

    @KafkaListener(topics = "events", groupId = "event-processor")
    public void handleEvent(ConsumerRecord<String, byte[]> record, Acknowledgment ack) {
        Header typeHeader = record.headers().lastHeader("event-type");
        String eventType = typeHeader != null ? new String(typeHeader.value()) : "UNKNOWN";

        switch (eventType) {
            case "ORDER_CREATED" -> processOrderCreated(record.value());
            case "ORDER_CANCELLED" -> processOrderCancelled(record.value());
            case "PAYMENT_PROCESSED" -> processPayment(record.value());
            default -> log.warn("Unknown event type at offset {}", record.offset());
        }
        ack.acknowledge();
    }
}

Always guard lastHeader() — it returns null when the header is absent, and a bare .value() call turns a missing header into an NPE that looks like a processing failure.

8. Multiple Container Factories

@Configuration
public class MultiTopicConfig {

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, Object> ordersFactory(
            ConsumerFactory<String, Object> cf) {
        var factory = new ConcurrentKafkaListenerContainerFactory<String, Object>();
        factory.setConsumerFactory(cf);
        factory.setConcurrency(3);
        return factory;
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, Object> paymentsFactory(
            ConsumerFactory<String, Object> cf) {
        var factory = new ConcurrentKafkaListenerContainerFactory<String, Object>();
        factory.setConsumerFactory(cf);
        factory.setConcurrency(2);
        return factory;
    }
}
@Service
public class MultiTopicConsumer {

    @KafkaListener(topics = "orders", groupId = "multi-service", containerFactory = "ordersFactory")
    public void handleOrder(OrderEvent event) {
        processOrder(event);
    }

    @KafkaListener(topics = "payments", groupId = "multi-service", containerFactory = "paymentsFactory")
    public void handlePayment(PaymentEvent event) {
        processPayment(event);
    }
}

Different topics often need different throughput or different error policies. Named factories let orders run 3 threads with aggressive retry while payments runs 2 threads with a stricter handler — one consumer group, scoped behavior.

How It Works

flowchart diagram: Kafka topic<br/>orders · 6 partitions
  1. The container, not your method, polls. ConcurrentMessageListenerContainer runs the poll() loop and dispatches records to your listener. setConcurrency(n) spawns n independent KafkaConsumer threads; Kafka’s group coordinator assigns partitions across them.
  2. Concurrency is capped by partitions. With 6 partitions and concurrency = 3, each thread owns 2. Setting concurrency = 12 gives you 6 idle threads — they’ll never receive a record. Scale the topic’s partition count to scale consumer parallelism.
  3. Ack modes decide when offsets move. MANUAL waits for your ack.acknowledge() and batches the commit on the next poll. MANUAL_IMMEDIATE commits synchronously right away. BATCH commits whatever was polled once the batch returns. RECORD commits per record. The lower you go, the more duplicates on redelivery — but the less you lose on a crash.
  4. The error handler wraps your method. On an exception, DefaultErrorHandler consults its backoff policy, retries, and eventually calls the recoverer — DeadLetterPublishingRecoverer publishes to topic.dlq (or topic-dlt by convention) with headers recording the original topic, partition, offset, and exception. Only then does the container acknowledge.
  5. Deserialization failures need their own path. If JsonDeserializer throws, your listener never runs. ErrorHandlingDeserializer wraps the real deserializer, captures the failure in a header, and lets the error handler route the bad record to the DLT instead of wedging the consumer.

Variants

Declarative Retries with @RetryableTopic

Spring Kafka 2.9+ can manage retry topics for you — no manual DefaultErrorHandler wiring:

@Service
public class RetryableOrderConsumer {

    @RetryableTopic(
        attempts = "4",
        backoff = @Backoff(delay = 1000, multiplier = 2.0),
        dltTopicSuffix = "-dlt",
        autoCreateTopics = "true"
    )
    @KafkaListener(topics = "orders", groupId = "order-service")
    public void handleOrder(OrderEvent event) {
        processOrder(event);
    }

    @DltHandler
    public void onDlt(OrderEvent event, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {
        log.error("Record landed in {} after all retries: {}", topic, event.getOrderId());
    }
}

This is non-blocking style retry: a failed record goes to orders-retry-0, orders-retry-1, etc., so one bad record doesn’t hold up the partition. Prefer it over blocking DefaultErrorHandler retries when ordering per-key doesn’t matter.

Classic Blocking Retry with Recoverer

@Bean
public ConcurrentKafkaListenerContainerFactory<String, Object> retryFactory(
        ConsumerFactory<String, Object> cf,
        KafkaTemplate<String, Object> template) {
    var factory = new ConcurrentKafkaListenerContainerFactory<String, Object>();
    factory.setConsumerFactory(cf);

    DefaultErrorHandler errorHandler = new DefaultErrorHandler(
        new DeadLetterPublishingRecoverer(template),
        new ExponentialBackOffWithMaxRetries(3)
    );
    factory.setCommonErrorHandler(errorHandler);
    return factory;
}

Blocking retry keeps records in-order and is simpler to reason about, but a slow-failing record delays everything behind it in the partition.

Filtering Messages

@Bean
public ConcurrentKafkaListenerContainerFactory<String, Object> filteringFactory(
        ConsumerFactory<String, Object> cf) {
    var factory = new ConcurrentKafkaListenerContainerFactory<String, Object>();
    factory.setConsumerFactory(cf);

    // Skip records whose status isn't PENDING — they never reach the listener.
    factory.setRecordFilterStrategy(record -> {
        OrderEvent event = (OrderEvent) record.value();
        return !"PENDING".equals(event.getStatus());
    });
    return factory;
}

Filtered records are still consumed and their offsets committed — the filter only skips dispatch to your method. It’s a cheap way to drop noise without a second consumer group.

Manual Partition Assignment

@KafkaListener(
    groupId = "partitioned-service",
    topicPartitions = @TopicPartition(topic = "orders", partitions = {"0", "1", "2"})
)
public void handlePartition(ConsumerRecord<String, OrderEvent> record) {
    log.info("Partition {} offset {}", record.partition(), record.offset());
}

Explicit assignment bypasses the group coordinator — useful for replaying a known partition or building tools, but you lose automatic rebalancing and can’t share the load dynamically.

Best Practices

  • Set concurrency to partition count. With 6 partitions, concurrency = 6 maxes parallelism; more threads just idle.
  • Disable auto-commit, always. enable-auto-commit: false plus explicit ack.acknowledge() is the only way to guarantee “commit means processed.”
  • Bound your retries. Either @RetryableTopic with attempts or DefaultErrorHandler with a recoverer — never let an exception loop forever against a partition.
  • Use ErrorHandlingDeserializer for untrusted topics so malformed payloads can’t wedge the consumer.
  • Size batches to max.poll.interval.ms. If 500 records take longer than the 5-minute default interval, the consumer looks dead and gets evicted mid-work.
  • Watch consumer lag, not just logs: Spring Boot Actuator’s Kafka metrics plus Micrometer give you lag per topic-partition — the earliest warning of a slow listener.

Common Mistakes

  • Leaving ack-mode at the default. BATCH commits whatever came back from poll() once your method returns — a thrown exception mid-method still commits the whole poll. Use MANUAL for per-record control.
  • Forgetting to ack in a manual DLQ. Catch → send to DLQ → still acknowledge. Otherwise the record returns after the next rebalance and you DLQ it forever.
  • Blocking inside the listener. A 30-second remote call blocks the poll thread; exceeding max.poll.interval.ms triggers a rebalance and mass redelivery. Offload heavy work to an executor and pause the container if needed.
  • Ignoring max.poll.records. The default 500 per poll can be too much for slow handlers — a smaller cap keeps each ack.acknowledge() within the interval.
  • Catching deserialization errors yourself. They happen before your method runs, so your try/catch never sees them — that’s what ErrorHandlingDeserializer is for.

See Also

Frequently Asked Questions

How does concurrency relate to partitions?

concurrency sets how many KafkaConsumer threads the container runs. The group coordinator assigns partitions across all consumers in the group, so concurrency = 3 on a 6-partition topic gives each thread 2 partitions. Anything above the partition count idles — extra threads are assigned nothing.

What's the difference between BATCH and MANUAL ack mode?

BATCH (the default for batch listeners) commits all offsets from the last poll() when your method returns normally — an exception partway through still risks committing unprocessed records depending on where it's thrown. MANUAL commits nothing until you call ack.acknowledge(), which puts the decision in your hands per batch or per record.

When should I use @RetryableTopic vs DefaultErrorHandler?

@RetryableTopic is the better default: retries happen in separate retry topics, so a failing record doesn't block everything behind it in the partition. Use blocking DefaultErrorHandler retries only when strict per-partition ordering matters more than latency.

What lands in the dead-letter topic?

Whatever the recoverer publishes — DeadLetterPublishingRecoverer copies the record to {topic}.dlt (or a name you choose) and stamps headers with the original topic, partition, offset, timestamp, and the exception class and message. That context is what makes DLQs debuggable instead of a graveyard.

Can one method listen to several topics?

Yes — @KafkaListener(topics = {"orders", "payments"}) subscribes to both, and all records funnel into the same handler. Differentiate them with record.topic(), a header-based router, or just use separate methods and container factories.

How do I handle records that fail to deserialize?

Set ErrorHandlingDeserializer as the value (or key) deserializer. It catches the failure, records it in a DeserializationException header, and hands the record to your error handler — which typically retries zero times and sends it straight to the DLT.