00:00

Apache Kafka with Spring Boot

Last updated:

Spring for Apache Kafka (Spring Kafka) brings Kafka to the Spring programming model, and Spring Boot configures it for you. You get a ready KafkaTemplate for sending, annotation-driven listeners for receiving, and configuration from application.yml instead of hand-built Properties objects.

This tutorial builds a small order service with Spring Boot 4.2: it publishes an OrderPlaced event as JSON and consumes it in a listener. It also shows how to create topics on startup and how to test with an embedded KRaft broker.

1. What Is Spring for Apache Kafka?

Spring Kafka is a Spring project that wraps the official Kafka Java client. Its main parts are:

  • KafkaTemplate, a thread-safe wrapper around KafkaProducer.
  • @KafkaListener and listener containers, which run the consumer poll loop, call your method for each record and commit offsets.
  • Error handlers, retry topics, transactions and test utilities.
Versions: Spring Boot 4.2 manages Spring for Apache Kafka 4.2 and kafka-clients 4.4. Spring Kafka 4.x requires Java 17 or later. In Boot 4, add spring-boot-starter-kafka; Boot 3 used the plain spring-kafka dependency.

2. Why Use Spring Boot with Kafka?

  • Less boilerplate: no manual poll loop, threading or commit code.
  • Externalised configuration: spring.kafka.* properties per environment.
  • Spring integration: dependency injection, transactions, metrics through Micrometer and health checks.
  • Built-in reliability features: DefaultErrorHandler, dead-letter publishing and non-blocking retries (see Exception Handling in Apache Kafka).

3. How It Works

Spring Boot Kafka application flowOrderService calls KafkaTemplate.send, which uses a producer created by the auto-configured ProducerFactory and serializes the record to JSON. The record goes to the orders topic on the Kafka cluster. A listener container created from the ConsumerFactory polls the topic, deserializes the JSON and invokes the @KafkaListener method in OrderListener, then commits the offset. Spring Boot app OrderService KafkaTemplateJacksonJsonSerializer Kafka clustertopic: orders send Spring Boot app listener containerpoll, deserialize, commit @KafkaListener method poll
Spring Boot creates the producer and consumer factories from application.yml; you write only the service and the listener method.

Spring Boot's auto-configuration reads spring.kafka.* properties and creates a ProducerFactory, a KafkaTemplate, a ConsumerFactory, a KafkaAdmin and a ConcurrentKafkaListenerContainerFactory. For each @KafkaListener, a container runs a consumer on its own thread and calls your method.

4. Step-by-Step Example

4.1 1. Maven dependencies

pom.xml
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.2.0</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-kafka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jackson</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-kafka-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

4.2 2. Configuration

application.yml
spring:
  kafka:
    bootstrap-servers: localhost:9092
    producer:
      value-serializer: org.springframework.kafka.support.serializer.JacksonJsonSerializer
    consumer:
      group-id: order-notifier
      auto-offset-reset: earliest
      value-deserializer: org.springframework.kafka.support.serializer.JacksonJsonDeserializer
      properties:
        spring.json.trusted.packages: com.javabytechie.kafka

Keys use the default StringSerializer. The JSON deserializer reads the target class from a type header that the serializer adds, and only creates classes from trusted packages.

4.3 3. The event and the topic

OrderPlaced.java
package com.javabytechie.kafka;

public record OrderPlaced(String orderId, String customer, double total) {
}
KafkaTopicConfig.java
package com.javabytechie.kafka;

import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.TopicBuilder;

@Configuration
public class KafkaTopicConfig {

    @Bean
    public NewTopic ordersTopic() {
        return TopicBuilder.name("orders").partitions(3).replicas(1).build();
    }
}

KafkaAdmin creates the topic at startup if it does not exist. Use 3 replicas in production.

4.4 4. Producer service

OrderService.java
package com.javabytechie.kafka;

import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
public class OrderService {

    private final KafkaTemplate<String, OrderPlaced> kafkaTemplate;

    public OrderService(KafkaTemplate<String, OrderPlaced> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    public void placeOrder(OrderPlaced order) {
        kafkaTemplate.send("orders", order.orderId(), order)
                .whenComplete((result, ex) -> {
                    if (ex != null) {
                        System.out.println("Send failed for " + order.orderId() + ": " + ex.getMessage());
                    } else {
                        System.out.println("Sent " + order.orderId() + " to partition "
                                + result.getRecordMetadata().partition());
                    }
                });
    }
}

send() returns a CompletableFuture<SendResult<K, V>>. Using the order ID as the key keeps all events of one order in the same partition.

4.5 5. Consumer

OrderListener.java
package com.javabytechie.kafka;

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

@Component
public class OrderListener {

    @KafkaListener(topics = "orders")
    public void onOrder(OrderPlaced order, @Header(KafkaHeaders.RECEIVED_PARTITION) int partition) {
        System.out.println("Notify " + order.customer() + ": order " + order.orderId()
                + " (" + order.total() + ") from partition " + partition);
    }
}

The group ID comes from spring.kafka.consumer.group-id. After the method returns, the container commits the offset (the default AckMode.BATCH commits after each poll's records are processed).

4.6 6. Application

OrderApplication.java
package com.javabytechie.kafka;

import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class OrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }

    @Bean
    ApplicationRunner demo(OrderService orders) {
        return args -> orders.placeOrder(new OrderPlaced("ORD-7001", "Asha", 1499.0));
    }
}

Output (Spring Boot 4.2.0 with a local Kafka 4.4 broker; Spring's startup logs omitted):

Output
Sent ORD-7001 to partition 0
Notify Asha: order ORD-7001 (1499.0) from partition 0

The producer callback prints the partition chosen from the key, and the listener receives the JSON payload already converted back to an OrderPlaced record. On your machine the partition number may differ, because it depends on the key hash and the partition count.

4.7 7. Testing with an embedded broker

@EmbeddedKafka starts an in-memory KRaft broker for tests, and ${spring.embedded.kafka.brokers} points the application at it:

OrderServiceTest.java
package com.javabytechie.kafka;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.test.context.EmbeddedKafka;

@SpringBootTest(properties = "spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}")
@EmbeddedKafka(partitions = 1, topics = "orders")
class OrderServiceTest {

    @Autowired
    OrderService orderService;

    @Test
    void publishesOrder() {
        orderService.placeOrder(new OrderPlaced("ORD-1", "Test", 10.0));
    }
}

For assertions, consume from the topic in the test with KafkaTestUtils.getSingleRecord(...), or use Testcontainers when you need a production-like broker.

5. Useful Spring Boot Properties

PropertyPurpose
spring.kafka.bootstrap-serversBroker addresses
spring.kafka.producer.acksProducer acknowledgements (Kafka default all)
spring.kafka.producer.properties.*Any other producer config, for example linger.ms
spring.kafka.consumer.group-idDefault group for listeners
spring.kafka.consumer.auto-offset-resetStart position for a new group
spring.kafka.listener.concurrencyConsumers per listener container
spring.kafka.listener.ack-modeWhen the container commits offsets

6. Common Mistakes

  • Using the deprecated JsonSerializer and JsonDeserializer in Spring Kafka 4; they are based on Jackson 2. Use JacksonJsonSerializer and JacksonJsonDeserializer (Jackson 3).
  • Forgetting spring.json.trusted.packages, which makes deserialization fail with "The class is not in the trusted packages".
  • Calling send(...).get() in a request thread, which blocks; react to the future instead.
  • Setting enable.auto.commit=true on Spring consumers; the container should manage commits.
  • One poison record stopping a listener: configure an error handler and dead-letter topic.

7. Best Practices

  • Keep listener methods small and delegate business logic to services that you can test without Kafka.
  • Set concurrency to the number of partitions per instance you want to process in parallel.
  • Wrap deserializers in ErrorHandlingDeserializer so bad payloads go to the error handler instead of looping.
  • Use typed records such as Java records for events, and version their schema.

8. Conclusion

With Spring Boot, a Kafka producer is an injected KafkaTemplate and a consumer is a method annotated with @KafkaListener, both configured from application.yml. Spring Boot 4.2 manages Spring Kafka 4.2 and Kafka clients 4.4, and uses Jackson 3 for JSON. Continue with Kafka Retry Mechanism to make your listeners resilient.

9. References