Sub topic 6
Publishing messages with KafkaTemplate
This chapter covers how a Spring Boot application sends records to Kafka with KafkaTemplate. It assumes you know Java and basic Spring Boot (beans, dependency injection, application.yml). It also assumes you have read the earlier chapters on topics, partitions, offsets and keys and values, and that you can run a local broker, for example with Docker.
What KafkaTemplate does
KafkaTemplate<K, V> is Spring's wrapper around the Kafka client's KafkaProducer. It gives you a thread-safe API for sending records, and it handles creating the producer and applying your serializer settings. Spring Boot creates one KafkaTemplate bean for you from the spring.kafka.* properties.
The two type parameters are the key type and the value type. They must match the serializers you configured. In this tutorial the key is a String and the value is an OrderEvent:
package com.example.orders;
public record OrderEvent(String orderId, long amountCents) {}The matching producer configuration uses a string key serializer and a JSON value serializer. Settings such as acks: all and idempotence are covered in a later chapter on reliable delivery, but they are shown here because they belong to the same producer.
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.OrderEventThe topic must exist before you rely on it. The earlier chapter showed a NewTopic bean for this:
package com.example.orders;
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();
}
}Sending a record
The simplest useful call is send(topic, key, value). The following service publishes an OrderEvent and logs the outcome.
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());
}
});
}
}Three points about this code matter in practice.
- The call is asynchronous.
sendreturns aCompletableFuture<SendResult<K, V>>right away. The record is not yet acknowledged whenpublishreturns. - The key is the order ID. Kafka hashes the key to choose a partition, so every event for one order lands on the same partition and is consumed in the order it was written.
- The callback receives either a result or an exception.
SendResult.getRecordMetadata()tells you the partition and offset the broker assigned.
What happens during a send
A send passes through several stages before the broker confirms it. Knowing them explains most surprising behavior.
The producer does not send each record on its own. It collects records into per-partition batches and sends a batch when it is full (batch.size) or when linger.ms has elapsed. With the default linger.ms of 0 a batch is sent as soon as possible, but records that arrive while a request is in flight still share batches. Raising linger.ms to a few milliseconds trades a little latency for larger batches and better throughput.
Retries happen inside the producer. If a send fails with a retriable error, such as a leader change, the client retries until delivery.timeout.ms expires. Your callback only sees the final outcome.
Handling the result
You have three ways to deal with the outcome of a send. Choose based on what the caller needs.
| Approach | How | Use when |
|---|---|---|
| Callback | `.whenComplete((result, ex) -> ...)` | You want to log, count metrics or trigger a compensating action without blocking. |
| Blocking wait | `.get(timeout, unit)` on the future | The caller must know the record was stored before continuing. |
| Fire and forget | Ignore the returned future | Losing a record is acceptable, such as low-value telemetry. |
Ignoring the future means a failure produces no signal at all. Spring does not log it for you. Always attach at least a callback for data you care about.
A blocking wait looks like this:
package com.example.orders;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
@Service
public class BlockingOrderPublisher {
private final KafkaTemplate<String, OrderEvent> kafkaTemplate;
public BlockingOrderPublisher(KafkaTemplate<String, OrderEvent> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public long publishAndWait(OrderEvent event)
throws ExecutionException, InterruptedException, TimeoutException {
SendResult<String, OrderEvent> result = kafkaTemplate
.send("orders", event.orderId(), event)
.get(10, TimeUnit.SECONDS);
return result.getRecordMetadata().offset();
}
}Waiting on every send removes the benefit of batching, because each call must finish before the next one starts. Use it for rare, important messages, not for bulk publishing.
Other send variants
KafkaTemplate has several overloads. The most useful ones are:
send(topic, value)sends with no key. Records are spread across partitions, so there is no per-key ordering.send(topic, key, value)sends with a key, as shown above.send(topic, partition, key, value)forces a specific partition. Do this only when you have a real reason, because it bypasses key hashing.send(ProducerRecord)andsend(Message<?>)give full control, including headers.sendDefault(key, value)uses the template's default topic. Set it withspring.kafka.template.default-topic.
A ProducerRecord is the way to attach headers, which are small key-value pairs that travel with the record, such as a trace ID:
package com.example.orders;
import java.nio.charset.StandardCharsets;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class TracedOrderPublisher {
private final KafkaTemplate<String, OrderEvent> kafkaTemplate;
public TracedOrderPublisher(KafkaTemplate<String, OrderEvent> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public void publish(OrderEvent event, String traceId) {
ProducerRecord<String, OrderEvent> record =
new ProducerRecord<>("orders", event.orderId(), event);
record.headers().add("trace-id", traceId.getBytes(StandardCharsets.UTF_8));
kafkaTemplate.send(record);
}
}Common errors
These are the problems learners hit most often when first publishing.
- Silent failures. The future is ignored, the broker is unreachable, and nothing is logged. Attach a callback.
- Blocking on
bootstrap-servers. If the broker address is wrong,sendblocks for up tomax.block.ms(60 seconds by default) while it tries to fetch topic metadata, and then fails with a timeout. Check the address and that the topic exists. - Serializer mismatch. The template is declared as
KafkaTemplate<String, OrderEvent>but the configured value serializer isStringSerializer. The failure is aClassCastExceptionat send time. Keep the generic types and the serializers consistent. - Null keys when ordering matters. Without a key there is no ordering guarantee across a topic's partitions. Use a key that identifies the entity whose events must stay in order.
- Assuming one send equals one stored record forever. With
acks=alland idempotence enabled, retries inside the producer do not create duplicates. If your own code resends after a failure, you can still produce duplicates, so consumers should tolerate them. - Hot partitions. A key with very uneven traffic, for example a single customer who generates most events, sends most records to one partition. Pick a key with enough variety.
Verifying it works
With a broker on localhost:9092, call publish(new OrderEvent("order-1", 2500)) from a controller or a CommandLineRunner. The log line from the callback should look similar to this:
Sent order order-1 to partition 1 at offset 0The partition number depends on the key hash, so yours may differ. Publish order-1 again and the partition stays the same while the offset increases. That is the per-key ordering guarantee at work. You can also inspect the topic from the command line:
kafka-console-consumer.sh --bootstrap-server localhost:9092 \
--topic orders --from-beginning --property print.key=trueExercise
A service calls kafkaTemplate.send("orders", event.orderId(), event) and never uses the returned future. The broker goes down for a minute. What happens to the records, and what is the smallest change that lets the service notice the failure?
Show answer
The producer retries internally until delivery.timeout.ms expires, and records that still cannot be delivered fail. Because the future is ignored, nobody is told, so the records are lost silently. The smallest change is to attach a callback with whenComplete (or call get with a timeout) on the returned CompletableFuture and log or handle the exception.
Exercise
Why does using the order ID as the key keep events for one order in sequence, and when would that guarantee not hold?
Show answer
Kafka hashes the key to pick a partition, so all records with the same key go to the same partition, and a partition preserves write order. The guarantee does not hold if the key is null, if you override the partition manually, or if the topic's partition count changes later, because the hash then maps keys to different partitions.