Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 58

    Kafka Messaging

    Apache Kafka is the durable partitioned log behind Orders events: order.placed, order.cancelled, inventory reservations, billing charges.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Apache Kafka is the durable partitioned log behind Orders events: order.placed, order.cancelled, inventory reservations, billing charges.

    Boot 3's spring-kafka provides KafkaTemplate producers and @KafkaListener consumers with group coordination.

    Partition keys (orderId/customerId) define ordering. Delivery is typically at-least-once — consumers must be idempotent. Prefer schema registry (Avro/Protobuf) over ad-hoc JSON as the platform matures.

    This lesson connects TechLearningPRO Orders to Kafka without embedding broker passwords in source.

    Purpose of this lesson

    Produce and consume Orders domain events with Spring Kafka on Boot 3 / Java 21.

    Understanding the topic

    Producers append; consumer groups share partitions; the log retains history.

    • topic: named stream of events.
    • partition key: ordering and parallelism.
    • consumer group: competing consumers for scale.
    • offset: progress marker — commit after successful processing.
    • idempotency: duplicates happen; design for them.

    Step-by-step explanation

    1. Add Spring Kafka and configure bootstrap-servers via env.
    2. Publish OrderPlaced from the service (ideally via outbox).
    3. Add a billing @KafkaListener on order.placed with a dedicated group id.
    4. Verify redelivery does not double-charge (idempotency key / processed table).

    Informative example

    Orders producer and billing listener.

    java
    # application.yml
    spring:
    kafka:
    bootstrap-servers: ${KAFKA_BOOTSTRAP:localhost:9092}
    consumer:
    group-id: orders-svc
    auto-offset-reset: earliest
    producer:
    key-serializer: org.apache.kafka.common.serialization.StringSerializer
    value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
    @Service
    public class OrderEventPublisher {
    private final KafkaTemplate<String, OrderPlaced> kafka;
    public OrderEventPublisher(KafkaTemplate<String, OrderPlaced> kafka) {
    this.kafka = kafka;
    }
    public void publish(OrderPlaced event) {
    kafka.send("order.placed", String.valueOf(event.orderId()), event);
    }
    }
    @Component
    public class BillingOrderListener {
    private final BillingService billing;
    public BillingOrderListener(BillingService billing) {
    this.billing = billing;
    }
    @KafkaListener(topics = "order.placed", groupId = "billing-svc")
    public void onOrderPlaced(OrderPlaced event) {
    billing.chargeOnce(event.orderId(), event.total());
    }
    }

    Real-world use

    Notification and analytics both needed place-order signals. Instead of chaining synchronous HTTP calls, Orders published order.placed once; each team consumed with its own group id and scaled independently during Black Friday.

    Security implications

    Kafka clusters hold sensitive business events.

    • Enable TLS and SASL in production; credentials via ${KAFKA_JAAS_CONFIG} style env.
    • Minimize PII in event payloads; prefer ids.
    • ACLs per producer/consumer principal — least privilege on topics.

    Best practices

    • Stable keys; idempotent handlers; dead-letter topics for poison messages.
    • Outbox to avoid dual-write between DB and Kafka.
    • Evolve schemas carefully; avoid breaking field removals.

    Common mistakes

    • Using null/random keys when you need per-order ordering.
    • Non-idempotent consumers under at-least-once delivery.
    • Blocking forever in a listener without timeouts — stalling the partition.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat does a Kafka consumer group provide?+

    Answer

    Competing consumers share topic partitions for scale while each group maintains its own offsets for independent progress.
    2IntermediateQuestionWhy is the partition key important?+

    Answer

    All events with the same key go to the same partition, preserving order for that key and controlling parallelism.
    3IntermediateQuestionHow do you handle at-least-once duplicates?+

    Answer

    Make processing idempotent — e.g. store processed event ids or use upsert/charge-once semantics keyed by order id.

    Hands-on exercise

    Lab. Publish OrderPlaced with orderId as key. Write two listeners in different group ids and confirm both receive the event. Replay the same message and prove your handler is idempotent.

    Summary

    Kafka messaging lets TechLearningPRO Orders publish once and fan out reliably — with idempotent listeners and env-based broker config.

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