๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Transactional Producers: Fencing, Idempotence and Commits

Apache KafkaTransactional Producersโญ Premium

Transactional Producers: Fencing, Idempotence and Commits

Senior level ยท What a transaction actually spans, why fencing exists, and the commit loop you can defend.

Prerequisites

  • !Idempotent producers and sequence numbers
  • !Consumer isolation levels

What You'll Learn

  • 1Explain what one Kafka transaction spans and what it does not
  • 2Describe how producer id and epoch fence zombie writers
  • 3Write a commit loop that aborts and recovers cleanly
  • 4Choose transactional ids that survive a rolling restart

What a transaction spans

A Kafka transaction is atomic across a set of topics for one producer instance. Records written during the transaction and the input offsets that the transaction acknowledges become visible together, or neither becomes visible. That is the entire guarantee, and it is narrower than it first sounds.

props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka1:9092");
props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "billing-sink-0");
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, 5);

The transactional id is what makes this possible across restarts. It maps to a persistent producer id on the broker, so a new process with the same transactional id takes over the identity and the previous incarnation is fenced. Enable idempotence is implied once a transactional id is set, but setting it explicitly documents intent and protects the configuration if the transactional id is ever removed.

What it does not span: any database write, HTTP call or filesystem operation the application performs. Those are outside the broker's view and outside the transaction. If a processor writes to Postgres and then aborts the Kafka transaction, the Postgres write stands and the Kafka output is rolled back, and nothing reconciles the two.

Fencing: why zombie writers cannot double-write

โš ๏ธThe zombie problem is not theoretical

A consumer lagging behind can be blocked, killed, and restarted by an orchestrator while the old process is still running on another host with a longer GC pause. Without fencing, both processes write to the same topic under the same identity and the downstream consumer sees interleaved records from two writers that each believe they are alone.

Every transactional producer carries a producer id and a monotonically increasing epoch. When a new producer with the same transactional id registers, the broker raises the epoch and fences the old one. Any request from the old producer carrying a stale epoch is rejected with an OutOfOrderSequenceException or ProducerFencedException, and the application is expected to shut down rather than retry.

# Inspect the transaction state on the broker
kafka-transactions.sh --bootstrap-server kafka1:9092 --list

# Abort a stuck transaction that has timed out
kafka-transactions.sh --bootstrap-server kafka1:9092 \
  --abort --transactional-id billing-sink-0

Fencing is why the transactional id must be stable across restarts of the same logical writer, and unique per active instance. Reusing one id across two concurrently running instances fences the one that started first, which is correct but surprising if the id was named for a service rather than an instance.

The commit loop, complete

producer.initTransactions();

while (true) {
    ConsumerRecords records = consumer.poll(Duration.ofMillis(500));
    if (records.isEmpty()) {
        continue;
    }

    producer.beginTransaction();
    try {
        for (ConsumerRecord record : records) {
            producer.send(new ProducerRecord(
                "billing.events", record.key(), transform(record.value())));
        }
        // Bind input offsets to the transaction so a crash does not re-read them
        producer.sendOffsetsToTransaction(
            offsetsFor(records), consumer.groupMetadata());
        producer.commitTransaction();
    } catch (ProducerFencedException | OutOfOrderSequenceException e) {
        // Another instance took over this transactional id. Stop.
        throw e;
    } catch (KafkaException e) {
        producer.abortTransaction();
        // Rewind so the same batch is reprocessed under a fresh transaction
        consumer.seekToBeginning(records.partitions());
    }
}

The seek after an abort is not optional. Without it the consumer's position has already advanced past the aborted batch, and the next poll starts after the records that were rolled back, silently dropping them. seekToBeginning on the affected partitions is heavy-handed but safe; seekToOffset with the first offset of the failed batch is the precise version when you have it.

sendOffsetsToTransaction takes the consumer group metadata as well as the offsets, which binds the membership to the transaction. That is what prevents a rebalance during the transaction from committing offsets for a group that has already moved on.

Naming transactional ids that survive a restart

The id must be unique per active producer instance and stable for that instance's lifetime. A common scheme is a fixed prefix plus a stable instance identifier: the pod name, the host name, or a partition index for a sharded writer. A bare service name breaks as soon as two pods of the same deployment start; the second fences the first and one shard stops producing with no error beyond a fenced log line.

# Application config, injected per instance
transactional.id=billing-sink-${HOSTNAME}
# or for a sharded writer
transactional.id=billing-sink-${SHARD_INDEX}

Rolling restarts then hand the id from the terminating instance to the new one on the same host, or fence the old instance when a different host takes the id, and either outcome is safe. What is never safe is two live writers sharing an id, which is a deployment bug that fencing converts from a data-corruption incident into a visible failure.

Recovery and transaction timeouts

Abandoned transactions block consumers set to read_committed until they time out or are aborted. The broker default transaction.timeout.ms is seven days, which is far longer than any operational incident, so a stuck transaction from a killed process stalls a topic for a week unless you abort it explicitly or shorten the timeout.

# Producer side: how long the broker waits for a commit or abort
transaction.timeout.ms=60000

# Consumer side: how long a read_committed consumer waits on an incomplete transaction
max.poll.records=500

Sixty seconds is a common producer timeout for pipelines that commit frequently; a transaction that has not committed in a minute is already an incident. Pair it with monitoring on open transaction age so a stuck one is visible long before it expires, and a runbook step that runs the abort command above.

Testing transactional behavior before production

The failure modes of a transactional producer are hard to observe in a happy-path test, which is why most teams discover them in production. A test that starts a producer, sends ten records, commits and exits tells you the happy path works and nothing about what happens when a rebalance interrupts a commit, when the coordinator is unreachable during a network partition, or when two instances briefly share a transactional id during a rolling deploy. Each of those is a scenario worth reproducing deliberately in a test harness before the code reaches production.

The simplest way to make these failures visible is to build a test that kills the producer mid-transaction and asserts that the output topic contains no partial batch. Start a transactional producer, send a known number of records without committing, then close the producer abruptly. Consume the topic with a read_committed consumer and assert that the batch is entirely absent. Then commit the same batch and assert it is entirely present. A test that catches a partial batch would have caught the class of bug where offsets and output are committed separately rather than atomically.

The second scenario worth automating is the zombie fencing test. Start two producer instances with the same transactional id, send a record from the first, then start the second and attempt to send from the first again. The expected outcome is a ProducerFencedException on the first instance. Teams that skip this test often ship a deployment where a stale pod continues to write after a failover, because nothing in the code path ever raised the exception and the application was written to retry on any KafkaException rather than exiting on fencing.

The third scenario is a timeout induced abort. Set transaction.timeout.ms very low, hold a transaction open past that duration, and assert that the coordinator aborts it and that the consumer sees no records from the aborted batch. This catches the common mistake of relying on the default seven day timeout and only discovering months later that a stuck transaction from a killed process has been blocking readers the entire time.

None of these tests require a real cluster beyond a single broker and a test topic, and each one can run in a continuous integration pipeline in under a minute. The cost is small; the incidents they prevent are not.

Common Mistakes

Using a bare service name as the transactional id

Fix: Include a stable instance identifier such as the pod name or a shard index. A shared id makes the second instance fence the first, and one writer silently stops.

Forgetting to seek after an abort

Fix: Rewind the consumer to the first offset of the failed batch before the next poll, otherwise the rolled-back records are skipped.

Writing to a database inside the transactional block and assuming it commits atomically

Fix: Kafka transactions cover only Kafka writes and offsets. Route critical side effects through an output topic or make the external write idempotent.

Leaving transaction.timeout.ms at the seven day default

Fix: Set it to a value that matches your commit cadence, and alert on open transaction age so stuck transactions are caught in minutes rather than days.

Best Practices

  • Set transactional id to a stable per-instance identifier and document the naming scheme in the deployment
  • Bind input offsets with sendOffsetsToTransaction using consumer group metadata, not offsets alone
  • Catch ProducerFencedException as fatal and exit; retrying against a fenced id never succeeds
  • Monitor open transaction age and abort stuck transactions from a runbook step
  • Consume transactional topics with read_committed isolation, enforced in shared client configuration

Interview Questions

Q1: What does a Kafka transaction guarantee?

Atomic visibility of the records a producer writes and the input offsets it acknowledges in that transaction. Both become visible to read_committed consumers together, or neither does. It does not cover side effects outside Kafka.

Q2: How does fencing prevent a zombie writer?

Each transactional id maps to a producer id with a monotonically increasing epoch. A new registration raises the epoch, and requests from the old producer with a stale epoch are rejected, so the old instance cannot write.

Q3: Why must you seek after aborting a transaction?

The consumer position advanced when the batch was polled. Without rewinding, the next poll starts after the rolled-back records and silently skips them.

Q4: Why pass consumer group metadata to sendOffsetsToTransaction?

It binds the offset commit to the group membership, preventing a rebalance during the transaction from committing offsets for a group that has already moved the partition to another member.

Q5: What happens when a process dies mid-transaction?

The transaction stays open until transaction.timeout.ms expires or is aborted explicitly. read_committed consumers block behind it, which is why the timeout is set to minutes and stuck transactions are monitored and aborted.

Key Takeaways

  • A transaction spans Kafka writes and input offsets for one producer instance; nothing outside Kafka participates
  • Fencing via producer id and epoch is what stops a zombie writer from double-writing under the same identity
  • The commit loop always seeks after an abort, and treats ProducerFencedException as fatal
  • Transactional ids must be unique per active instance and stable across that instance's lifetime
  • Short transaction timeouts plus age monitoring keep a stuck transaction from blocking readers for days
๐Ÿ”’

Premium Content

Transactional Producers: Fencing, Idempotence and Commits

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement