Video in progress

Strong Middle 📨 Kafka and messaging

How do Kafka transactions work in a read-process-write chain, and why is isolation.level needed?

A transactional producer writes to several topics and commits the consumer offsets in one atomic transaction. With isolation.level=read_committed on the consumer side, only messages from committed transactions are visible, and aborted ones are skipped.

📖 Answer

The flow: read from orders → compute → write to invoices → commit the offset. Without a transaction, a crash is dangerous in two places: the write happened but the offset wasn't committed (duplicate), or the other way around.

In Spring Kafka:

spring:
  kafka:
    producer:
      transaction-id-prefix: billing-tx-
    consumer:
      isolation-level: read_committed

When transaction-id-prefix is set, Spring Boot creates a KafkaTransactionManager and the listener container uses it. The kafkaTemplate.send() calls inside the listener and the offsets go into one transaction; if the listener throws an exception, everything is aborted.

Internally the transaction coordinator on the broker keeps the state in the __transaction_state topic and writes commit/abort markers to the partitions. A read_committed consumer reads up to the LSO (last stable offset): messages after an open transaction aren't given to it until that transaction finishes. That's why long transactions artificially inflate consumer lag.

The default is isolation.level=read_uncommitted. If you set up a transactional producer and forget this on the consumer, aborted messages are still read, and the whole idea is defeated.

A limitation: a DB write doesn't take part in this transaction. For atomicity between a DB and Kafka you need the outbox pattern.