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.
- Update
pom.xml: Your newnotifications-service/pom.xmlwill need dependencies forspring-kafka,kafka-avro-serializer, and theavro-maven-plugin. The configuration will be nearly identical to the one you added to theauth-servicein the last lesson. This is because the consumer also needs to understand the Avro format and generate theUserRegisteredEventclass. - Copy the Avro Schema: Copy the
UserRegisteredEvent.avscfile fromauth-service/src/main/avro/tonotifications-service/src/main/avro/. This ensures both services are working from the exact same event contract. - Build the Project: Run
mvn clean installfrom your project's root directory to generate theUserRegisteredEvent.javaclass inside your newnotifications-servicemodule.
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 samegroup-idwork 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.earliestmeans it will read all messages from the beginning of the topic, which is perfect for development and testing. The other common value islatest, 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 useStringDeserializerfor the key andKafkaAvroDeserializerfor our Avro-formatted value.specific.avro.reader: true: This is a crucial property for theKafkaAvroDeserializer. 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 aClassCastException.
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 theconsumemethod 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 thegroup-idin yourapplication.yml.
public void consume(UserRegisteredEvent event): The method signature is key. Spring Kafka, using the configuredKafkaAvroDeserializer, automatically deserializes the message payload into aUserRegisteredEventobject 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.

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.
- Start your infrastructure: In your terminal, run
docker-compose upto start Kafka, Zookeeper, and the Schema Registry. - Start the producer: Run your
auth-serviceapplication. - Start the consumer: Run your new
notifications-serviceapplication. You should have two Spring Boot applications running simultaneously. Your IDE should make it easy to manage multiple running applications. - Trigger the event: Use Postman or
curlto send aPOSTrequest to yourauth-service's registration endpoint (e.g.,http://localhost:8080/api/auth/register) with a new user's details. - Observe the logs:
- Check the logs for the
auth-service. You should see the confirmation that theUserRegisteredEventwas sent. - Now, check the logs for the
notifications-service. You should see the log message from ourUserEventConsumer:Received UserRegisteredEvent for user email: ...followed by the "Simulating sending welcome email" message.
- Check the logs for the
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'sapplication.yml, temporarily change thevalue-deserializertoorg.apache.kafka.common.serialization.StringDeserializer. Restart the service and send a new registration event. Observe thenotifications-servicelogs. You will see aDeserializationExceptionor aClassCastException. 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 toio.confluent.kafka.serializers.KafkaAvroDeserializerto fix it. -
Other Potential Issues:
ClassNotFoundException: com.example.blog.events.UserRegisteredEvent: The Avro class wasn't generated. Runmvn clean install.- Consumer doesn't receive messages:
- Check that the topic names in the producer and
@KafkaListenermatch exactly. - Ensure the
group-idin the annotation andapplication.ymlalso match. - Verify that all services (Kafka,
auth-service,notifications-service) are running without errors.
- Check that the topic names in the producer and
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
@KafkaListenerannotation is the primary mechanism for creating Kafka consumers in Spring. - Consumer configuration in
application.ymldictates connection details, deserialization, and group behavior. - The
group-idis fundamental to how Kafka enables consumer scaling and load balancing. - Properly configuring deserializers (especially
KafkaAvroDeserializerwithspecific.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.