Skip to main content

Welcome to a Grasp lesson

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

Lesson 44

Publishing Registration Events with Kafka Producers

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

Hello! In our last lesson, we designed the data contract for our UserRegisteredEvent using Avro and explored the role of the Schema Registry. We now have a blueprint for our events and the local Kafka infrastructure to support them.

Today, we'll bring that design to life. This lesson focuses on implementing the producer side of our event-driven flow. You will modify the Auth Service to publish a UserRegisteredEvent to a Kafka topic immediately after a new user successfully registers. This is the first concrete step in decoupling our services.

Introduction: From Schema to Action

In the MERN world, after defining a data shape with TypeScript or Zod, you'd use a library like kafkajs to create a producer instance, connect to the broker, and send a JSON payload.

In Spring Boot, the ecosystem provides a powerful abstraction called spring-kafka. We won't manage the producer lifecycle manually; instead, we'll configure it and then inject a ready-to-use helper object called KafkaTemplate. This template will handle the complexities of serialization, connection management, and sending messages, allowing us to focus purely on the business logic.

Our goal is to hook into the user registration process and fire off a UserRegisteredEvent containing the new user's ID, email, and registration time.

Spring Boot Kafka Producer-Consumer Architecture
This diagram illustrates the architecture we're beginning to build. Our Spring Boot application will act as the "Producer," sending a message (our event) to the Kafka Cluster. In a future lesson, another service will act as the "Consumer."

Step 1: Configuring Your Project for Kafka and Avro

Before we write any producer code, we need to configure our project to understand Kafka and, more specifically, to handle Avro-formatted data. This involves two parts: updating our Maven dependencies and our application configuration.

Maven Dependencies (pom.xml)

We need to add three key components to our pom.xml:

  1. spring-kafka: The core library for Spring and Kafka integration.
  2. kafka-avro-serializer: Confluent's library that provides the KafkaAvroSerializer. This is what will convert our Java objects into Avro binary format, using the schema from the Schema Registry.
  3. avro-maven-plugin: A tool that automatically generates Java classes from our .avsc schema files during the build process. This gives us compile-time type safety.

Please add the following to your pom.xml:

  1. Dependencies Block: Ensure spring-kafka is present and add the Avro serializer.

    <dependencies>
        <!-- ... other dependencies ... -->
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>
        <dependency>
            <groupId>io.confluent</groupId>
            <artifactId>kafka-avro-serializer</artifactId>
            <version>7.5.0</version> <!-- Use a recent version -->
        </dependency>
        <!-- ... other dependencies ... -->
    </dependencies>
    
  2. Repository for Confluent: Confluent's artifacts are not in the central Maven repository, so we need to tell Maven where to find them.

    <repositories>
        <!-- ... other repositories ... -->
        <repository>
            <id>confluent</id>
            <url>https://packages.confluent.io/maven/</url>
        </repository>
    </repositories>
    
  3. Build Plugin: This plugin will find our UserRegisteredEvent.avsc and generate a corresponding UserRegisteredEvent.java class.

    <build>
        <plugins>
            <!-- ... other plugins ... -->
            <plugin>
                <groupId>org.apache.avro</groupId>
                <artifactId>avro-maven-plugin</artifactId>
                <version>1.11.3</version> <!-- Use a recent version -->
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>schema</goal>
                        </goals>
                        <configuration>
                            <sourceDirectory>${project.basedir}/src/main/avro/</sourceDirectory>
                            <outputDirectory>${project.build.directory}/generated-sources/avro/</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    

After adding this configuration, run mvn clean install from your terminal in the project root, or let your IDE sync the Maven changes. This will trigger the avro-maven-plugin and generate our event class. You can find it under the target/generated-sources/avro directory. Your IDE will automatically add this to the project's classpath, making the UserRegisteredEvent class available to use in your code.

Application Configuration (application.yml)

Now, let's tell our Spring application how to connect to Kafka and use our Avro serializer. Add the following configuration to your src/main/resources/application.yml:

spring:
  kafka:
    bootstrap-servers: localhost:9092 # Points to the Kafka broker in Docker
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: io.confluent.kafka.serializers.KafkaAvroSerializer
      properties:
        schema.registry.url: http://localhost:8081 # Points to the Schema Registry in Docker

Let's break this down:

  • bootstrap-servers: The address of our Kafka broker.
  • key-serializer: We'll use a simple String for our message keys.
  • value-serializer: This is the crucial part. We're telling Kafka to use Confluent's KafkaAvroSerializer for the message value. This serializer will automatically communicate with the Schema Registry to register schemas and serialize our UserRegisteredEvent object.
  • schema.registry.url: The location of our Schema Registry service.

To see how this configuration is used, let's watch a short segment on configuring a producer. The video uses a plain string message, but the configuration principles are the same.

Apache Kafka® Producer Example using SpringBoot 3.x | Java Techie

The video 'Apache Kafka® Producer Example' by Java Techie demonstrates how to configure the Kafka producer properties in a Spring Boot application.

Watch from 04:00 to 05:13. This section shows how to set up the producer bootstrap server in application.yml. Note that we are using additional properties for the serializer and schema registry, which is standard for production-grade applications.


Step 2: Implementing the Kafka Producer Service

With the configuration in place, Spring Boot will automatically create a KafkaTemplate bean for us. Now, we can create a dedicated service to encapsulate the logic of sending our event.

  1. Create a UserEventProducer service: Create a new Java class UserEventProducer.java in a suitable package (e.g., com.example.blog.kafka).

  2. Inject KafkaTemplate: The KafkaTemplate is generic. We specify that its key is a String and its value is our auto-generated UserRegisteredEvent class.

  3. Create the sendUserRegisteredEvent method: This method will take our domain User object, map it to the UserRegisteredEvent DTO, and send it.

Here is the full implementation:

package com.example.blog.kafka;

import com.example.blog.events.UserRegisteredEvent;
import com.example.blog.model.User; // Assuming you have a User model
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.concurrent.CompletableFuture;

@Service
public class UserEventProducer {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserEventProducer.class);
    private static final String TOPIC_NAME = "user-registered-events";

    private final KafkaTemplate<String, UserRegisteredEvent> kafkaTemplate;

    @Autowired
    public UserEventProducer(KafkaTemplate<String, UserRegisteredEvent> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    public void sendUserRegisteredEvent(User user) {
        // Create the event object from our generated Avro class
        UserRegisteredEvent event = UserRegisteredEvent.newBuilder()
                .setUserId(user.getId().toString()) // Assuming user ID is a UUID or Long
                .setEmail(user.getEmail())
                .setRegisteredAt(Instant.now().toEpochMilli())
                .build();

        // The user's ID is a good candidate for the message key.
        // All events for the same user will go to the same partition.
        String key = user.getId().toString();

        CompletableFuture<Void> future = kafkaTemplate.send(TOPIC_NAME, key, event)
            .whenComplete((result, ex) -> {
                if (ex == null) {
                    LOGGER.info("UserRegisteredEvent sent for user [{}]. Message offset: {}", 
                                key, result.getRecordMetadata().offset());
                } else {
                    LOGGER.error("Failed to send UserRegisteredEvent for user [{}]. Exception: {}",
                                key, ex.getMessage());
                }
            });
    }
}

Key Concepts in this Code:

  • KafkaTemplate<String, UserRegisteredEvent>: This is Spring's wrapper around the native Kafka producer. Because we configured the KafkaAvroSerializer, this template knows how to handle our UserRegisteredEvent object.
  • Asynchronous Sending: kafkaTemplate.send() is non-blocking. It returns a CompletableFuture, which is Java's equivalent of a JavaScript Promise.
  • Callback (whenComplete): We attach a callback to handle the result. This is essential for production systems to log whether the message was successfully delivered or if an error occurred. This is conceptually similar to using .then().catch() or async/await with try/catch in JavaScript.

The following resource provides excellent textual examples of using KafkaTemplate with custom objects and callbacks. The examples use JSON, but the KafkaTemplate API and callback logic are identical for Avro.

Using Kafka with Spring Boot - Reflectoring

The article 'Using Kafka with Spring Boot' from Reflectoring provides clear code snippets for sending messages with KafkaTemplate.

Please read the sections 'Sending Messages' (specifically 'Using KafkaTemplate') and 'Custom Messages' (specifically 'Configuring JSON Serializer & Deserializer' and 'Sending Java Objects'). This will solidify your understanding of how KafkaTemplate works with custom objects and asynchronous callbacks.


Step 3: Integrating with the User Registration Flow

Now we just need to call our new producer from the AuthService (or whichever service handles user creation).

  1. Inject UserEventProducer into your AuthService.
  2. In your register method, after the new user has been successfully saved to the database, call userEventProducer.sendUserRegisteredEvent(savedUser).
// In your AuthService.java or similar service

@Service
public class AuthService {

    // ... your existing dependencies like UserRepository, PasswordEncoder ...

    private final UserEventProducer userEventProducer;

    @Autowired
    public AuthService(/*...,*/ UserEventProducer userEventProducer) {
        // ...
        this.userEventProducer = userEventProducer;
    }

    @Transactional
    public User registerUser(RegisterRequestDto requestDto) {
        // ... existing logic to create and validate user ...
        
        // Save the user to the database
        User savedUser = userRepository.save(newUser);

        // *** Publish the event AFTER the transaction commits successfully ***
        // For now, we call it directly. We will improve this later with transactional outbox pattern.
        userEventProducer.sendUserRegisteredEvent(savedUser);

        return savedUser;
    }
}

Placing the event publication after the database save is critical. You don't want to announce a user registration that never actually got persisted.


Your Task: Runtime Observation and Debugging

It's time to see your code in action.

  1. Ensure your environment is running: Use docker-compose up to start Kafka, Zookeeper, and the Schema Registry.

  2. Build the project: Run mvn clean install one more time to ensure the Avro classes are generated and the project is compiled.

  3. Start the Spring Boot application.

  4. Trigger the registration: Use Postman or curl to send a request to your user registration endpoint (POST /api/auth/register).

  5. Check the application logs: You should see the log message from our whenComplete callback: INFO: UserRegisteredEvent sent for user [...]. This is your first confirmation.

  6. Verify the message in Kafka: This is the definitive proof. The message is in Avro format, so a standard consumer won't work. We need the kafka-avro-console-consumer provided by the Confluent Docker image. Open a new terminal and run:

    docker exec -it schema-registry kafka-avro-console-consumer \
        --bootstrap-server broker:9092 \
        --topic user-registered-events \
        --from-beginning
    

    Note: schema-registry is the name of the container in our docker-compose.yml that has the tool, and broker:9092 is the Kafka address inside the Docker network.

    You should see the event output as a JSON object, beautifully deserialized for you!

    {"userId":"...","email":"test@example.com","registeredAt":1678886400000}
    

Common Bugs and How to Fix Them

  • SerializationException: Error registering schema: This usually means your application can't reach the Schema Registry. Check that schema.registry.url in application.yml is correct and that the schema-registry container is running and healthy.
  • ConnectException or TimeoutException on startup: Your application can't reach the Kafka broker. Check that the bootstrap-servers address is correct and the broker container is running.
  • ClassNotFoundException: com.example.blog.events.UserRegisteredEvent: The Avro class was not generated or not found on the classpath. Make sure your avro-maven-plugin configuration is correct and you've run mvn clean install.

Conclusion

Congratulations! You have successfully implemented a Kafka producer in a Spring Boot application. You've configured your project for Avro serialization, used the KafkaTemplate to send a strongly-typed event, and verified the entire flow from an API request to a message in a Kafka topic.

Key Takeaways:

  • Spring Boot's auto-configuration greatly simplifies Kafka producer setup via application.yml.
  • The kafka-avro-serializer combined with the Schema Registry provides robust, schema-enforced serialization.
  • The avro-maven-plugin bridges the gap between schema definition (.avsc) and type-safe Java code.
  • KafkaTemplate is the primary tool for producing messages, and its asynchronous nature with callbacks is a production-ready pattern.

Preview of the Next Lesson:

An event is only useful if someone is listening. In our next lesson, we will implement a Kafka consumer. You will create a new, separate service (a "Notifications" service) that subscribes to the user-registered-events topic using the @KafkaListener annotation and processes the event, for example, by logging a message simulating a welcome email being sent.