Apache Kafka with Spring Boot
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 aroundKafkaProducer.@KafkaListenerand 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.
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
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
<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
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
package com.javabytechie.kafka;
public record OrderPlaced(String orderId, String customer, double total) {
}
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
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
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
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):
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:
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
| Property | Purpose |
|---|---|
spring.kafka.bootstrap-servers | Broker addresses |
spring.kafka.producer.acks | Producer acknowledgements (Kafka default all) |
spring.kafka.producer.properties.* | Any other producer config, for example linger.ms |
spring.kafka.consumer.group-id | Default group for listeners |
spring.kafka.consumer.auto-offset-reset | Start position for a new group |
spring.kafka.listener.concurrency | Consumers per listener container |
spring.kafka.listener.ack-mode | When the container commits offsets |
6. Common Mistakes
- Using the deprecated
JsonSerializerandJsonDeserializerin Spring Kafka 4; they are based on Jackson 2. UseJacksonJsonSerializerandJacksonJsonDeserializer(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=trueon 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
concurrencyto the number of partitions per instance you want to process in parallel. - Wrap deserializers in
ErrorHandlingDeserializerso 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
Kafka with Spring Boot Interview Questions and Answers
Common interview questions on Kafka with Spring Boot, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What does Spring Boot auto-configure for Kafka?
Answer: From spring.kafka.* properties it creates a ProducerFactory and KafkaTemplate, a ConsumerFactory, a ConcurrentKafkaListenerContainerFactory used by @KafkaListener, and a KafkaAdmin that creates NewTopic beans at startup. You can override any of these by declaring your own bean.
Q. What does KafkaTemplate.send() return in Spring Kafka 3 and later?
Answer: A CompletableFuture<SendResult<K, V>>. SendResult contains the ProducerRecord and the RecordMetadata with partition and offset. Older versions returned a ListenableFuture, which has been removed.
Intermediate questions
Q. How does the listener container commit offsets by default?
Answer: Spring disables the client's auto commit and commits itself. With the default AckMode.BATCH, the container commits the offsets of all records returned by one poll() after the listener has processed them. Other modes include RECORD, TIME, COUNT, MANUAL and MANUAL_IMMEDIATE.
Q. How do you consume JSON into a Java record safely?
Answer: Use JacksonJsonDeserializer with spring.json.trusted.packages limited to your event package, or set spring.json.value.default.type when the producer does not send type headers. Wrap it in ErrorHandlingDeserializer so invalid JSON is passed to the error handler instead of failing every poll.
Tricky and scenario questions
Q. Your @KafkaListener has concurrency 6 but only 3 threads receive records. Why?
Answer: The topic probably has three partitions. Each of the six consumers created by the container joins the same group, and a partition is assigned to only one of them, so three consumers stay idle. Increase the partition count or reduce concurrency.
Q. How would you send to Kafka only when a database transaction commits?
Answer: Either use the transactional outbox pattern, writing the event to a table in the same database transaction and publishing it afterwards (for example with Debezium), or send from a @TransactionalEventListener(phase = AFTER_COMMIT). Spring's Kafka transactions synchronise with a database transaction, but they are not an atomic two-phase commit, so the outbox is the safer choice.