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.

KafkaTemplate is Spring's wrapper around the Kafka Producer. Calling send does not write to the network straight away. The producer works in stages:

  1. The key and value are turned into bytes by the configured serializers.
  2. 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.
  3. The record is added to an in-memory batch for that partition, and send returns a CompletableFuture at once.
  4. A background I/O thread sends full batches, or batches that have waited linger.ms, to the partition leader. When the broker acknowledges them, the futures complete with the partition and offset.

Spring Boot creates the ProducerFactory and the KafkaTemplate from spring.kafka.* properties. The template is thread-safe, and all its sends share one producer instance. In Spring Boot 4 the dependency is spring-boot-starter-kafka, which brings Spring for Apache Kafka 4.1 and the Kafka 4.2 client. Boot 3 had no Kafka starter; you added spring-kafka directly.

The main ways to send with KafkaTemplate
MethodBest 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 EmbeddedKafkaKraftBroker from spring-kafka-test, the same broker Spring's own tests use. It runs in KRaft mode, because Kafka 4.0 removed ZooKeeper. The startBroker method at the end of each program does this, and silences the broker's own start-up logging. Everything else is a normal Spring Boot application that points spring.kafka.bootstrap-servers at that broker.

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. At the end it prints the producer defaults that control delivery, read from the Kafka client itself:

Java
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);
        }
    }
}
Output
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
  • send() returned a CompletableFuture that was not done yet: the record was still in the producer's batch.
  • get() waited for the broker. The SendResult says the record landed in partition 0 of greetings at offset 0. The second record got offset 1.
  • The topic exists because the NewTopic bean asked Boot's auto-configured KafkaAdmin to create it at start-up. Declaring topics this way documents their partition count in code.
  • acks = all and enable.idempotence = true 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.
  • linger.ms = 5 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.
  • delivery.timeout.ms = 120000 is the time the producer keeps retrying a record, two minutes, before it fails the future.

Boot's defaults use StringSerializer for keys and values. Set spring.kafka.producer.key-serializer and value-serializer to change them, as the JSON section does.

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:

Java
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);
        }
    }
}
Output
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.
  • sendDefault used the topic set with setDefaultTopic, also settable as 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, which writes the value as JSON with Jackson 3, the version Spring Boot 4 uses. It is configured here with one property, and the consumer reads the raw strings so that the bytes on the wire are visible:

Java
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);
        }
    }
}
Output
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 __TypeId__ 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.
  • The ProducerRecord carried a custom source header, stored as raw bytes.
  • Sending a Spring Message took the topic and key from KafkaHeaders.TOPIC and KafkaHeaders.KEY, and mapped the other headers. The mapper also added spring_json_header_types, which lets a Spring consumer restore the header's Java type.

The older JsonSerializer, based on Jackson 2, still exists for applications that have not moved to Jackson 3. To send records without type headers, set spring.kafka.producer.properties.spring.json.add.type.headers=false; the consumer then needs a default type. For schemas shared across teams, a schema registry with Avro or Protobuf is the usual choice.

When a send fails

A send can fail in two places: inside send() itself, before the record is queued, or later, when the broker rejects the batch. Each case below triggers one of them. A topic named small accepts at most 1 KB per message, and max.block.ms is lowered to 2 seconds so that a wait for missing metadata ends quickly:

Java
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);
        }
    }
}
Output
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 whenComplete received the offset and a null 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.
  • A 2 MB record exceeded the producer's own max.request.size of 1 MB. The producer checked this before queuing, so send() threw a KafkaException straight away, and no future was returned.
  • Partition 7 does not exist. The producer waited for metadata that would show it, for max.block.ms, then send() threw with a TimeoutException after 2000 ms. With the default of 60 seconds, the calling thread blocks for a minute.
  • The 5 KB record passed the producer's checks but not the topic's 1 KB limit. This time send() returned normally, and the future failed later with KafkaProducerException, caused by the broker's RecordTooLargeException.
  • The last send had the same problem, but nobody looked at its future, so the program never knew.

Spring Boot registers a LoggingProducerListener that logs failed sends at ERROR level, which is the only trace of a fire-and-forget failure; this program turns logging off to keep the output stable. Handle both paths: catch exceptions from send(), and check the future, with get(), join() or a callback. For records that must not be lost, also keep acks=all and a topic with a replication factor of 3 and min.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 makes Boot's template transactional:

Java
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);
        }
    }
}
Output
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 flush(), then failed. executeInTransaction aborted the transaction and rethrew the exception.
  • Once the template is transactional, a plain send() outside a transaction is refused with "No transaction is in process".
  • The read_uncommitted consumer, Kafka's default, saw the aborted debit 70 at offset 3. The aborted record is in the log: an abort only marks it.
  • The read_committed 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.

Transactions only protect readers that use isolation.level=read_committed, so set spring.kafka.consumer.isolation-level=read-committed on every consumer of such a topic. Inside a @KafkaListener, the container can run the listener in a Kafka transaction too, so that consuming a record, producing results and committing the offset happen together. The single-node broker here needs its transaction log replication lowered to 1, which startBroker does; production clusters keep the default of 3.

Waiting after every send is slow

Calling get() after each send() is common, because it makes failures easy to handle. It also defeats batching: each record must reach the broker before the next one is even queued. This program sends 500 small records three ways:

Java
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);
        }
    }
}
Output
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 linger.ms=5, 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.
  • With linger.ms=0, set through the KafkaTemplate constructor that overrides producer properties, the same loop was several times faster, but it still paid one network round trip per record.
  • 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

Situations and the approach that fits
SituationApproach
Events about an entity, such as an order or a customersend(topic, entityId, event), so each entity's events stay in order
High-volume events with no ordering needssend(topic, value) with no key, and futures checked in bulk
A request handler that must report failure to the callersend(...).get(timeout), accepting the latency
Several records that must appear togethertransaction-id-prefix and executeInTransaction, with read_committed consumers
Metadata such as a trace id or the event sourceHeaders on a ProducerRecord or a Spring Message
Objects between Spring servicesJacksonJsonSerializer; a schema registry when other teams or languages consume

The other side of the topic is covered on consuming messages with @KafkaListener. When a consumer fails on a record, see Kafka error handling and retries and dead letter topics; to watch producers and consumers in production, see Kafka monitoring.