Scrivio Interview library
Kafka6 August 202615 min read

Debugging Kafka in Production: Four Failure Modes and Their Parameters

The Coordinator Cannot Tell a Slow Consumer From a Dead One#

The orders-events topic has 12 partitions, consumed by six instances of a payments-enrichment service. Roughly every five minutes, the group logs a rebalance, all 12 partitions get reassigned, and consumers resume from the last committed offset, replaying records that were already enriched. No pod restarted, no broker went offline, and the processing code threw no exception. The consumers are, by every process-level measure, alive.

Why does a healthy, correct-looking consumer keep getting evicted and falling behind? The answer starts with what poll() actually does. It is not a data-fetching call with coordination bolted on the side. Once a consumer subscribes, the poll loop handles coordination, partition rebalances, heartbeats, and data fetching, and returns records as its visible output1. Group membership work happens on the poll loop's schedule, not the application's.

Because of that, liveness is judged by two independent clocks, and they measure different things.

ClockDriven byControlling parameter and defaultWhat expiry triggersWhat it cannot detect
SessionBackground heartbeat thread sending heartbeats to the group coordinatorsession.timeout.ms, 45 seconds on Kafka 3.0+, with heartbeat.interval.ms at 3 seconds1Broker removes the client from the group and initiates a rebalance2An application thread stuck inside processing: heartbeats keep flowing while no records advance
Poll intervalThe application thread returning to poll()max.poll.interval.ms, 5 minutes by default2Consumer is considered failed and its partitions are reassigned to another member1A hard process death sooner than the session clock would catch it

The heartbeat clock answers "is the JVM reachable?" The poll clock answers "is this member still making progress?" A consumer that is slow rather than dead keeps the first clock satisfied while running the second one down. The coordinator sees the same outcome either way: a member that stopped participating, so the partitions move.

That puts the open question in a specific place. Each instance polls up to 500 records at a time, the default for max.poll.records2. How long does the service take to work through one of those batches, worst case, including the enrichment lookups? Nobody on the team had measured it. That number, checked against the five-minute poll interval, is what decides whether this group is stable, and it is not the number most rebalance investigations start with.

Measuring it does not require broker access. The Java clients report through the built-in Kafka Metrics registry, which exposes everything over JMX3. rebalance-rate-per-hour and last-rebalance-seconds-ago on consumer-coordinator-metrics3 tell you the cadence; records-lag-max3 tells you the cost. Each of the four failure modes ahead has a signal like these that identifies it before you touch a parameter.

Diagram as text
sequenceDiagram
 participant App as App thread
 participant HB as Heartbeat thread
 participant GC as Group coordinator
 participant B as Other member

 App->>GC: poll()
 GC-->>App: 500 records
 Note over App: poll clock starts
 App->>App: enrich batch, ~90s

 HB->>GC: heartbeat every 3s
 GC-->>HB: member alive
 Note over HB,GC: heartbeats keep flowing during processing

 alt Clock 1: no heartbeat within session.timeout.ms, 45s
 GC->>GC: remove member, start rebalance
 else Clock 2: no poll within max.poll.interval.ms, 5 min
 GC->>GC: mark member failed, start rebalance
 end

 GC->>B: assign revoked partitions
 B->>GC: poll()
 GC-->>B: records replayed from last committed offset

Rebalance Storms: The Batch Size Is What Evicts You, Not the Session Timeout#

Here is the payments-enrichment consumer as it usually ships, with no poll tuning at all:

Java
@KafkaListener(topics = "payments", groupId = "payments-enrichment")
public void onBatch(List<ConsumerRecord<String, Payment>> records) {
for (ConsumerRecord<String, Payment> record: records) {
Enrichment e = riskService.lookup(record.value().accountId()); // ~180 ms
sink.write(enrich(record.value(), e));
}
}

With nothing configured, max.poll.records defaults to 5002 and max.poll.interval.ms to five minutes2. Five hundred records at 180ms each is a 90 second batch, comfortably inside the bound, and this runs fine for months. Then the risk service degrades to 700ms per call. The same batch now takes close to six minutes, poll() does not return in time, and the coordinator declares the member failed and reassigns its partitions2. The evicted consumer finishes its batch, tries to commit, discovers it no longer owns the partitions, rejoins, and gets handed another 500 records to fail on. The group churns roughly every five minutes without a single process dying.

The instinctive response is to raise session.timeout.ms from its 45 second default to something generous2. That knob cannot help here, because heartbeats were never the failing clock. The heartbeat thread runs independently of your processing thread and keeps sending its beat every three seconds2 while the application thread grinds through record 312 of 500. The session never expires. Raising it further only slows down detection of consumers that genuinely die.

The signal that distinguishes this from every other rebalance cause is its regularity: rebalance log lines repeating on a near-fixed cadence, rebalance-rate-per-hour well above zero, and no process restarts or OOM kills to explain them. When the cadence tracks your worst-case batch duration rather than a deployment or a broker event, the poll interval is what is expiring.

The parameter that moves it is max.poll.records. Set it so that worst-case per-record time multiplied by the batch size stays under max.poll.interval.ms with real headroom: at 700ms per record, 50 records gives a 35 second batch against a 300 second bound. Pair that with a hard timeout on riskService.lookup so a single hung call cannot stall the loop, and move genuinely long work off the polling thread entirely1. Kafka Streams users get the same eviction behavior, since application.id is what Streams uses as the consumer group.id for coordination4.

Smaller batches stop the thrashing. They do not make the consumer faster, and on payments-enrichment the lag that piled up during the storm will sit there refusing to drain even after the group goes stable. Raising max.poll.records back up will not fix that either, because max.poll.records does not change what the consumer fetches from the broker2. The ceiling is somewhere else.

Lag That Never Drains: Partition Count Is a Hard Ceiling, Fetch Sizing Is a Soft One#

Do the arithmetic on the orders topic. Twelve partitions, six consumer instances, two partitions each. Cutting max.poll.records stopped the eviction loop, but total lag still sat at four million records and barely moved. So you double the fleet to twelve: each instance now owns one partition, and drain rate roughly doubles. Encouraged, you scale to eighteen. Nothing changes. Six of those instances report assigned-partitions of zero and consume nothing at all, because a partition can be assigned to only one consumer within a group, and consumption parallelism is bounded by the partition count5.

That is the hard ceiling, and no client parameter moves it. Twelve partitions means twelve concurrent readers, whatever your deployment says. Raising it means adding partitions to the topic, which changes key-to-partition mapping for every future record and therefore changes ordering guarantees for existing keys. Plan that as a data change, not a scaling knob.

The softer limit shows up once you are at or below the ceiling and the consumers still look bored: CPU idle, no rebalances, records-consumed-rate low, lag flat. Under-fed rather than under-provisioned. The consumer reports these over the same JMX registry3, and the pairing to watch is max lag alongside minimum fetch rate: for a consumer to keep up, lag needs to stay under threshold while fetch rate stays above zero3. Four settings shape how much arrives per fetch, and each trades one thing away.

SettingDefaultRaise it forPay for it with
fetch.min.bytes1 byte2Fewer requests, better broker throughputAdded latency while data accumulates
fetch.max.wait.ms500 ms2More batching per responseSlower responses on quiet partitions
max.partition.fetch.bytes1 MiB2Larger batches from a lagging partitionConsumer memory, per partition
fetch.max.bytes50 MiB2Bigger total responseConsumer memory, per fetch

The first two work together: if fetch.min.bytes is not satisfied, the broker holds the request until fetch.max.wait.ms expires and then returns whatever it has. Raising the byte floor without raising the wait buys you little.

One caution on max.partition.fetch.bytes. During heavy lag, a generous per-partition limit lets a single partition dominate the returned batch, which shrinks the mix of partitions in each poll and can reduce how much work your processing threads parallelize6.

Add partitions, size the fetch, and eleven of twelve drain cleanly while one stays flat. That last one is not a consumer problem.

Hot Partitions: Flat Lag on One Partition Is a Key Problem#

The payments-enrichment group is now in what should be a healthy state: twelve partitions on orders-events, twelve consumer pods, fetch sizing tuned. Eleven of those pods drain to near-zero lag within a minute. The twelfth sits at 180,000 records and climbing, its pod pinned at 100% CPU while five others idle at 4%. Adding a thirteenth pod does nothing, because there is no unassigned partition for it to take.

Aggregate lag hides this completely. Summed across the group, 180,000 records spread over twelve partitions reads as a mild backlog. The diagnostic move is to stop summing. Break lag out per partition, and the shape changes: eleven partitions near zero, partition 7 holding the entire number. records-lag-max is the consumer-published metric that surfaces this, exposed over JMX from the client's own metrics registry, so you can see it without any broker-side tooling3. Kafka's own monitoring guidance is to watch max lag across partitions rather than an average, precisely because the max is where skew shows up3.

Partition 7 is where one large merchant lands. That merchant produces about 70% of the topic's traffic, and every one of its records carries the same merchant_id as the message key. The key is not a slice of the payload the producer happens to hash. It is a first-class field with its own serializer: key.serializer and value.serializer are separate high-importance producer properties, each implementing org.apache.kafka.common.serialization.Serializer7. The default partitioner hashes that key when one is present, so identical keys land on the same partition every time7. No consumer setting can undo that assignment. max.poll.records and fetch sizing both operate after the record has already been placed.

The three levers all live on the producer, and each trades away some ordering:

  • Salt the key (merchant_id:0 through merchant_id:9): spreads one hot merchant across ten partitions, and costs per-merchant ordering while preserving order within each salt bucket.
  • **Custom Partitioner** implementation via partitioner.class: routes known-hot keys across a reserved partition range while everything else hashes normally, and costs ordering only for the keys you deliberately spread7.
  • **partitioner.ignore.keys=true**: stops the producer using keys for placement entirely, giving even distribution at the cost of all per-key ordering (and it has no effect if a custom partitioner is already set)7.

That trade is the point. A key buys you a guarantee: same key, same partition, records read back in the order they were written. Skew is the price of that guarantee, and every fix above pays for throughput with some of it.

Diagram as text
flowchart LR
 HK["Hot merchant key: 70%"]
 OK["Other merchant keys"]

 subgraph TOPIC["orders-events, 12 partitions"]
 PHOT["One hot partition"]
 REST["Other 11 partitions"]
 end

 subgraph CG["12 consumer pods"]
 CHOT["One pod at 100% CPU"]
 IDLE["11 idle pods"]
 end

 LAGH["records-lag-max: millions"]
 LAGO["records-lag-max: near zero"]
 AGG["Aggregate lag hides skew"]
 FIX["Salted key: merchant plus bucket"]

 HK -->|"hash of key"| PHOT
 OK -->|"spread across"| REST
 PHOT -->|"one owner"| CHOT
 REST --> IDLE
 CHOT --> LAGH
 IDLE --> LAGO
 LAGH --> AGG
 LAGO --> AGG

 HK -.->|"fix: salt hot key"| FIX
 FIX -.->|"spreads across buckets"| REST

 classDef hot fill:#f8d7da,stroke:#b02a37,color:#000
 classDef cold fill:#e7f1ff,stroke:#4a7ebb,color:#000
 classDef fix fill:#d1e7dd,stroke:#0f5132,color:#000
 class HK,PHOT,CHOT,LAGH hot
 class OK,REST,IDLE,LAGO cold
 class FIX fix

Duplicates and Reordering: Producer Retries Without Idempotence#

The nightly reconciliation on payments-enrichment comes back with 312 double-charged records and eleven applied out of order. Consumer logs are clean: no rebalances, no deserialization errors, lag sitting at zero all night. The only correlated event is a broker restart at 02:10. Of the four root causes, this is the one that produces no alarming signal on the consumer side at all, because nothing on the consumer side went wrong.

What went wrong is upstream. The producer sent a batch, the leader appended it to its log, and the acknowledgement was lost or delayed past request.timeout.ms. From the producer's point of view that request failed, so it resent the same records, and the broker appended them a second time. The Kafka docs call this out directly: request.timeout.ms should exceed the broker's replica.lag.time.max.ms specifically to reduce message duplication from unnecessary producer retries8. Reordering follows from the same retry, one step removed. With more than one request in flight to a partition, batch 1 can fail and be retried while batch 2 succeeds, so batch 2's records land first8. The per-key ordering the previous section leaned on is gone, and the enrichment service applies a refund before the charge it reverses.

These four properties are one setting, not four. Turning idempotence on requires max.in.flight.requests.per.connection at 5 or below, retries above 0, and acks=all; set a conflicting value without explicitly enabling idempotence and the Java client quietly disables it rather than failing8.

PropertySet toWhy it is requiredJava vs librdkafka default
enable.idempotencetrueBroker deduplicates retried batches by sequence number, so exactly one copy is written8true vs false9
max.in.flight.requests.per.connection5 or lessBroker retains at most 5 batches per producer; beyond that earlier batches are dropped and order cannot be restored85 vs 10000009
acksallIdempotence requires it; the leader waits for the full in-sync replica set8all vs verify for your client version
delivery.timeout.msAbove request.timeout.ms + linger.msBounds the whole retry window, so a partition outage fails fast instead of retrying into the next batch8120000 vs 3000009
Java
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "broker-1:9092,broker-2:9092");
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, 5);
props.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 120_000);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

Set all four explicitly rather than trusting a blog post's defaults, including this one. Defaults move between releases: linger.ms changed from 0 to 5 in Apache Kafka 4.08. Open the producer-config reference for the exact broker and client version you run and read the documented default for each property8.

Diagram as text
sequenceDiagram
 participant P as Producer
 participant L as Broker Leader
 participant Log as Partition Log

 rect rgb(255, 235, 235)
 Note over P,Log: Without idempotence: duplicate
 P->>L: Send batch 1
 L->>Log: Append batch 1
 L--xP: Ack lost or delayed
 P->>L: Resend batch 1
 L->>Log: Append batch 1 again
 Note over Log: Two copies in log
 end

 rect rgb(255, 245, 230)
 Note over P,Log: Without idempotence: reordering
 P->>L: Send batch 1 and batch 2
 L--xP: Batch 1 fails
 L->>Log: Append batch 2
 P->>L: Retry batch 1
 L->>Log: Append batch 1
 Note over Log: Batch 2 records appear first
 end

 rect rgb(235, 245, 255)
 Note over P,Log: enable.idempotence=true, acks=all
 P->>L: Send batch 1, id and sequence
 L->>Log: Append batch 1
 L--xP: Ack lost or delayed
 P->>L: Retry batch 1
 L-->>P: Retry deduplicated, order preserved
 Note over P: delivery.timeout.ms bounds whole attempt
 end

Reading the Signal to Pick the Parameter#

What you seeWhat it meansWhat you change
Rebalance log lines repeating, processes never exit, rebalance-rate-per-hour climbing3A poll cycle is exceeding max.poll.interval.msmax.poll.records and per-record processing time; not session.timeout.ms
Aggregate lag flat or growing, every consumer healthy, CPU idleParallelism ceiling, then fetch sizingPartition count first; then fetch.min.bytes, fetch.max.wait.ms, max.partition.fetch.bytes
One partition's lag diverging while the others sit near zeroKey skew concentrating traffic on one partitionKey design, salting, or a custom partitioner upstream
Duplicates or out-of-order records downstream, no consumer-side errorProducer retries resending an unacknowledged batchenable.idempotence=true, max.in.flight.requests.per.connection at or below 5, acks=all8

Every row assumes the signal is visible, and that takes setup. Client metrics come from the built-in Kafka Metrics registry, exposed over JMX3. Remote JMX is disabled by default, and turning it on without security is what makes this a decision rather than a checkbox: an unauthenticated remote JMX port lets outsiders monitor or control not just the client process but the platform it runs on. Authentication is off by default in Kafka, so set KAFKA_JMX_OPTS (or the equivalent Java system properties) with authentication and TLS before opening the port anywhere a network can reach it3. On a locked-down host, an alternative is a metrics reporter that pushes to your monitoring system, which keeps no listening port open at all.

Then alert on the right aggregation. records-lag-max is a client-published metric, not a broker one3, and a group-total lag alarm will happily stay green while partition 7 falls an hour behind: the healthy partitions dilute it to noise. Alert on maximum per-partition lag, with the partition ID in the alert payload. That one change turns the hot-partition row of the table from a thing you discover during an incident into a thing you get paged for, and it collapses your first diagnostic step, since a lag alarm naming a single partition has already told you which root cause you are looking at.

One more habit worth building. Defaults move between versions: linger.ms went from 0 to 5 in Kafka 4.08, and enable.idempotence differs between the Java client and librdkafka9. Bookmark the per-property configuration reference for the exact version and client library you run, and check the property there before you tune it.

Start with the alert. Pull per-partition lag for your busiest consumer group today and look at the spread across partitions; whichever row of the table that spread points at is the one worth your afternoon.

Sources

  1. Kafka Consumer Poll & Timeout Settingsconduktor.io
  2. Kafka Consumer Configuration Reference for Confluent ...docs.confluent.io
  3. Monitoring - Apache Kafkakafka.apache.org
  4. Configuring a Streams Application | Apache Kafkakafka.apache.org
  5. Kafka Performance: Understanding and Optimizing the 5 Phases of End-to-End Latency - Florian Courougefloriancourouge.com
  6. Latency and Throughput - Karafka framework documentationkarafka.io
  7. Producer Configs | Apache Kafkakafka.apache.org
  8. Kafka Producer Configuration Reference for Confluent Platform | Confluent Documentationdocs.confluent.io
  9. Kafka Client Configuration Reference | All Properties, Error Handling, Retry Logic | Confluent Documentationdocs.confluent.io

Keep reading

Kafka13 August 2026

How Kafka Rebalances a Consumer Group, Step by Step

The orders topic has six partitions. Consumer A owns 0 through 2, consumer B owns 3 through 5, and both are keeping pace with the write rate. Ahead of a traffic spike you start a...

13 min readRead the article
Kafka12 August 2026

How Kafka Handles Backpressure: Durable Log, Pull Consumers, Blocking Producers

send() is asynchronous in a specific and limited sense: it hands a record to an in-memory buffer and returns. When that buffer has no room, it does not return. A payments service...

14 min readRead the article
Kafka22 May 2026

Five Kafka Design Patterns Every Backend Engineer Should Know

Kafka is a distributed commit log. Producers append records to topics; consumers read those records independently, each maintaining their own offset into the log. Unlike a...

18 min readRead the article