Hello! Welcome to the first lesson in our new module, "Event-Driven Architecture with Kafka."
Congratulations on building a complete, production-grade authentication service in the previous module! You've successfully implemented secure registration, login with JWTs, token refresh, and a robust logout mechanism. You now have a solid foundation in securing Spring Boot APIs.
So far, all communication in our application has been synchronous (request-response). This is great for many use cases, but modern distributed systems often rely on a different pattern: Event-Driven Architecture (EDA). Instead of one service directly calling another and waiting for a response, services communicate asynchronously by producing and consuming events. This decouples services, improves scalability, and builds resilience.
In this lesson, we will tackle our first step into this new world by focusing on the learning outcome: Set up Apache Kafka and a schema registry locally using a Docker Compose file. We'll get the core infrastructure for our event-driven features up and running, preparing our local environment for the exciting work ahead.
Core Concepts of Our Kafka Stack
Before we write any code, let's understand the key players in our setup. In an event-driven system, components communicate via messages or "events." Kafka is the platform that manages the flow of these events.
- Broker: This is the Kafka server itself. It receives events from producers and stores them durably.
- Producer: An application that sends (produces) events to a Kafka topic. In our project, the
Auth servicewill become a producer. - Consumer: An application that reads (consumes) events from a Kafka topic. We'll later build a
Notification servicethat will be a consumer. - Topic: A named category or stream of events. For example, we'll create a
user-registered-eventstopic.
MERN-to-Spring Mapping: Persistent, Distributed Events
In the Node.js world, you might be familiar with the in-memory EventEmitter for handling events within a single application process. Think of Kafka as a powerful, distributed, and persistent version of this. Instead of events disappearing once handled, they are stored durably in topics and can be consumed by multiple, independent services, even if those services were offline when the event was produced.
For our local development, we'll run all the necessary components as Docker containers, orchestrated by a single docker-compose.yml file.
Two other critical components we'll set up are:
- Schema Registry: What happens if our
Auth servicechanges the structure of aUserRegisteredevent? TheNotification servicemight break. The Schema Registry prevents this. It acts as a central repository for the "schemas" (the data structure) of our events. It ensures that producers and consumers agree on the event format, providing a form of runtime type-safety for your event streams. This is analogous to sharing TypeScript interfaces between different parts of a frontend application, but enforced at the infrastructure level. - Kafka UI: A web-based tool that allows us to see our Kafka cluster, inspect topics, view messages, and manage consumers. It's an indispensable tool for development and debugging, much like Postman is for REST APIs or a database client is for PostgreSQL.
Building the Docker Compose File
We will use docker-compose to define and run our local Kafka environment. For this, we'll use a modern Kafka setup that uses KRaft mode, which simplifies the architecture by removing the need for a separate Zookeeper instance for cluster coordination.
Let's create the docker-compose.yml file. You can place this in the root directory of your Spring Boot project for now.
# docker-compose.yml
version: '3.8'
services:
kafka:
image: apache/kafka:3.7.0
container_name: kafka
ports:
- "9092:9092"
environment:
KAFKA_NODE_ID: 1
KAFKA_PROCESS_ROLES: 'broker,controller'
KAFKA_LISTENERS: 'PLAINTEXT://0.0.0.0:9092,CONTROLLER://kafka:9093'
KAFKA_ADVERTISED_LISTENERS: 'PLAINTEXT://kafka:9092'
KAFKA_CONTROLLER_LISTENER_NAMES: 'CONTROLLER'
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: 'CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT'
KAFKA_CONTROLLER_QUORUM_VOTERS: '1@kafka:9093'
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
volumes:
- kafka-data:/var/lib/kafka/data
networks:
- kafka-network
schema-registry:
image: confluentinc/cp-schema-registry:7.6.0
container_name: schema-registry
ports:
- "8081:8081"
environment:
SCHEMA_REGISTRY_HOST_NAME: schema-registry
SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: 'kafka:9092'
SCHEMA_REGISTRY_LISTENERS: 'http://0.0.0.0:8081'
depends_on:
- kafka
networks:
- kafka-network
kafka-ui:
image: provectuslabs/kafka-ui:latest
container_name: kafka-ui
ports:
- "8080:8080"
environment:
KAFKA_CLUSTERS_0_NAME: 'local'
KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: 'kafka:9092'
KAFKA_CLUSTERS_0_SCHEMAREGISTRY: 'http://schema-registry:8081'
DYNAMIC_CONFIG_ENABLED: 'true'
depends_on:
- kafka
- schema-registry
networks:
- kafka-network
volumes:
kafka-data:
networks:
kafka-network:
driver: bridge
The article below provides more context on this configuration. You can refer to it if you want to dig deeper into the different options.
How to Run Kafka in Docker and Docker Compose
The article 'How to Run Kafka in Docker and Docker Compose' from OneUptime provides an excellent, up-to-date guide on setting up Kafka with KRaft. The docker-compose.yml file above is a combination of the examples shown in this article.
Scan through the sections 'Basic docker-compose.yml', 'Adding Kafka UI for Management', and 'Using Kafka with Schema Registry'. Notice how the final configuration we are using combines these three services into a single file. Pay attention to the environment variables used for each service, as they define how the services connect to each other.
Configuration Breakdown:
kafkaservice: This is the Kafka broker.KAFKA_PROCESS_ROLES: 'broker,controller': This tells Kafka to run in KRaft mode, acting as both a broker and its own controller.KAFKA_ADVERTISED_LISTENERS: 'PLAINTEXT://kafka:9092': This is the address that Kafka will tell other services inside the Docker network to use to connect to it.kafkais the service name.ports: - "9092:9092": This exposes the Kafka broker on port9092to your host machine, which will be useful for connecting our Spring application directly during development.
schema-registryservice:SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: 'kafka:9092': This tells the Schema Registry how to find the Kafka broker. It uses the internal Docker network namekafka.depends_on: - kafka: This ensures Docker starts Kafka before starting the Schema Registry.
kafka-uiservice:KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: 'kafka:9092': Tells the UI how to connect to the Kafka broker.KAFKA_CLUSTERS_0_SCHEMAREGISTRY: 'http://schema-registry:8081': Tells the UI how to connect to the Schema Registry.
Launching and Verifying the Environment
Now for the rewarding part: let's bring our Kafka stack to life.
-
Launch the Services:
Open a terminal in the directory containing yourdocker-compose.ymlfile and run:docker-compose up -dThis command starts all the services in detached mode (
-d). -
Runtime Observation & Debugging:
After a minute, check that all containers are running and healthy.docker-compose psYou should see three containers (
kafka,schema-registry,kafka-ui) with aStateofUp.If a container is not running, check its logs for errors. For example, to check the Kafka logs:
docker logs kafkaA common error is a port conflict if another service on your machine is already using port 9092, 8080, or 8081.
-
Verification Task:
Let's confirm everything is working as expected.-
Step 1: Check the UI
Open your web browser and navigate tohttp://localhost:8080. You should see the Kafka UI dashboard. On the left, you'll see your cluster information. Initially, there will be no topics. -
Step 2: Create a Topic using Command-Line Tools
To be sure Kafka is fully functional, let's create a topic manually. We'll execute a command inside thekafkacontainer.docker exec -it kafka /opt/kafka/bin/kafka-topics.sh \ --bootstrap-server kafka:9092 \ --create \ --topic test-topic \ --partitions 1 \ --replication-factor 1This command uses Kafka's built-in topic management script to create a new topic named
test-topic. -
Step 3: Verify in the UI
Go back to the Kafka UI in your browser (http://localhost:8080). Refresh the page, and click on the "Topics" tab. You should now seetest-topicin the list.
If you see the topic, your local Kafka environment is successfully up and running!
-
Conclusion
In this lesson, you've successfully set up a complete, production-style local Kafka environment using Docker Compose. This is a critical piece of infrastructure for building our event-driven features.
Key Takeaways:
- An event-driven architecture uses producers and consumers that communicate asynchronously via a message broker like Kafka.
docker-composeis an excellent tool for orchestrating multi-service development environments, including Kafka, a Schema Registry, and a UI.- The Schema Registry enforces data contracts between services, preventing data-related bugs in a distributed system.
- Understanding Kafka's networking (
advertised.listeners) is key to configuring connections between containers and the host machine.
Preview of the Next Lesson:
With our infrastructure in place, we're ready to connect our application to it. In the next lesson, we will design an event schema for a 'user registered' event. We'll then modify our Auth service to act as a Kafka producer, publishing an event to a Kafka topic every time a new user successfully registers. This will be our first concrete step in building an event-driven flow.