Sub topic 6
Publishing messages with KafkaTemplate
This chapter assumes you know basic Spring Boot (beans, dependency injection, application.yml). It also assumes you have read the earlier chapters on topics, partitions, offsets, and on keys, values and JSON serialization. You should be able to run a local broker, for example with Docker.
What KafkaTemplate does
KafkaTemplate<K, V> is Spring's wrapper around the Kafka producer client. Spring Boot auto-configures one from the spring.kafka.* properties. You inject it like any other bean and call send.
The type parameters must match your serializers. This tutorial uses a String key and an OrderEvent value, so the template is a KafkaTemplate<String, OrderEvent>.
Producer configuration
The producer settings live in application.yml, together with the consumer settings you will need later.
spring:
kafka:
bootstrap-servers: localhost:9092
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
acks: all
properties:
enable.idempotence: true
consumer:
group-id: order-service
auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
properties:
spring.json.trusted.packages: com.example.orders
spring.json.value.default.type: com.example.orders.OrderEventacks: all makes the leader wait for the in-sync replicas before it confirms a write. enable.idempotence stops retries from creating duplicates. The delivery guarantees chapter covers both in detail.
The payload
The payload is a plain record. The JSON serializer turns it into bytes on send.
package com.example.orders;
public record OrderEvent(String orderId, long amountCents) {}Sending a message
package com.example.orders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class OrderPublisher {
private static final Logger log = LoggerFactory.getLogger(OrderPublisher.class);
private final KafkaTemplate<String, OrderEvent> kafkaTemplate;
public OrderPublisher(KafkaTemplate<String, OrderEvent> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public void publish(OrderEvent event) {
kafkaTemplate.send("orders", event.orderId(), event)
.whenComplete((result, ex) -> {
if (ex != null) {
log.error("Send failed for order {}", event.orderId(), ex);
} else {
log.info("Sent order {} to partition {} at offset {}",
event.orderId(),
result.getRecordMetadata().partition(),
result.getRecordMetadata().offset());
}
});
}
}The call send("orders", event.orderId(), event) takes the topic, the key and the value.
The key decides the partition
The producer hashes the key to choose a partition. Every event with the same order ID goes to the same partition, and Kafka preserves order within a partition. A consumer therefore sees the events for one order in the order they were sent. Events for different orders may be spread across partitions, so there is no ordering between them.
If you send with a null key, the producer spreads records across partitions and you lose per-order ordering.
Send is asynchronous
send returns a CompletableFuture<SendResult<K, V>> right away. The record is not yet confirmed when publish returns. The callback runs later, either with a SendResult that holds the partition and offset, or with an exception.
Common errors
- Ignoring the result. If you do not check the future, a failed send disappears without a trace. Always attach a callback, or block on the future when the caller must know the outcome.
- Blocking inside the callback. The callback runs on the producer's I/O thread. Keep it short.
- Serializer mismatch. A
KafkaTemplate<String, OrderEvent>with aStringSerializerfor values fails at send time with a class cast error. Keep the YAML and the generic types in agreement. - Assuming
publishmeans delivered. The method returns before the broker confirms. If the application exits at once, buffered records can be lost. CallkafkaTemplate.flush()before shutdown in short-lived programs.
Checking your work
Start a broker, run the application, and call publish(new OrderEvent("o-1", 2500)). The log should show a line like Sent order o-1 to partition 1 at offset 0. Publish a second event with the same ID. It should report the same partition and the next offset.
Exercise
You publish three events with the key "o-7" and two events with the key "o-8" to a topic with three partitions. What ordering does Kafka guarantee, and why does send() returning not prove the broker stored the record?
Show answer
Kafka guarantees that the three "o-7" events are stored and read in the order they were sent, because the same key always maps to the same partition and a partition is ordered. The same holds for the "o-8" events. It guarantees no order between "o-7" and "o-8" events if they land on different partitions. send() returns a future immediately, before the broker confirms. Only when the future completes successfully (the callback runs without an exception) has the broker acknowledged the write according to the acks setting.