Sub topic 13
Kafka transactions with Spring
This chapter assumes you know how KafkaTemplate, @KafkaListener, consumer groups and offset commits work, and that you have configured acks: all and idempotence as in the earlier chapters on reliable delivery.
Why idempotence is not enough
An idempotent producer prevents duplicates caused by its own retries within one producer session. It does not cover a common pattern: consume a record, process it, and publish a result to another topic. That flow has two separate writes:
- The result is sent to the output topic.
- The consumer offset is committed to
__consumer_offsets.
If the application crashes between these two steps, the result is already published, but the offset is not committed. After a restart the record is read again and a second result is published. This is at-least-once delivery.
A Kafka transaction makes both writes atomic. The output records and the offset commit either both become visible or neither does. This pattern is called consume-transform-produce.
How it works
A transactional producer has a transactional.id. The broker uses it to fence out an older instance with the same ID, so a "zombie" producer cannot write after its replacement has started.
Inside a transaction, the producer:
- Begins the transaction.
- Sends records to one or more partitions.
- Sends the consumer offsets to the transaction with
sendOffsetsToTransaction. - Commits the transaction, or aborts it on failure.
Spring for Apache Kafka performs these steps for you when the listener container is transaction-aware.
Enabling transactions in Spring Boot
Setting spring.kafka.producer.transaction-id-prefix turns on transactions. Spring Boot then creates a KafkaTransactionManager and wires it into the auto-configured listener container.
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
transaction-id-prefix: order-tx-
consumer:
group-id: order-service
enable-auto-commit: false
isolation-level: read_committed
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.OrderEventTwo settings matter here:
transaction-id-prefixgives each producer instance a uniquetransactional.id. Spring appends a suffix to the prefix. Idempotence andacks=allare enabled automatically for transactional producers.isolation-level: read_committedmakes consumers skip records from aborted or still-open transactions. The default,read_uncommitted, shows everything.
A transactional listener
With the transaction manager in place, a listener's KafkaTemplate.send calls take part in the container's transaction. No extra annotation is needed.
package com.example.orders;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
@Component
public class PaymentRequester {
private final KafkaTemplate<String, OrderEvent> kafkaTemplate;
public PaymentRequester(KafkaTemplate<String, OrderEvent> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
@KafkaListener(topics = "orders", groupId = "order-service")
public void onOrder(OrderEvent event) {
if (event.amountCents() <= 0) {
throw new IllegalArgumentException("Invalid amount for " + event.orderId());
}
kafkaTemplate.send("payments", event.orderId(), event);
}
}If onOrder throws, the container aborts the transaction. The record sent to payments is discarded for read_committed consumers, and the offset is not committed. The error handler then decides whether to retry or route the record to a dead-letter topic.
To use a transaction outside a listener, for example in a REST handler, call kafkaTemplate.executeInTransaction(...) or annotate a method with @Transactional.
Common mistakes
- Consumers left at
read_uncommitted. They read records from aborted transactions, so the atomicity is invisible to them. - Expecting database changes to join the transaction. A Kafka transaction covers only Kafka. A database write in the listener can still commit while the Kafka transaction aborts, or the reverse. Make database handling idempotent, or use an outbox pattern.
- Running with fewer brokers than the transaction state log needs. The default
transaction.state.log.replication.factoris 3. A single-broker development setup must lower it, and so musttransaction.state.log.min.isr. - Reusing one
transactional.idacross running instances. Instances fence each other out. Spring'stransaction-id-prefixplus its per-producer suffix avoids this when you use it as intended.
Exercise
A listener reads from orders and sends to payments inside a Kafka transaction. The application crashes after the send but before the commit. What does a consumer of payments with isolation-level: read_committed see after the restart, and why?
Show answer
It sees exactly one payment record per order. The crashed transaction was never committed, so it is aborted and its record is hidden from read_committed consumers. The offset was not committed either, so the restarted listener reads the order again and sends the result in a new transaction that commits.