Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Kafka Exactly-Once Processing
& Zombie Fencing.

In Kafka consume-transform-produce EOS pipelines, a stalled producer waking from a GC pause becomes a 'zombie' that can commit duplicate outputs unless fenced by a deterministic transactional.id and monotonically increasing producer_epoch.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When a single bottleneck threatens end-to-end availability, assign a deterministic, partition-bound `transactional.id`, call `initTransactions()` to bump `producer_epoch` and fence zombies, commit consumer offsets via `sendOffsetsToTransaction()`, and configure downstream consumers with `isolation.level=read_committed`.

TL;DR30-second simplified summary
▾

Core Mechanics: A Kafka 3.6 fraud-scoring pipeline (acks=all, enable.idempotence=true, 32 partitions, 15,000 events/sec) reads payments.raw, scores events, and writes payments.scored atomically.

Visual & Structural Flow: Depicts Producer Epoch Bump Fences Stalled GC Pod (Zombie Pod (e=1) -> Tx Coordinator -> New Pod (e=2) -> Downstream); Two-Phase Commit Across Topic & consumer_offsets (payments.raw -> Tx Coordinator -> payments.scored -> consumer_offsets).

Trade-Offs & Production: Generating a random UUID for transactional.id on every pod startup breaks fencing completely: the replacement pod gets a new transactional.id instead of bumping the. Guarantee end-to-end EOS across rebalances and 20–30s GC pauses: Deterministic transactional.id + Static Membership (EOS v2): Bind transactional.id and group.instance.id.

Failure Modes & Application: Fenced transactional streaming is critical whenever duplicate events cause financial or state corruption: Real-Time Fraud & Risk Scoring: Ensures every payment is scored and alerted once across pod evictions.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why Kafka Exactly-Once & Zombie Fencing Matter.

Why this matters: The mechanism: understand how Why Kafka Exactly-Once & Zombie Fencing Matter works from first principles.

Think of Why Kafka Exactly-Once & Zombie Fencing Matter as the intuition layer for Kafka Exactly-Once Processing & Zombie Fencing: The mechanism: understand how Why Kafka Exactly-Once & Zombie Fencing Matter works from first principles.

A Kafka 3.6 fraud-scoring pipeline (acks=all, enable.idempotence=true, 32 partitions, 15,000 events/sec) reads payments.raw, scores events, and writes payments.scored atomically. When a pod hits a 25-second JVM GC pause, Kafka rebalances its partition to a replacement pod—then the stalled 'zombie' pod wakes up and commits duplicate outputs.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Real-World Impact of Unfenced Zombie Producers.

Why this matters: The problem: see what breaks without Real-World Impact of Unfenced Zombie Producers under real concurrency or scale.

Without deterministic zombie fencing and read_committed isolation:

  1. Duplicate Downstream Actions: Both the waking zombie and the new owner write scored fraud events for the same input offset.
  2. Dirty Reads: Downstream consumers using default read_uncommitted process messages from aborted transactions.
  3. Split Offset Commits: Committing consumer offsets separately from producer.send() creates a crash window between output write and offset commit.
Kafka EOS Zombie Fencing

Producer Epoch Bump Fences Stalled GC Pod

Zombie Pod (e=1)Tx CoordinatorNew Pod (e=2)Downstream1. 25s GC pause -> Rebalancetriggered2. initTransactions(txId) ->epoch=23. Wakes up, sends batch withepoch=14. ProducerFencedException(rejected!)5. Commit Tx + offsets(read_committed)

Deterministic transactional.id bumps producer_epoch on takeover, fencing any stalled zombie with ProducerFencedException.

Engineering Decision Framework
Problem
How to implement Kafka Exactly-Once Processing & Zombie Fencing without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When a single bottleneck threatens end-to-end availability, assign a deterministic, partition-bound transactional.id, call initTransactions() to bump producer_epoch and fence zombies, commit consumer offsets via sendOffsetsToTransaction(), and configure downstream consumers with isolation.level=read_committed.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Kafka Exactly-Once Processing & Zombie Fencing experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive Solution (and Why It Breaks).

Why this matters: The problem: see what breaks without Naive Solution under real concurrency or scale.

Think of Naive Solution (and Why It Breaks) as the intuition layer for Kafka Exactly-Once Processing & Zombie Fencing: The problem: see what breaks without Naive Solution under real concurrency or scale.

Generating a random UUID for transactional.id on every pod startup breaks fencing completely: the replacement pod gets a new transactional.id instead of bumping the producer_epoch of the stalled pod, so the zombie's old epoch remains valid! Likewise, leaving downstream consumers on read_uncommitted exposes uncommitted/aborted records.

Request & State Flow

Naive Solution (and Why It Breaks)

Producer / TXBroker PartitionConsumer GroupDLQ / Retry1. Append event with idempotencykey2. Deliver batch in partitionorder3. Route poison pill after maxretries4. Commit offset after durablesink
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise Solution: Deterministic `transactional.id` + `sendOffsetsToTransaction()`.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Guarantee end-to-end EOS across rebalances and 20–30s GC pauses:

  • Deterministic transactional.id + Static Membership (EOS v2): Bind transactional.id and group.instance.id to the pod's stable identity (e.g., StatefulSet ordinal fraud-scorer-0). Calling initTransactions() bumps producer_epoch and aborts any open zombie transaction.
  • Atomic Output + Offset Commit: Call producer.sendOffsetsToTransaction(offsets, consumer.groupMetadata()) before commitTransaction() so __consumer_offsets and payments.scored commit atomically.
  • Timeout Alignment & Downstream Isolation: Set transaction.timeout.ms=15000, delivery.timeout.ms=12000, max.poll.interval.ms=30000, and configure downstream consumers with isolation.level=read_committed + idempotent DB ON CONFLICT DO NOTHING.
Atomic Consume-Transform-Produce

Two-Phase Commit Across Topic & __consumer_offsets

payments.rawPoll + score batchTx Coordinatorepoch fencing + 2PCpayments.scoredread_committed view__consumer_offsetsAtomic offset commit

1.Epoch Fencing: Coordinator rejects any write with epoch < current producer_epoch.

2.EOS v2 Static ID: One deterministic transactional.id per static consumer instance.

3.read_committed: Downstream consumers buffer until LSO (Last Stable Offset) advances.

4.Sink Idempotency: External DB sinks still use ON CONFLICT DO NOTHING for true E2E EOS.

Kafka's Transaction Coordinator atomically commits output messages and input offsets while fencing stale epochs.

// EOS v2: one deterministic transactional.id per static consumer instance
props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "fraud-scorer-" + staticInstanceId);
props.put(ConsumerConfig.GROUP_INSTANCE_ID_CONFIG, staticInstanceId);

producer.initTransactions();
while (running) {
    ConsumerRecords<String, byte[]> records = consumer.poll(Duration.ofMillis(200));
    if (records.isEmpty()) continue;
    try {
        producer.beginTransaction();
        Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>();
        for (ConsumerRecord<String, byte[]> rec : records) {
            byte[] scored = scoreFraud(rec.value());
            producer.send(new ProducerRecord<>("payments.scored", rec.key(), scored));
            offsets.put(new TopicPartition(rec.topic(), rec.partition()), new OffsetAndMetadata(rec.offset() + 1));
        }
        producer.sendOffsetsToTransaction(offsets, consumer.groupMetadata());
        producer.commitTransaction();
    } catch (ProducerFencedException | OutOfOrderSequenceException | AuthorizationException fatal) {
        producer.close(Duration.ZERO);
        consumer.close();
        throw fatal;
    } catch (KafkaException transientEx) {
        producer.abortTransaction();
        resetToCommittedOffsets(consumer);
    }
}

// Mandatory downstream consumer config for EOS
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "fraud-alert-service");
props.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed");
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Kafka EOS & Fencing Apply in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Fenced transactional streaming is critical whenever duplicate events cause financial or state corruption:

  • Real-Time Fraud & Risk Scoring: Ensures every payment is scored and alerted once across pod evictions.
  • Stream Aggregations (Kafka Streams / Flink): Ties RocksDB changelog updates to input offsets.
  • Multi-Stage Financial Pipelines: Combines Kafka EOS with Postgres ON CONFLICT for true end-to-end exactly-once.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

What happens if you use a random UUID for `transactional.id` on every Kafka consumer pod restart?

Recommended Learning Flow