Spring Kafka: sending messages with KafkaTemplate
KafkaTemplate wraps the Kafka producer so that a Spring application can send a record with one call. What happens after that call decides whether the record arrives, in which order and how fast. This page explains the producer underneath, then runs every example against a real Kafka broker started inside the program.
Contents
What happens when you send a record
A Kafka topic is split into partitions, and each partition is an append-only log on the brokers. A record has a key, a value, optional headers and a timestamp. Once the broker has written it, the record gets an offset: its position in that partition's log.
KafkaTemplateProducersend
- The key and value are turned into bytes by the configured serializers.
- The partitioner picks a partition. With a key, it hashes the key, so the same key always goes to the same partition. Without a key, it fills one partition's batch, then moves on to another.
- The record is added to an in-memory batch for that partition, and
returns asend at once.CompletableFuture - A background I/O thread sends full batches, or batches that have waited
, to the partition leader. When the broker acknowledges them, the futures complete with the partition and offset.linger.ms
Spring Boot creates the ProducerFactoryKafkaTemplatespring.kafka.*spring-boot-starter-kafkaspring-kafka
| Method | Best for |
|---|---|
send(topic, value) | Events where order does not matter |
send(topic, key, value) | Most events: the key keeps related records in order |
send(topic, partition, key, value) | Rare cases that must choose the partition themselves |
send(ProducerRecord) | Records with headers or an explicit timestamp |
send(Message) | Spring Messaging code, with topic and key as headers |
sendDefault(...) | A template dedicated to one topic |
executeInTransaction(...) | Several records that must all be visible, or none |
The examples need a broker, so each one starts a single-node Kafka broker in the same JVM with EmbeddedKafkaKraftBrokerspring-kafka-teststartBrokerspring.kafka.bootstrap-servers
A first send and what comes back
The program sends two greetings, waits for the broker's acknowledgement of the first, then reads both back with a plain consumer from Boot's ConsumerFactory
package demo.kafka.first;
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
@SpringBootApplication
public class FirstSend {
@Bean
NewTopic greetings() {
return TopicBuilder.name("greetings").partitions(1).replicas(1).build();
}
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
SpringApplication app = new SpringApplication(FirstSend.class);
app.setDefaultProperties(Map.of(
"spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
"spring.kafka.consumer.auto-offset-reset", "earliest",
"spring.main.banner-mode", "off", "logging.level.root", "ERROR"));
try (var context = app.run(args)) {
@SuppressWarnings("unchecked")
KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
var future = template.send("greetings", "user-1", "hello");
System.out.println("send() returned " + future.getClass().getSimpleName()
+ ", done yet: " + future.isDone());
SendResult<String, String> result = future.get();
System.out.println("acknowledged: topic " + result.getRecordMetadata().topic()
+ ", partition " + result.getRecordMetadata().partition()
+ ", offset " + result.getRecordMetadata().offset());
template.send("greetings", "user-2", "bonjour").get();
ConsumerFactory<?, ?> factory = context.getBean(ConsumerFactory.class);
try (Consumer<?, ?> consumer = factory.createConsumer("reader", null)) {
consumer.subscribe(List.of("greetings"));
int seen = 0;
while (seen < 2) {
for (ConsumerRecord<?, ?> r : consumer.poll(Duration.ofSeconds(1))) {
System.out.println("read back: offset " + r.offset() + ", key "
+ r.key() + ", value " + r.value());
seen++;
}
}
}
Map<String, Object> defaults = ProducerConfig.configDef().defaultValues();
System.out.println("Kafka producer defaults:");
for (String key : List.of("acks", "enable.idempotence", "linger.ms", "batch.size",
"delivery.timeout.ms", "max.request.size")) {
System.out.println(" " + key + " = " + defaults.get(key));
}
} finally {
broker.destroy();
}
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO, and prints its storage setup, before Spring Boot
// configures logging, so both are silenced while it starts.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.ERROR);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
send() returned CompletableFuture, done yet: false
acknowledged: topic greetings, partition 0, offset 0
read back: offset 0, key user-1, value hello
read back: offset 1, key user-2, value bonjour
Kafka producer defaults:
acks = all
enable.idempotence = true
linger.ms = 5
batch.size = 16384
delivery.timeout.ms = 120000
max.request.size = 1048576
returned asend() that was not done yet: the record was still in the producer's batch.CompletableFuture waited for the broker. Theget() says the record landed in partition 0 ofSendResult at offset 0. The second record got offset 1.greetings- The topic exists because the
bean asked Boot's auto-configuredNewTopic to create it at start-up. Declaring topics this way documents their partition count in code.KafkaAdmin andacks = all mean the leader waits for all in-sync replicas, and broker-side retries cannot write duplicates. Both have been the default since Kafka 3.0.enable.idempotence = true makes the producer wait up to 5 ms to fill a batch. The default was 0 until Kafka 4.0 changed it in KIP-1030. A later section shows what this does to code that waits after every send.linger.ms = 5 is the time the producer keeps retrying a record, two minutes, before it fails the future.delivery.timeout.ms = 120000
Boot's defaults use StringSerializerspring.kafka.producer.key-serializervalue-serializer
Keys, partitions and ordering
Kafka keeps order only within a partition. The key decides the partition, so it decides which records stay in order relative to each other. This program sends three events for each of four customers, interleaved, to a topic with three partitions:
package demo.kafka.keys;
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
@SpringBootApplication
public class KeysAndPartitions {
@Bean
NewTopic orders() {
return TopicBuilder.name("orders").partitions(3).replicas(1).build();
}
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
SpringApplication app = new SpringApplication(KeysAndPartitions.class);
app.setDefaultProperties(Map.of(
"spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
"spring.main.banner-mode", "off", "logging.level.root", "ERROR"));
try (var context = app.run(args)) {
@SuppressWarnings("unchecked")
KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
// three events for each of four customers, sent in an interleaved order
Map<String, TreeSet<Integer>> partitionsByKey = new TreeMap<>();
Map<Integer, StringBuilder> logByPartition = new TreeMap<>();
for (int event = 1; event <= 3; event++) {
for (String customer : new String[] {"alice", "bob", "carol", "dave"}) {
SendResult<String, String> r =
template.send("orders", customer, customer + "#" + event).get();
int partition = r.getRecordMetadata().partition();
partitionsByKey.computeIfAbsent(customer, k -> new TreeSet<>())
.add(partition);
logByPartition.computeIfAbsent(partition, p -> new StringBuilder())
.append(customer).append('#').append(event).append(' ');
}
}
partitionsByKey.forEach((key, parts) ->
System.out.println("key " + key + " -> partitions " + parts));
logByPartition.forEach((p, log) -> System.out.println("partition " + p
+ " in offset order: " + log.toString().trim()));
SendResult<String, String> pinned = template.send("orders", 2, "alice", "x").get();
System.out.println("explicit partition 2 for key alice -> partition "
+ pinned.getRecordMetadata().partition());
template.setDefaultTopic("orders");
SendResult<String, String> viaDefault = template.sendDefault("erin", "erin#1").get();
System.out.println("sendDefault -> topic " + viaDefault.getRecordMetadata().topic());
} finally {
broker.destroy();
}
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO, and prints its storage setup, before Spring Boot
// configures logging, so both are silenced while it starts.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.ERROR);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
key alice -> partitions [0]
key bob -> partitions [0]
key carol -> partitions [2]
key dave -> partitions [1]
partition 0 in offset order: alice#1 bob#1 alice#2 bob#2 alice#3 bob#3
partition 1 in offset order: dave#1 dave#2 dave#3
partition 2 in offset order: carol#1 carol#2 carol#3
explicit partition 2 for key alice -> partition 2
sendDefault -> topic orders
- Each key always went to one partition: alice and bob to 0, dave to 1, carol to 2. The default partitioner takes a murmur2 hash of the key bytes, modulo the partition count, so the result is the same on every run and in every client.
- Within partition 0, alice's events are in order #1, #2, #3, and so are bob's. Their records are interleaved, which is fine: a consumer of that partition still sees each customer's events in order.
- Two keys can share a partition, as alice and bob do. With few keys and many partitions, some partitions may get no traffic at all.
- An explicit partition overrode the key hash: alice's record went to partition 2.
used the topic set withsendDefault , also settable assetDefaultTopic .spring.kafka.template.default-topic
Two consequences follow. Changing the number of partitions of a topic changes where existing keys go, so records for one key can end up in two partitions and lose their order. And records without a key have no ordering at all: since Kafka 2.4, the producer fills a batch for one partition, then switches to another, to spread load.
JSON values and headers
Most applications send objects, not strings. Spring for Apache Kafka provides JacksonJsonSerializer
package demo.kafka.json;
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.header.Header;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.messaging.support.MessageBuilder;
@SpringBootApplication
public class JsonAndHeaders {
record OrderPlaced(String orderId, String customer, int totalCents) { }
@Bean
NewTopic orders() {
return TopicBuilder.name("orders").partitions(1).replicas(1).build();
}
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
SpringApplication app = new SpringApplication(JsonAndHeaders.class);
app.setDefaultProperties(Map.of(
"spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
"spring.kafka.producer.value-serializer",
"org.springframework.kafka.support.serializer.JacksonJsonSerializer",
"spring.kafka.consumer.auto-offset-reset", "earliest",
"spring.main.banner-mode", "off", "logging.level.root", "ERROR"));
try (var context = app.run(args)) {
@SuppressWarnings("unchecked")
KafkaTemplate<String, Object> template = context.getBean(KafkaTemplate.class);
// 1. a plain object: the serializer writes JSON and a type header
template.send("orders", "o-1", new OrderPlaced("o-1", "alice", 2599)).get();
// 2. a ProducerRecord, to add headers of your own
ProducerRecord<String, Object> record = new ProducerRecord<>("orders", "o-2",
new OrderPlaced("o-2", "bob", 1000));
record.headers().add("source", "web-checkout".getBytes(StandardCharsets.UTF_8));
template.send(record).get();
// 3. a Spring Message, with topic and key given as headers
template.send(MessageBuilder.withPayload(new OrderPlaced("o-3", "carol", 450))
.setHeader(KafkaHeaders.TOPIC, "orders")
.setHeader(KafkaHeaders.KEY, "o-3")
.setHeader("source", "mobile-app")
.build()).get();
// read the raw records with the String deserializer Boot configures by default
ConsumerFactory<?, ?> factory = context.getBean(ConsumerFactory.class);
try (Consumer<?, ?> consumer = factory.createConsumer("reader", null)) {
consumer.subscribe(List.of("orders"));
int seen = 0;
while (seen < 3) {
for (ConsumerRecord<?, ?> r : consumer.poll(Duration.ofSeconds(1))) {
System.out.println("offset " + r.offset() + " key " + r.key());
System.out.println(" value : " + r.value());
for (Header h : r.headers()) {
System.out.println(" header : " + h.key() + " = "
+ new String(h.value(), StandardCharsets.UTF_8));
}
seen++;
}
}
}
} finally {
broker.destroy();
}
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO, and prints its storage setup, before Spring Boot
// configures logging, so both are silenced while it starts.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.ERROR);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
offset 0 key o-1
value : {"orderId":"o-1","customer":"alice","totalCents":2599}
header : __TypeId__ = demo.kafka.json.JsonAndHeaders$OrderPlaced
offset 1 key o-2
value : {"orderId":"o-2","customer":"bob","totalCents":1000}
header : source = web-checkout
header : __TypeId__ = demo.kafka.json.JsonAndHeaders$OrderPlaced
offset 2 key o-3
value : {"orderId":"o-3","customer":"carol","totalCents":450}
header : source = mobile-app
header : spring_json_header_types = {"source":"java.lang.String"}
header : __TypeId__ = demo.kafka.json.JsonAndHeaders$OrderPlaced
- The value of every record is plain JSON built from the record components.
- The serializer added a
header with the Java class name. A Spring consumer can use it to pick the target class. A consumer in another language ignores it, and if the class is renamed, consumers that still rely on the header break.__TypeId__ - The
carried a customProducerRecord header, stored as raw bytes.source - Sending a Spring
took the topic and key fromMessage andKafkaHeaders.TOPIC , and mapped the other headers. The mapper also addedKafkaHeaders.KEY , which lets a Spring consumer restore the header's Java type.spring_json_header_types
The older JsonSerializerspring.kafka.producer.properties.spring.json.add.type.headers=false
When a send fails
A send can fail in two places: inside send()smallmax.block.ms
package demo.kafka.failures;
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.config.TopicConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
@SpringBootApplication
public class SendFailures {
@Bean
NewTopic payments() {
return TopicBuilder.name("payments").partitions(1).replicas(1).build();
}
@Bean
NewTopic small() {
return TopicBuilder.name("small").partitions(1).replicas(1)
.config(TopicConfig.MAX_MESSAGE_BYTES_CONFIG, "1024").build();
}
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
SpringApplication app = new SpringApplication(SendFailures.class);
app.setDefaultProperties(Map.of(
"spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
"spring.kafka.producer.properties.max.block.ms", "2000",
"spring.main.banner-mode", "off", "logging.level.root", "OFF"));
try (var context = app.run(args)) {
@SuppressWarnings("unchecked")
KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
System.out.println("1. A callback instead of get():");
CompletableFuture<SendResult<String, String>> ok =
template.send("payments", "p-1", "100 EUR");
ok.whenComplete((result, error) -> System.out.println(" callback: offset "
+ result.getRecordMetadata().offset() + ", error " + error));
ok.join();
Thread.sleep(100); // let the callback print before the next step
System.out.println("2. A record over the producer's max.request.size (1 MB):");
report(() -> template.send("payments", "p-2", "x".repeat(2 * 1024 * 1024)).get());
System.out.println("3. A partition that does not exist:");
report(() -> template.send("payments", 7, "p-3", "5 EUR").get());
System.out.println("4. 5 KB to a topic whose brokers accept at most 1 KB:");
report(() -> template.send("small", "p-4", "z".repeat(5 * 1024)).get());
System.out.println("5. The same without get() or a callback:");
template.send("small", "p-5", "z".repeat(5 * 1024));
System.out.println(" send() returned normally; nothing reported the error");
} finally {
broker.destroy();
}
}
interface Send {
void run() throws Exception;
}
static void report(Send send) {
try {
send.run();
System.out.println(" sent");
} catch (ExecutionException e) {
System.out.println(" the future failed: " + describe(e.getCause()));
} catch (Exception e) {
System.out.println(" send() threw: " + describe(e));
}
}
static String describe(Throwable e) {
Throwable root = rootCause(e);
return e.getClass().getSimpleName() + (root == e ? "" : ", caused by "
+ root.getClass().getSimpleName()) + "\n " + root.getMessage();
}
static Throwable rootCause(Throwable e) {
while (e.getCause() != null) {
e = e.getCause();
}
return e;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO, and prints its storage setup, before Spring Boot
// configures logging, so both are silenced while it starts.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.ERROR);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
1. A callback instead of get():
callback: offset 0, error null
2. A record over the producer's max.request.size (1 MB):
send() threw: KafkaException, caused by RecordTooLargeException
The message is 2097243 bytes when serialized which is larger than 1048576, which is the value of the max.request.size configuration.
3. A partition that does not exist:
send() threw: KafkaException, caused by TimeoutException
Partition 7 of topic payments with partition count 1 is not present in metadata after 2000 ms.
4. 5 KB to a topic whose brokers accept at most 1 KB:
the future failed: KafkaProducerException, caused by RecordTooLargeException
The request included a message larger than the max message size the server will accept.
5. The same without get() or a callback:
send() returned normally; nothing reported the error
- The callback attached with
received the offset and awhenComplete error. Callbacks run on the producer's single I/O thread, or on the caller if the future had already completed, so they must stay short.null - A 2 MB record exceeded the producer's own
of 1 MB. The producer checked this before queuing, somax.request.size threw asend() straight away, and no future was returned.KafkaException - Partition 7 does not exist. The producer waited for metadata that would show it, for
, thenmax.block.ms threw with asend() after 2000 ms. With the default of 60 seconds, the calling thread blocks for a minute.TimeoutException - The 5 KB record passed the producer's checks but not the topic's 1 KB limit. This time
returned normally, and the future failed later withsend() , caused by the broker'sKafkaProducerException .RecordTooLargeException - The last send had the same problem, but nobody looked at its future, so the program never knew.
Spring Boot registers a LoggingProducerListenersend()get()join()acks=allmin.insync.replicas=2
Transactions: all records or none
A transfer writes a debit and a credit, and a consumer must never see one without the other. Kafka transactions make a group of records visible atomically. Setting spring.kafka.producer.transaction-id-prefix
package demo.kafka.tx;
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
@SpringBootApplication
public class TransactionalSend {
@Bean
NewTopic ledger() {
return TopicBuilder.name("ledger").partitions(1).replicas(1).build();
}
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
SpringApplication app = new SpringApplication(TransactionalSend.class);
app.setDefaultProperties(Map.of(
"spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
"spring.kafka.producer.transaction-id-prefix", "ledger-tx-",
"spring.kafka.consumer.auto-offset-reset", "earliest",
"spring.main.banner-mode", "off", "logging.level.root", "OFF"));
try (var context = app.run(args)) {
@SuppressWarnings("unchecked")
KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
System.out.println("transactional template: " + template.isTransactional());
template.executeInTransaction(t -> {
t.send("ledger", "acc-1", "debit 50");
t.send("ledger", "acc-2", "credit 50");
return null;
});
System.out.println("transfer 1 committed");
try {
template.executeInTransaction(t -> {
t.send("ledger", "acc-1", "debit 70");
t.flush(); // make sure the record reaches the broker before the failure
throw new IllegalStateException("credit side failed");
});
} catch (IllegalStateException e) {
System.out.println("transfer 2 aborted: " + e.getMessage());
}
try {
template.send("ledger", "acc-3", "outside a transaction");
} catch (IllegalStateException e) {
System.out.println("plain send(): " + e.getMessage().split(";")[0]);
}
ConsumerFactory<?, ?> factory = context.getBean(ConsumerFactory.class);
for (String isolation : List.of("read_uncommitted", "read_committed")) {
System.out.println(isolation + " consumer sees: " + readAll(factory, isolation));
}
} finally {
broker.destroy();
}
}
static List<String> readAll(ConsumerFactory<?, ?> factory, String isolation) {
List<String> values = new ArrayList<>();
Properties overrides = new Properties();
overrides.setProperty(ConsumerConfig.ISOLATION_LEVEL_CONFIG, isolation);
try (Consumer<?, ?> consumer = factory.createConsumer(isolation, null, null, overrides)) {
consumer.subscribe(List.of("ledger"));
long deadline = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < deadline) {
for (ConsumerRecord<?, ?> r : consumer.poll(Duration.ofMillis(500))) {
values.add(r.offset() + ":" + r.value());
}
if (!values.isEmpty() && consumer.poll(Duration.ofMillis(500)).isEmpty()) {
break;
}
}
}
return values;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO, and prints its storage setup, before Spring Boot
// configures logging, so both are silenced while it starts.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.ERROR);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
transactional template: true
transfer 1 committed
transfer 2 aborted: credit side failed
plain send(): No transaction is in process
read_uncommitted consumer sees: [0:debit 50, 1:credit 50, 3:debit 70]
read_committed consumer sees: [0:debit 50, 1:credit 50]
- Transfer 1 sent both records and committed.
- Transfer 2 sent the debit, forced it to the broker with
, then failed.flush() aborted the transaction and rethrew the exception.executeInTransaction - Once the template is transactional, a plain
outside a transaction is refused with "No transaction is in process".send() - The
consumer, Kafka's default, saw the abortedread_uncommitted at offset 3. The aborted record is in the log: an abort only marks it.debit 70 - The
consumer saw only the committed transfer. Offsets 2 and 4 are missing from both lists because they hold the commit and abort markers that the broker writes.read_committed
Transactions only protect readers that use isolation.level=read_committedspring.kafka.consumer.isolation-level=read-committed@KafkaListenerstartBroker
Waiting after every send is slow
Calling get()send()
package demo.kafka.throughput;
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
@SpringBootApplication
public class SyncVsAsync {
static final int RECORDS = 500;
@Bean
NewTopic clicks() {
return TopicBuilder.name("clicks").partitions(1).replicas(1).build();
}
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
SpringApplication app = new SpringApplication(SyncVsAsync.class);
app.setDefaultProperties(Map.of(
"spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
"spring.main.banner-mode", "off", "logging.level.root", "ERROR"));
try (var context = app.run(args)) {
@SuppressWarnings("unchecked")
KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
KafkaTemplate<String, String> noLinger = new KafkaTemplate<>(
template.getProducerFactory(), Map.of(ProducerConfig.LINGER_MS_CONFIG, 0));
sendAsync(template); // warm-up
long[] best = {Long.MAX_VALUE, Long.MAX_VALUE, Long.MAX_VALUE};
for (int run = 0; run < 3; run++) {
best[0] = Math.min(best[0], time(() -> sendEachAndWait(template)));
best[1] = Math.min(best[1], time(() -> sendEachAndWait(noLinger)));
best[2] = Math.min(best[2], time(() -> sendAsync(template)));
}
System.out.println(RECORDS + " records, rough comparison, best of 3 runs:");
System.out.println(" get() after every send, linger.ms=5 : " + best[0] + " ms");
System.out.println(" get() after every send, linger.ms=0 : " + best[1] + " ms");
System.out.println(" send all, then wait for all : " + best[2] + " ms");
} finally {
broker.destroy();
}
}
static long time(Runnable task) {
long start = System.nanoTime();
task.run();
return (System.nanoTime() - start) / 1000000;
}
static void sendEachAndWait(KafkaTemplate<String, String> template) {
for (int i = 0; i < RECORDS; i++) {
template.send("clicks", "page-" + (i % 10), "click " + i).join();
}
}
static void sendAsync(KafkaTemplate<String, String> template) {
List<CompletableFuture<?>> futures = new ArrayList<>(RECORDS);
for (int i = 0; i < RECORDS; i++) {
futures.add(template.send("clicks", "page-" + (i % 10), "click " + i));
}
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO, and prints its storage setup, before Spring Boot
// configures logging, so both are silenced while it starts.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.ERROR);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
500 records, rough comparison, best of 3 runs:
get() after every send, linger.ms=5 : 3687 ms
get() after every send, linger.ms=0 : 444 ms
send all, then wait for all : 5 ms
- With the Kafka 4 default of
, waiting after every send cost more than 5 ms per record, because each lone record waited for its batch to fill before being sent. This is the slowest variant by a wide margin.linger.ms=5 - With
, set through thelinger.ms=0 constructor that overrides producer properties, the same loop was several times faster, but it still paid one network round trip per record.KafkaTemplate - Sending all 500 records first and then waiting for all the futures let the producer pack them into a few batches. It was faster again by two orders of magnitude.
These are rough comparisons: best of 3 runs on a 2-core Linux container with the broker in the same JVM, so there is almost no network latency. Against a remote cluster, every round trip is slower and the gap grows. When you need to know that each record arrived, collect the futures and check them together, or use callbacks, instead of blocking per record.
Choosing how to send
| Situation | Approach |
|---|---|
| Events about an entity, such as an order or a customer | send(topic, entityId, event) |
| High-volume events with no ordering needs | send(topic, value) |
| A request handler that must report failure to the caller | send(...).get(timeout) |
| Several records that must appear together | transaction-id-prefixexecuteInTransactionread_committed |
| Metadata such as a trace id or the event source | Headers on a ProducerRecordMessage |
| Objects between Spring services | JacksonJsonSerializer |
The other side of the topic is covered on