Spring Kafka in 30 Lines
Produce and consume with Spring Boot, and know which auto-configured beans you actually control.
Open this lesson in the learning hubKey points
- Add
spring-kafka. Boot auto-configures aKafkaTemplate, a consumer factory and the listener containers. KafkaTemplate.send()returns aCompletableFuture<SendResult>in Spring Kafka 3.x. Do not block on it in a hot path.@KafkaListenercreates one container per method.concurrencyis the thread count, and each thread owns whole partitions.- Keep
concurrencyat or below the partition count. Extra threads just sit idle. - Writing to a database? Use manual ack:
spring.kafka.listener.ack-mode=manualplus anAcknowledgmentparameter. - Spring hides the poll loop, not the partition maths. Every rule from the earlier lessons still applies.
Example
@Service
public class OrderEvents {
private static final Logger log = LoggerFactory.getLogger(OrderEvents.class);
private final KafkaTemplate<String, OrderEvent> template;
private final BillingService billing;
public OrderEvents(KafkaTemplate<String, OrderEvent> template, BillingService billing) {
this.template = template;
this.billing = billing;
}
public void publish(OrderEvent event) {
// key = orderId keeps every event for one order in the same partition
template.send("orders", event.orderId(), event)
.whenComplete((result, ex) -> {
if (ex != null) log.error("publish failed for {}", event.orderId(), ex);
});
}
@KafkaListener(topics = "orders", groupId = "billing-service", concurrency = "3")
public void onOrder(OrderEvent event, Acknowledgment ack) {
billing.charge(event); // must be idempotent -- this can be redelivered
ack.acknowledge(); // commit only after the work succeeded
}
}
Spring hides the poll loop. It does not hide the partition maths.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Kafka course, and every lesson in it is listed on the Kafka contents page.