Transactions

A transactional producer writes records and consumer offsets as one unit. Everything it wrote becomes visible together when the transaction commits, and none of it becomes visible if the transaction aborts.

// Write a record in a transaction, which commits when the body succeeds
import cats.data.NonEmptyList
import cats.effect.IO

import xkafka.*

val utf8 = Serializer.utf8[IO]

val program =
  for
    client   <- ClientSettings.from(NonEmptyList.one("localhost:9092")).liftTo[IO]
    id       <- TransactionalId.from("order-writer").liftTo[IO]  // Give each producer running alongside another its own id
    settings <- TransactionalProducerSettings.from(client, id, utf8, utf8).liftTo[IO]
    topic    <- Topic.from("events").liftTo[IO]
    record    = ProducerRecord(topic, "key", "value")
    // Commits if this succeeds, and aborts if it fails or is cancelled
    _        <- KafkaClient[IO].transactionalProducer(settings).use(_.transactionally(_.produce(NonEmptyList.one(record))))
  yield ()

transactionally commits the transaction if its body succeeds, and aborts it if the body fails or is cancelled.

If the commit itself fails, transactionally fails with that error:

An abort that fails is likewise asked for again before the next transaction begins.

A transactional producer only writes inside transactions.

Kafka allows one transaction at a time per transactional id, so concurrent calls to transactionally on one producer run one after another.

Do not nest transactionally on the same producer. The inner call waits for the outer transaction to finish, and the outer transaction cannot finish until its body returns, so the pair deadlocks. Use one transaction per unit of work, or a second producer with its own transactional id.

Reading what a transaction wrote

Records written by an open transaction are already in the log, and a consumer delivers them by default. To read only committed records, set the isolation level:

// Read only the records of committed transactions
settings.withIsolationLevel(IsolationLevel.ReadCommitted)

The default is IsolationLevel.ReadUncommitted, which is also Kafka's default. It delivers every record as soon as it is written, including records from a transaction that later aborts.

Read, process, write

commitOffsets adds the offsets a consumer has reached to the transaction, so the records produced and the position they were produced from are committed together:

// Write each chunk's results and consumed offsets in one transaction
consumer.records.chunks.evalMap: chunk =>
  val batch = CommittableOffsetBatch.fromFoldable(chunk.map(_.offset))  // The offsets to commit for these records
  producer.transactionally: transaction =>
    transaction.produce(derive(chunk)) *> transaction.commitOffsets(batch)  // Both become visible together, or neither does

The batch already identifies the consumer its offsets came from, so commitOffsets needs no consumer argument and cannot record them against the wrong group.

If a partition is revoked after its records were read, their offsets can no longer be committed. commitOffsets fails with ErrorCode.IllegalGeneration, and transactionally aborts the transaction, so none of it becomes visible. Read the records again and process them in a new transaction. See Offsets and rebalances.

The pipeline is only atomic end to end if whatever reads the output topic also sets IsolationLevel.ReadCommitted. A reader left on the default sees records from transactions that have not committed, including ones that later abort.

produce inside a transaction returns F[NonEmptyList[Produced]] rather than the two stages a plain producer offers. A transaction cannot commit records the broker has not acknowledged, so the call waits for them.

Settings

TransactionalProducerSettings takes the producer's client, serializers, and properties, along with these values:

setting default meaning
transactionalId required Kafka's transactional.id
transactionTimeout 60s how long the broker lets a transaction stay open before it aborts it (Kafka's transaction.timeout.ms), and how long creating the producer waits to be ready for transactions; at least 1 second
closeTimeout 60s how long releasing the producer waits for records it has not delivered
compression Compression.Uncompressed how record batches are compressed
linger 5ms how long a record waits for others to join its batch, from zero to under 5 minutes, and under transactionTimeout
batchSize unset, which leaves it to the platform's client the most bytes one batch holds before it is sent
enqueueTimeout 60s how long produce waits for room for a record while the client's buffer is full

A transactional producer always uses Acks.AllReplicas and idempotence, because Kafka requires both for transactions, so neither can be changed.

Give each producer that runs alongside another its own transactionalId. Creating a second producer with an id already in use fences the first, and its open transaction can then no longer commit. That is the intended behaviour when a replacement takes over from an instance that has stopped, and a source of failures when two producers were meant to run at the same time.