Featured Article

Apache Kafka Tutorial Spring Boot: A Comprehensive Guide to Event Streaming

Kenneth Jul 13, 2026

If you're a Java developer keen on leveraging real-time data processing, you've likely heard about Apache Kafka, a distributed streaming platform that's become an industry standard. When combined with Spring Boot, a popular microframework for building stand-alone, production-grade Spring-based applications, Kafka's capabilities truly shine. Let's delve into a comprehensive tutorial on integrating Apache Kafka with Spring Boot.

How To Work With Apache Kafka In Spring Boot?
How To Work With Apache Kafka In Spring Boot?

Before getting started, ensure you have a solid understanding of both Apache Kafka and Spring Boot. If you're new to these, consider familiarizing yourself with them first as this tutorial assumes prior knowledge.

an image of a diagram with the words apache kafka
an image of a diagram with the words apache kafka

Setting Up the Development Environment

The first step involves setting up the development environment. We'll be using Java 8 or later, Maven as the build tool, and an Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse.

Top 10 Apache Kafka Features | What is Apache Kafka? | Apache Kafka Tutorial
Top 10 Apache Kafka Features | What is Apache Kafka? | Apache Kafka Tutorial

Start by creating a new Spring Boot project. Once your project is set up, we'll add Kafka dependencies to our `pom.xml` file. For simplicity, we'll use the popular 'spring-kafka' dependency, which abstracts away many of Kafka's complexities.

Adding Kafka Dependencies

Install Apache Kafka on Amazon EC2 Instance or Linux Operating System? | Hands-on Kafka using CLI
Install Apache Kafka on Amazon EC2 Instance or Linux Operating System? | Hands-on Kafka using CLI

Add the following dependency to your `pom.xml`: ```xml org.springframework.kafka spring-kafka ```

Synch the dependencies to download the necessary libraries. Your project is now ready to leverage Apache Kafka with Spring Boot.

Configuring Kafka Properties

Demystifying Apache Kafka Cluster: Components and Architecture Tutorial | Apache Kafka Tutorial
Demystifying Apache Kafka Cluster: Components and Architecture Tutorial | Apache Kafka Tutorial

Next, we need to configure Kafka properties in our `application.properties` or `application.yml` file. These configuration files support both key-value pair and YAML format.

Example for `application.properties`: ```properties spring.kafka.bootstrap-servers=localhost:9092 spring.kafka.producer.key-serializer=org.apache.kafka comuneer.serialization.StringSerializer spring.kafka.producer.value-serializer=org.apache.kafka comuneer.serialization.StringSerializer ```

In the above configuration, replace `localhost:9092` with your Kafka broker address. The key-serializer and value-serializer should match the types of your key and value.

Event-Driven Microservices using Spring Boot and Kafka
Event-Driven Microservices using Spring Boot and Kafka

Producing Messages with Spring Kafka

Now that our environment is set up, let's dive into producing messages using Spring Kafka. Spring Kafka provides convenient `KafkaTemplate` class for sending messages asynchronously.

Java Consumer code to consume messages from Apache Kafka Server installed in the Amazon EC2 Instance
Java Consumer code to consume messages from Apache Kafka Server installed in the Amazon EC2 Instance
Apache Kafka Cluster Overview: Understanding Components and Architecture | Apache Kafka Tutorial
Apache Kafka Cluster Overview: Understanding Components and Architecture | Apache Kafka Tutorial
Spring Boot Folder Structure: Best Practices and Guide
Spring Boot Folder Structure: Best Practices and Guide
Apache Kafka Tutorial: Complete Pub-Sub Messaging Workflow | Kafka Consumer Groups
Apache Kafka Tutorial: Complete Pub-Sub Messaging Workflow | Kafka Consumer Groups
an image of a web page with the text'apachic kahla architecture cluster
an image of a web page with the text'apachic kahla architecture cluster
How to Install Apache Kafka on Windows or Windows 10/11? | Hands-on Kafka using CLI
How to Install Apache Kafka on Windows or Windows 10/11? | Hands-on Kafka using CLI
Kafka Consumer Groups Explained | The Workflow Behind Kafka
Kafka Consumer Groups Explained | The Workflow Behind Kafka
Apache Kafka Introduction and Apache Kafka Architecture- Overview of Kafka Components | Apache Kafka
Apache Kafka Introduction and Apache Kafka Architecture- Overview of Kafka Components | Apache Kafka
Apache Kafka Producer in Java | Simple Java Kafka Producer Example
Apache Kafka Producer in Java | Simple Java Kafka Producer Example

Here's a simple example of sending a message: ```java @Autowired private KafkaTemplate kafkaTemplate; public void sendMessage(String topic, String key, String payload) { kafkaTemplate.send(topic, key, payload); } ```

In the above code, we're injecting `KafkaTemplate` and using it to send a message to a specified topic. The message's key and payload are also provided.

Sending a Synchronous Message

If you need to send a message synchronously (waiting for an acknowledgment from the broker), you can do so using `sendAndReceive()` method: ```java Future> future = kafkaTemplate.sendAndReceive(topic, key, payload); String receivedPayload = future.get().value(); ```

In this example, we're sending a message and awaiting the result. Once the result is available, we retrieve the received payload.

Producing Messages asynchronously

Spring Kafka supports async processing by default. You can leverage this in two ways: by providing a callback or by listening for a response.

When using a callback, pass a `SendCallback` to the `send()` method. When the message is successfully sent, the callback's `onSuccess()` method will be invoked. ```java kafkaTemplate.send(topic, key, payload, new SendCallback() { @Override public void onSuccess(SendResult sendResult) { System.out.println("Message sent successfully to topic: " + sendResult.getRecordMetadata().topic()); } @Override public void onError(Throwable ex) { System.out.println("Sending message failed: " + ex.getMessage()); } }); ```

The `onError()` method will be invoked if an error occurs during sending.

Consuming Messages with Spring Kafka

Now that we've seen how to produce messages, let's look at consuming them. Spring Kafka provides a convenient listener container for consuming messages.

Defining the KafkaListener

You can define a `KafkaListener` using the `@KafkaListener` annotation, which should be applied to a method or a class with a single method. The annotated method will receive messages from a specific topic.

Here's an example: ```java @KafkaListener(topics = "myTopic", groupId = "myGroup") public void listen(String message) { System.out.println("Received message: " + message); } ```

In this case, we're consuming messages from the `myTopic` topic. The groupId must be unique for each listener in a group.

Configuring the KafkaListener

You can configure the `KafkaListener` using its attributes or by providing a `ContainerProperties` bean. For example, you can set the concurrency (number of threads) to improve throughput: ```java @Bean public ConsumerFactory consumerFactory() { Map props = new HashMap<>(); // configure here return new DefaultKafkaConsumerFactory<>(props); } @Bean public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory()); factory.setConcurrency(3); // set concurrency return factory; } ```

The listener will now consume messages using 3 threads.

Handling Exceptions

When consuming messages, it's important to handle exceptions. You can use the `RetryTemplate` and `RecoveryCallback` for handling transient errors: ```java @Bean public RetryTemplate retryTemplate() { RetryTemplate template = new RetryTemplate(); template.setRetryStrategy(new SimpleRetryStrategy(3)); return template; } @Bean public RecoveryCallback recoveryCallback() { return RecoveryCallback.wrap(retryCallback ConcurrentMessageListenerContainer.MANDATORY.fail()); } ```

The above example configures a `RetryTemplate` that will retry consuming a message up to 3 times. If a message cannot be consumed after 3 retries, it will be sent to the `DlqTopic` (Dead Letter Queue).

Spring Kafka provides extensive functionality for producing and consuming messages, making it an excellent choice for large-scale, distributed systems. By leveraging Spring Kafka with Spring Boot, you can build robust, scalable, and maintainable applications.

Now that you've seen how to integrate Apache Kafka with Spring Boot, it's time to put your skills into practice. Start by building a simple application that produces and consumes messages. As you gain more experience, consider building more complex applications, such as real-time analytics services or stream processing applications.