Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 45

Consuming Kafka Messages with `@KafkaListener`

This lesson is built with resources from youtube.com, baeldung.com and 1 more site.

Hello! In our last lesson, we successfully implemented a Kafka producer in the Auth Service. When a new user registers, our application now publishes a UserRegisteredEvent to a Kafka topic, and we verified this using a command-line consumer tool.

Today, we'll build the other side of this communication channel. We will create a brand new, independent "Notifications Service" that acts as a consumer. This service will subscribe to the user-registered-events topic, receive the event, and process it—in this case, by logging a message that simulates sending a welcome email. This is a fundamental step in building a decoupled, event-driven microservices architecture.

Introduction: Receiving and Processing Events

In your MERN background, you would use a library like kafkajs to create a consumer instance. You'd then subscribe to a topic and define a callback function inside consumer.run({ eachMessage: async ({ topic, partition, message }) => { ... } }). This function would contain the logic to parse the JSON message and act on it.

Spring for Apache Kafka abstracts this away beautifully with the @KafkaListener annotation. Instead of managing a connection loop, we simply annotate a method. The Spring framework handles the underlying complexity of connecting to Kafka, subscribing to the topic, polling for messages, and deserializing the message payload directly into a Java object for our method to use. This is a powerful example of the Inversion of Control (IoC) principle in action.

Our goal is to create a new service that listens for UserRegisteredEvent and proves it can receive and understand the data sent by the Auth Service.


1. Creating the Notifications Service

First, we need a new, separate Spring Boot project for our Notifications Service. This service will be completely independent of the Auth Service, communicating only through Kafka.

A clean way to manage this is by creating a new module within our existing project structure. This keeps all our services organized under a single parent project.

Spring Boot Kafka Microservices - Spring Boot Kafka Real-World Project Tutorial @RameshFadatare

The video 'Spring Boot Kafka Microservices' from Java Guides provides an excellent walkthrough of creating a new consumer module within a parent Maven project. We will follow a similar approach.

Watch from 00:50:16 to 00:53:12. This section demonstrates how to create a new module, make it a Spring Boot application, and ensure the parent pom.xml is updated correctly. You can name your new module notifications-service.

After creating the new module, you'll need to set up its dependencies and copy the event schema.

  1. Update pom.xml: Your new notifications-service/pom.xml will need dependencies for spring-kafka, kafka-avro-serializer, and the avro-maven-plugin. The configuration will be nearly identical to the one you added to the auth-service in the last lesson. This is because the consumer also needs to understand the Avro format and generate the UserRegisteredEvent class.
  2. Copy the Avro Schema: Copy the UserRegisteredEvent.avsc file from auth-service/src/main/avro/ to notifications-service/src/main/avro/. This ensures both services are working from the exact same event contract.
  3. Build the Project: Run mvn clean install from your project's root directory to generate the UserRegisteredEvent.java class inside your new notifications-service module.

2. Configuring the Kafka Consumer

Now, let's configure our new service to connect to Kafka as a consumer. Create the src/main/resources/application.yml file in your notifications-service module and add the following configuration:

server:
  port: 8082 # A different port to avoid conflicts with the Auth Service (8080)

spring:
  application:
    name: notifications-service
  kafka:
    bootstrap-servers: localhost:9092
    consumer:
      group-id: "notifications-group" # Identifies this consumer group
      auto-offset-reset: earliest # Start reading from the beginning of the topic
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: io.confluent.kafka.serializers.KafkaAvroDeserializer
      properties:
        schema.registry.url: http://localhost:8081
        specific.avro.reader: true # IMPORTANT: Deserialize to specific Avro-generated class

Let's break down the key consumer-specific properties:

  • group-id: This is a critical concept. All consumers that share the same group-id work together to process messages from a topic. Kafka ensures that each message in a partition is delivered to only one consumer within that group. This is how you scale consumption.
  • auto-offset-reset: earliest: This tells the consumer where to start reading if it has no previously committed offset. earliest means it will read all messages from the beginning of the topic, which is perfect for development and testing. The other common value is latest, which would only process new messages arriving after the consumer starts.
  • key-deserializer & value-deserializer: These are the counterparts to the serializers in the producer. We use StringDeserializer for the key and KafkaAvroDeserializer for our Avro-formatted value.
  • specific.avro.reader: true: This is a crucial property for the KafkaAvroDeserializer. It tells the deserializer to map the incoming Avro message to the specific Java class generated by our plugin (UserRegisteredEvent.java), rather than a generic Avro record. Without this, you would get a ClassCastException.

3. Implementing the @KafkaListener

With configuration complete, writing the consumer code is remarkably simple.

First, ensure your main application class has the @EnableKafka annotation. Spring Boot often auto-configures this, but it's good practice to be explicit.

// In src/main/java/.../NotificationsServiceApplication.java
package com.example.notifications;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.EnableKafka;

@SpringBootApplication
@EnableKafka // Enable Kafka listener detection
public class NotificationsServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(NotificationsServiceApplication.class, args);
    }
}

Next, create a new class to house our listener logic.

// In src/main/java/com/example/notifications/UserEventConsumer.java
package com.example.notifications;

import com.example.blog.events.UserRegisteredEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

@Service
public class UserEventConsumer {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserEventConsumer.class);

    @KafkaListener(topics = "user-registered-events", groupId = "notifications-group")
    public void consume(UserRegisteredEvent event) {
        LOGGER.info("Received UserRegisteredEvent for user email: {}", event.getEmail());
        LOGGER.info("-> Simulating sending a welcome email to {}", event.getEmail());
        // In a real application, you would inject an EmailService and call it here.
        // emailService.sendWelcomeEmail(event.getEmail());
    }
}

That's it! Let's analyze what's happening:

  • @Service: This annotation registers our class as a Spring bean, so the framework will scan it for other annotations like @KafkaListener.
  • @KafkaListener: This is the magic. We tell Spring that the consume method is a Kafka message handler.
    • topics = "user-registered-events": The topic to subscribe to.
    • groupId = "notifications-group": The consumer group this listener belongs to. This should match the group-id in your application.yml.
  • public void consume(UserRegisteredEvent event): The method signature is key. Spring Kafka, using the configured KafkaAvroDeserializer, automatically deserializes the message payload into a UserRegisteredEvent object and passes it as an argument. This gives us full type safety right away.

This one annotation and method replaces all the manual setup of a consumer, subscription loop, and deserialization you'd do in kafkajs.

Scaling Kafka Consumers with Spring Boot and Schema Registry
This diagram from Confluent illustrates how consumers in a group work. Our `@KafkaListener` creates a consumer instance within the Spring Boot JVM. If we were to run multiple instances of our `notifications-service` (all with the same `group-id`), they would automatically balance the topic partitions among themselves, allowing for parallel processing.

The following video shows this exact process of creating a listener and logging the received message.

Spring Boot Kafka Microservices - Spring Boot Kafka Real-World Project Tutorial @RameshFadatare

The 'Spring Boot Kafka Microservices' video also demonstrates how to implement the consumer logic.

Watch from 00:57:42 to 01:02:22. This segment walks through creating a consumer class, adding a logger, and using the @KafkaListener annotation to consume and log a message from a topic. Notice how the method parameter directly receives the message content.


4. Your Task: End-to-End Verification

Now it's time to see the whole system work together.

  1. Start your infrastructure: In your terminal, run docker-compose up to start Kafka, Zookeeper, and the Schema Registry.
  2. Start the producer: Run your auth-service application.
  3. Start the consumer: Run your new notifications-service application. You should have two Spring Boot applications running simultaneously. Your IDE should make it easy to manage multiple running applications.
  4. Trigger the event: Use Postman or curl to send a POST request to your auth-service's registration endpoint (e.g., http://localhost:8080/api/auth/register) with a new user's details.
  5. Observe the logs:
    • Check the logs for the auth-service. You should see the confirmation that the UserRegisteredEvent was sent.
    • Now, check the logs for the notifications-service. You should see the log message from our UserEventConsumer: Received UserRegisteredEvent for user email: ... followed by the "Simulating sending welcome email" message.

Seeing the message appear in the second service's logs confirms that you have successfully built an end-to-end, event-driven communication flow between two microservices!


Debugging-First: Common Errors

A common point of failure in consumer applications is deserialization.

  • Debugging Task: In your notifications-service's application.yml, temporarily change the value-deserializer to org.apache.kafka.common.serialization.StringDeserializer. Restart the service and send a new registration event. Observe the notifications-service logs. You will see a DeserializationException or a ClassCastException. Spring's listener container will try to retry a few times and then stop. This happens because the consumer is trying to interpret binary Avro data as a simple string. Change the deserializer back to io.confluent.kafka.serializers.KafkaAvroDeserializer to fix it.

  • Other Potential Issues:

    • ClassNotFoundException: com.example.blog.events.UserRegisteredEvent: The Avro class wasn't generated. Run mvn clean install.
    • Consumer doesn't receive messages:
      • Check that the topic names in the producer and @KafkaListener match exactly.
      • Ensure the group-id in the annotation and application.yml also match.
      • Verify that all services (Kafka, auth-service, notifications-service) are running without errors.

Conclusion

Excellent work! You have now implemented the consumer side of our event-driven architecture. You created a new, independent service, configured it to consume Avro-formatted events, and used the declarative power of @KafkaListener to process them.

Key Takeaways:

  • The @KafkaListener annotation is the primary mechanism for creating Kafka consumers in Spring.
  • Consumer configuration in application.yml dictates connection details, deserialization, and group behavior.
  • The group-id is fundamental to how Kafka enables consumer scaling and load balancing.
  • Properly configuring deserializers (especially KafkaAvroDeserializer with specific.avro.reader: true) is critical for type-safe message consumption.

Preview of the Next Lesson:

Our current consumer works perfectly for successful scenarios. But what happens if our notifications-service fails to process a message? For example, what if the email service it calls is temporarily down? The message will be lost. In the next lesson, we will address this by implementing an idempotent consumer to prevent duplicate processing and configuring a Dead Letter Queue (DLQ) to capture and sideline messages that repeatedly fail, ensuring no event is ever lost.