# Practical Kafka Implementation in Spring Boot Microservices
Mid-to-senior developers can quickly deploy a Kafka cluster using KRaft and integrate it with four Spring Boot services for an online store. The order-service accepts orders via REST API and publishes an order-placed event. The inventory-service reserves stock and generates inventory-reserved or inventory-rejected events. The analytics-service and notification-service process these events asynchronously.
Requirements: Java, Spring Boot, Docker, Docker Compose, Postman. Dependencies: Spring for Apache Kafka, Spring Web.
Docker Compose for Kafka Cluster
Deploying three Kafka 8.1.0 brokers with KRaft without Zookeeper. Each broker performs both broker and controller roles. Kafka-UI on port 8086 for monitoring topics, partitions, and consumer groups.
Create docker-compose.yaml:
services:
kafka-0:
image: confluentinc/cp-kafka:8.1.0
container_name: kafka-0
hostname: kafka-0
ports:
- "29092:29092"
environment:
CLUSTER_ID: ZETVJENWRjaECDUEExP_eg
KAFKA_NODE_ID: 0
KAFKA_PROCESS_ROLES: broker,controller
KAFKA_LISTENERS: INTERNAL://:9091,EXTERNAL://:29092,CONTROLLER://:9093
KAFKA_CONTROLLER_QUORUM_VOTERS: 0@kafka-0:9093,1@kafka-1:9093,2@kafka-2:9093
KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka-0:9091,EXTERNAL://localhost:29092
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT,CONTROLLER:PLAINTEXT
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
# Similarly for kafka-1 (port 29093), kafka-2 (port 29094)
kafka-ui:
image: provectuslabs/kafka-ui:v0.7.2
container_name: kafka-ui
ports:
- "8086:8080"
environment:
KAFKA_CLUSTERS_0_NAME: local
KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka-0:9091,kafka-1:9091,kafka-2:9091
DYNAMIC_CONFIG_ENABLED: true
Startup command: docker compose up -d. The cluster is ready for load with 3 partitions and x3 replication.
Spring Boot Services Configuration
Common Producer Settings
In application.properties for all services:
spring.kafka.bootstrap-servers=localhost:29092,localhost:29093,localhost:29094
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer
Programmatic Topic Creation
KafkaConfig class in the config package:
@Configuration
public class KafkaConfig {
@Bean
public NewTopic orderPlacedTopic() {
return TopicBuilder.name("order-placed")
.partitions(3)
.replicas(3)
.config(TopicConfig.RETENTION_MS_CONFIG, "86400000")
.config(TopicConfig.RETENTION_BYTES_CONFIG, "524288000")
.build();
}
}
Retention: 24 hours, 500MB per topic. Similarly for inventory-reserved, inventory-rejected in inventory-service.
Order-Service Implementation (Producer)
DTOs and Events
public record OrderRequest(String email, String productName, Integer quantity) {}
public record OrderPlacedEvent(String orderId, String email, String productName, Integer quantity) {}
Business Logic
@Service
public class OrderService {
private final KafkaTemplate<String, OrderPlacedEvent> kafkaTemplate;
public OrderService(KafkaTemplate<String, OrderPlacedEvent> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public String placeOrder(OrderRequest orderRequest) {
String orderId = UUID.randomUUID().toString();
OrderPlacedEvent event = new OrderPlacedEvent(orderId, orderRequest.email(),
orderRequest.productName(), orderRequest.quantity());
kafkaTemplate.send("order-placed", event);
return orderId;
}
}
The REST controller returns 201 Created with the orderId instantly, with processing happening asynchronously.
Inventory-Service: Producer + Consumer
Listens to order-placed, checks stock levels, and publishes inventory-reserved or inventory-rejected. Requires @KafkaListener and a second KafkaTemplate.
Service roles:
- Pure Producer: order-service
- Pure Consumer: analytics-service, notification-service
- Producer+Consumer: inventory-service
Consumer Implementation (analytics, notification)
@KafkaListener(topics = "inventory-reserved")
public void handleInventoryReserved(InventoryReservedEvent event) {
// Analytics logic
}
Spring Kafka automatically manages offsets, with consumer groups formed by service name.
Testing the Flow
- POST
/orderswith JSON{ "email": "[email protected]", "productName": "laptop", "quantity": 1 } - Monitor in Kafka-UI: order-placed → inventory-reserved
- Analytics and notification receive events in parallel
Key Points:
- KRaft simplifies deployment without Zookeeper
- 3 partitions + x3 replication = fault tolerance
- JsonSerializer for value, StringSerializer for key
- 24h/500MB retention suitable for development
- KafkaTemplate abstracts low-level API
— Editorial Team
No comments yet.