Skip to content
Kafka Is Fun

Production Patterns · Intermediate · Topic 3 of 5

Transactional Kafka Producer

A Kafka transaction writes to several topics and partitions atomically: they are all committed or all aborted. Set a transaction-id-prefix and Spring Boot configures a KafkaTransactionManager and wires it into the listener containers.

application.yml (transaction config)yaml
spring:
  kafka:
    producer:
      transaction-id-prefix: order-service-tx-
      # When this is set, Spring Boot configures a KafkaTransactionManager
    consumer:
      properties:
        isolation.level: read_committed   # consumers then skip aborted transactional records
TransactionalOrderService.javajava
@Service
@Slf4j
public class TransactionalOrderService {

    private final KafkaTemplate<String, Object> kafkaTemplate;

    // Option 1: @Transactional with the KafkaTransactionManager bean
    @Transactional("kafkaTransactionManager")
    public void processOrderWithEvents(Order order) {
        // Both sends are in one Kafka transaction: they commit or abort together
        kafkaTemplate.send("orders.order.created",
            order.getId(), new OrderCreatedEvent(order));
        kafkaTemplate.send("inventory.reservation.requested",
            order.getId(), new ReservationRequest(order));
        // If an exception leaves this method, both records are aborted
    }

    // Option 2: explicit transaction around a callback
    public void processWithExplicitTx(Order order) {
        kafkaTemplate.executeInTransaction(operations -> {
            operations.send("orders.order.created", order.getId(), new OrderCreatedEvent(order));
            operations.send("payments.payment.requested", order.getId(), new PaymentRequest(order));
            return true;   // normal exit commits the transaction
        });
    }
}

Sources

Checked against Spring for Apache Kafka 4.1.1, Spring Boot 4.1.1 and Kafka 4.2 documentation on 11 October 2026. Draft: not yet reviewed by a Kafka specialist, and releases move on, so confirm against the current documentation before you act on it.