Apache Kafka Tutorial 0/111 lessons ~6 min read Lesson 83

    @KafkaListener

    What is @KafkaListener?

    Course progress0%
    Focus
    9 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    What is @KafkaListener? @KafkaListener creates message listener containers that poll Kafka and invoke your method.

    Understanding the topic

    What happens — @KafkaListener:

    • Add spring-kafka dependency.
    • Configure bootstrap servers in application.yml.
    • Use KafkaTemplate to send.
    • Use @KafkaListener to consume.
    TermDescription
    KafkaTemplateSpring producer wrapper.
    @KafkaListenerAnnotated consumer method.
    AcknowledgmentManual ack in listener.
    ErrorHandlerRetry and DLT routing.

    Visual explanation

    Pipeline view:

    text
    KafkaTemplate
    topic
    @KafkaListener container
    service logic
    ack/retry/DLT

    Step-by-step explanation

    1. Configure — Producer/consumer factories.
    2. Produce — kafkaTemplate.send().
    3. Consume — @KafkaListener method.
    4. Handle errors — Retry topics + DLT.

    Informative example

    Example:

    java
    @KafkaListener(topics = "orders", groupId = "inventory-service")
    public void handle(OrderCreated event, Acknowledgment ack) {
    inventory.reserve(event);
    ack.acknowledge();
    }

    Execution workflow

    1@KafkaListener workflow
    1 / 4

    Configure

    Producer/consumer factories.

    Best practices

    • Use typed event classes and schema validation.
    • Use manual or record ack modes for critical processing.
    • Add retry topics and DLT with alerts.
    • Test with embedded Kafka or Testcontainers.

    Common mistakes

    • Doing slow blocking work inside listener threads without concurrency planning.
    • Catching exceptions and still acknowledging bad records.
    • No DLT monitoring.

    Summary

    @KafkaListener — Configure listener containers intentionally: ack mode, concurrency, error handling, retries, DLT, observability, and idempotent processing.

    Ready to mark this lesson complete?Track your journey across the entire course.