In Spring, KafkaTemplate is the high-level client for producing messages to Apache Kafka. It hides producer creation, serialization and resource handling behind a template API, much like JdbcTemplate does for SQL, so application code just calls send and handles the result.
This article shows how to wire it without relying on Spring Boot auto-configuration, how it pairs with @KafkaListener on the consuming side, and how to test it. Spring Kafka 3.x returns CompletableFuture from send; the older ListenableFuture is gone.
Outside Boot you define a ProducerFactory and a KafkaTemplate yourself. The factory creates producers; the template uses them.
With Spring Boot, the same result comes from spring.kafka.* properties, and a KafkaTemplate bean exists without any of this code.
The caller decides whether to wait, chain or log:
Using the payment id as key sends every event of one payment to one partition, so consumers see them in order. Ordering across partitions is not guaranteed by Kafka.
KafkaTemplate only produces. Consumers use @KafkaListener and a listener container, which is configured separately:
The JsonDeserializer needs trusted packages (spring.json.trusted.packages) so it only deserializes types you expect. For request and reply style messaging there is ReplyingKafkaTemplate, which correlates a reply with the original request.
| Setting | Recommended value | Reason |
|---|---|---|
acks | all | Wait for in-sync replicas |
enable.idempotence | true | Retries do not duplicate records |
delivery.timeout.ms | Set deliberately | Upper bound for send plus retries |
linger.ms and batch.size | Tune per workload | Larger batches improve throughput |
compression.type | lz4 or zstd | Less network and disk use |
The template buffers records in the producer, so call flush() before shutdown if you manage the factory yourself. Spring closes producers when the context stops.
spring-kafka-test provides @EmbeddedKafka, which starts a broker inside the test JVM:
For integration tests that match production more closely, Testcontainers with a Kafka image is a common alternative.
The raw KafkaProducer is the low-level client. KafkaTemplate manages its lifecycle, adds Spring conventions such as default topics and Message support, and integrates with transactions and observability.
Yes, every template uses one. Boot creates it for you; in plain Spring you define it.
It guarantees what Kafka guarantees under your acks, retry and idempotence settings. You must still handle failed futures.
Yes. Define one per cluster or per serializer combination and select it with a qualifier.
KafkaTemplate is Spring's producer abstraction for Kafka. A ProducerFactory creates the producers, the template sends keyed or headered records and reports results through CompletableFuture. Pair it with @KafkaListener for consuming, set acks=all with idempotence for safety, and test with @EmbeddedKafka or Testcontainers.