Sub topic 13
Kafka transactions with Spring
This chapter assumes you know topics, partitions, offsets and consumer groups. It also assumes you have a working KafkaTemplate and @KafkaListener, and that you understand acks=all and idempotence from the delivery guarantees chapter.
Why idempotence is not enough
An idempotent producer removes duplicates caused by its own retries. It does this within one producer session and one partition. It does not help when a single unit of work does several things that must succeed or fail together.
Consider a service that reads an order event, computes a result, and writes a result event to another topic. The listener then commits its consumer offset. Two things can go wrong:
- The result is published, but the service crashes before the offset is committed. On restart the input record is read again and a second result is published.
- The service publishes to two topics, and the second send fails. Consumers of the first topic now see an event that has no counterpart.
A Kafka transaction makes a group of produces, and optionally the consumer offset commit, atomic. Either all of them become visible or none of them do.
What a transaction covers
Kafka transactions cover writes to Kafka only. They do not include your database, an HTTP call, or an email. If the listener also updates a SQL database, that update is not part of the Kafka transaction. Use the outbox pattern or an idempotent consumer for that part.
A transaction can include:
- Records sent to one or more topics and partitions.
- The consumer offsets of the records that were processed (consume-transform-produce).
The working model
A transactional producer has a transactional.id. The broker uses it to identify the producer across restarts and to fence out older instances with the same ID, called zombies.
The flow looks like this:
- The producer registers its
transactional.idwith the transaction coordinator on a broker. - It begins a transaction and sends records. The records are written to the partition logs right away, but they are marked as part of an open transaction.
- For consume-transform-produce, the producer sends the consumer offsets to the transaction.
- The producer commits or aborts. The coordinator writes a marker to every partition involved.
Consumers decide whether to see uncommitted data through isolation.level. The default is read_uncommitted, which returns every record, including those from aborted transactions. To get transactional visibility, consumers must use read_committed.
Enabling transactions in Spring Boot
Setting spring.kafka.producer.transaction-id-prefix is enough to turn on transactions. Spring Boot then auto-configures a KafkaTransactionManager and makes the producer factory transactional.
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
isolation-level: read_committed
enable-auto-commit: false
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.OrderEventSpring appends a suffix to the prefix to build each producer's transactional.id. Spring Kafka 3.x uses one producer per consumer-and-partition assignment, which keeps the fencing correct without a unique ID per application instance. Instances of the same application can share the same prefix. Different applications that write to the same cluster should use different prefixes.
With a transactional producer factory, acks must be all, and idempotence is turned on for you. The broker requires transaction.state.log.replication.factor and transaction.state.log.min.isr to be satisfiable. On a single-broker development cluster, set both to 1, or the first transaction will time out.
# Broker settings for a single-node development cluster (for example, in docker-compose environment variables)
# KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
# KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1Pattern 1: producing several records atomically
Annotate a method with @Transactional, and the KafkaTransactionManager starts a Kafka transaction around it. Every KafkaTemplate.send call inside the method joins the transaction.
package com.example.orders;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class OrderFanOut {
private final KafkaTemplate<String, OrderEvent> kafkaTemplate;
public OrderFanOut(KafkaTemplate<String, OrderEvent> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
@Transactional("kafkaTransactionManager")
public void publishToBoth(OrderEvent event) {
kafkaTemplate.send("orders-audit", event.orderId(), event);
kafkaTemplate.send("orders-billing", event.orderId(), event);
}
}If the method throws a runtime exception, the transaction aborts and neither record becomes visible to read_committed consumers. The qualifier is useful when the application also has a JPA transaction manager, because a bare @Transactional would pick the primary one.
Outside any transaction, a transactional KafkaTemplate refuses to send. You can use executeInTransaction for a one-off:
kafkaTemplate.executeInTransaction(ops -> {
ops.send("orders-audit", "o-1", new OrderEvent("o-1", 500));
ops.send("orders-billing", "o-1", new OrderEvent("o-1", 500));
return true;
});Pattern 2: consume-transform-produce
When the listener container itself is given a transaction manager, it starts a transaction before invoking the listener. It also sends the consumed offsets to that transaction before committing. Spring Boot wires the auto-configured KafkaTransactionManager into the container factory when you set the prefix, so the listener only needs to send.
package com.example.orders;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
@Component
public class OrderProcessor {
private final KafkaTemplate<String, OrderEvent> kafkaTemplate;
public OrderProcessor(KafkaTemplate<String, OrderEvent> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
@KafkaListener(topics = "orders", groupId = "order-service")
public void process(OrderEvent event) {
OrderEvent priced = new OrderEvent(event.orderId(), event.amountCents() + 100);
kafkaTemplate.send("orders-priced", event.orderId(), priced);
}
}If the method returns normally, the container commits the transaction. That makes the orders-priced record visible and advances the offset for orders in one step. If the method throws, the transaction aborts. The record on orders-priced stays hidden and the offset is not advanced, so the record is redelivered according to your error handler.
Do not call Acknowledgment.acknowledge() or commit offsets yourself in this mode. The container owns the offsets.
Exactly-once is scoped
This pattern gives exactly-once processing of Kafka-to-Kafka flows, provided downstream consumers use read_committed. Redelivery still happens, since an aborted attempt is retried. What changes is that aborted attempts leave no visible output.
| Situation | Result |
|---|---|
| Listener throws after `send` | Output aborted, offset not committed, record retried |
| Application crashes mid-listener | Transaction times out and aborts, record redelivered |
| Listener writes to a database | Database write is not rolled back by Kafka |
| Downstream consumer uses `read_uncommitted` | Sees records from aborted attempts |
Error handling interaction
With a transaction manager configured, each retry of a failing record runs in a new transaction. A DefaultErrorHandler with a back-off behaves differently depending on how it was configured. By default it seeks the consumer back to the failed record and the next poll retries it. Because the transaction already aborted, nothing from the failed attempt is visible.
When the error handler reaches the dead-letter step, the DeadLetterPublishingRecoverer publishes through a KafkaTemplate. If the recoverer's template is transactional and the publish happens after the listener transaction aborted, the template has no transaction to join. In recent Spring Kafka versions the container handles this by running the recoverer inside a new transaction. If you see "No transaction is in process" errors, check that the recoverer's template comes from the same transactional producer factory and that you are on a current Spring Kafka release.
Common errors
- Timeouts on the first send. Usually the transaction state log cannot be created because the broker has fewer brokers than
transaction.state.log.replication.factor. Lower it on dev clusters. ProducerFencedException. Another producer with the sametransactional.idstarted and took over. This is the zombie fencing working as designed. Check that two different applications do not share a prefix.- Aborted records still visible. The consumer is on
read_uncommitted. Setisolation-level: read_committed. - Consumer appears stuck. A
read_committedconsumer cannot read past an open transaction. A long-running or hung transaction stalls readers of that partition until it completes or times out (transaction.timeout.ms, default 60 seconds). - Database and Kafka disagree. The Kafka transaction does not cover the database. Make the database write idempotent, or use an outbox.
Cost and when to use transactions
Transactions add round trips to the coordinator and commit markers on every partition. Latency and broker load rise, and read_committed consumers wait for commits. Use them when duplicate output or partial output is a real problem and the flow is Kafka-to-Kafka. For simple handlers, an idempotent consumer with at-least-once delivery is often cheaper and easier to run.
Exercise
A listener consumes from orders, sends a record to orders-priced, and the container has a Kafka transaction manager. The listener throws an exception after the send call. A downstream consumer of orders-priced uses the default isolation level. What does that consumer see, and what change would hide the aborted record?
Show answer
With the default read_uncommitted isolation level, the downstream consumer sees the record from the aborted transaction, because it is already in the partition log. Setting isolation.level to read_committed (in Spring Boot, spring.kafka.consumer.isolation-level: read_committed) makes the consumer skip records from aborted transactions.
Exercise
Your listener, running with a Kafka transaction, saves an order to a relational database and then sends an event to Kafka. The send fails and the Kafka transaction aborts. What happens to the database row, and how can you keep the two consistent?
Show answer
The database row stays, because the Kafka transaction does not cover the database. To keep them consistent, write the event to an outbox table in the same database transaction and publish it from there, or make the handler idempotent so the retry of the record does not create a second row.