Prev Next

Integration / Kafka real time troubleshooting and scenario based Interview questions

Last updated

1. What is consumer lag and how do you check it? 2. What does an under-replicated partition indicate? 3. How do you troubleshoot steadily growing consumer lag? 4. Why does a consumer group keep rebalancing? 5. What happens when a broker fails with replication factor 3 and min.insync.replicas=2? 6. Why do producers throw NotEnoughReplicasException? 7. Why do duplicate messages appear after a consumer restart? 8. Why do messages arrive out of order in Kafka? 9. How do you fix one partition having huge lag while the others are fine? 10. How do you troubleshoot a producer TimeoutException saying records expired? 11. What happens when a consumer exceeds max.poll.interval.ms? 12. How do you fix RecordTooLargeException for large messages? 13. What do you do when a Kafka broker's disk is full? 14. What happens when a partition leader fails and no in-sync replica is available? 15. How do you troubleshoot slow consumer processing? 16. Why did consumer offsets reset unexpectedly to earliest or latest? 17. How do you replay messages from a specific point in time? 18. How do you handle a poison pill message that blocks a consumer? 19. How do you troubleshoot deserialization errors in a Kafka consumer? 20. How do you handle a breaking schema change safely with Schema Registry? 21. How do you troubleshoot NotLeaderOrFollowerException and LEADER_NOT_AVAILABLE errors? 22. How do you diagnose high request latency on a Kafka broker? 23. What happens when the active KRaft controller fails? 24. Why does a consumer get CommitFailedException? 25. How do you build exactly-once consume-transform-produce processing in Kafka? 26. How do you troubleshoot ProducerFencedException in a transactional producer? 27. How do you safely increase the partition count of a live topic? 28. How do you rebalance data after adding a new broker to a cluster? 29. How do you troubleshoot long GC pauses on a Kafka broker? 30. How do you troubleshoot a failed Kafka Connect task? 31. How do you troubleshoot MirrorMaker 2 replication lag? 32. How do you troubleshoot SSL handshake failures between Kafka clients and brokers? 33. How do you troubleshoot SASL authentication failures in Kafka? 34. How do you troubleshoot TopicAuthorizationException? 35. Why can clients connect to the bootstrap server but fail to reach the brokers? 36. What problems do too many partitions cause in a Kafka cluster? 37. How do you troubleshoot log compaction that is not cleaning up a topic? 38. Why is data retained longer than retention.ms? 39. How does static membership reduce rebalances during rolling deployments? 40. How do you troubleshoot slow state restore in a Kafka Streams application? 41. How do you handle a Kafka Streams thread that dies from an exception? 42. How do you perform a rolling restart of Kafka brokers safely? 43. How do you handle a sudden 10x spike in Kafka traffic? 44. How can you reduce end-to-end latency in a real-time Kafka pipeline? 45. How do you improve Kafka producer throughput? 46. How do you troubleshoot replicas repeatedly falling out of the ISR because of network problems? 47. How do you fix uneven load across Kafka brokers? 48. How do you fix 'Too many open files' on a Kafka broker? 49. Which metrics should you alert on to monitor Kafka health? 50. What happens when an entire availability zone fails in a Kafka cluster?

1. What is consumer lag and how do you check it?

Consumer lag is the gap between the newest offset written to a partition (the log-end offset) and the offset your consumer group has committed for it. A lag of 0 means the consumer is fully caught up; a growing lag means producers are writing faster than the group is processing.

Lag is tracked per partition, so always look at the individual numbers and not only the total. One stuck partition can hide behind a healthy-looking sum.

kafka-consumer-groups.sh --bootstrap-server broker1:9092 \
  --describe --group orders-cg

The output lists CURRENT-OFFSET, LOG-END-OFFSET and LAG for every partition, along with the consumer id that owns it.

Offset lag does not tell you how stale the data is. A lag of 10,000 records can mean two seconds on a busy topic or two days on a quiet one, so many teams also track time lag using tools such as Burrow, Kafka Exporter with Prometheus, or the consumer's records-lag-max metric.

Take quiz
Consumer lag for one partition is calculated as:
time between producer send and broker acknowledgement
committed offset minus log-start offset
log-end offset minus the group's committed offset
number of consumers minus number of partitions
Why can a healthy total lag still hide a problem?
Committed offsets are shared across all groups
Lag is per partition, so one stuck partition can be masked by the sum
The total always includes the producer's buffer
Lag is only updated once per hour

2. What does an under-replicated partition indicate?

An under-replicated partition is one where the in-sync replica set (ISR) is smaller than the configured replication factor. At least one follower has stopped keeping up with the leader, or its broker is gone.

A follower is dropped from the ISR when it has not caught up to the leader's log end within replica.lag.time.max.ms (30 seconds by default in recent versions). It rejoins automatically once it catches up again.

On its own this is a warning, not an outage: the partition still serves reads and writes. It becomes an outage for producers when the ISR drops below min.insync.replicas and they use acks=all, because writes are then rejected.

kafka-topics.sh --bootstrap-server broker1:9092 \
  --describe --under-replicated-partitions

Typical causes are a stopped or restarting broker, a slow disk, GC pauses, or network trouble between brokers. Alert on the UnderReplicatedPartitions metric when it stays above zero for more than a few minutes.

Take quiz
A partition is under-replicated when:
its log-end offset equals the committed offset
it has no messages for retention.ms
its ISR is smaller than the replication factor
its leader has more than one consumer group
Which command lists only the partitions with a shrunken ISR?
kafka-log-dirs.sh --describe
kafka-topics.sh --describe --under-replicated-partitions
kafka-consumer-groups.sh --describe --state
kafka-acls.sh --list --topic

3. How do you troubleshoot steadily growing consumer lag?

First decide whether the problem is on the input side (producers sending more than before) or the processing side (consumers got slower). Compare the log-end offset growth rate with the consumer's current-offset progress.

  1. Run kafka-consumer-groups.sh --describe and see if lag is spread evenly or sits on a few partitions.
  2. Check the group state. If it keeps rebalancing, no one is making progress.
  3. Measure the time spent per poll() loop. Slow database calls, REST calls or locks are the usual culprits.
  4. Look at consumer CPU, GC and pod restarts.
  5. Count consumers against partitions. Extra consumers beyond the partition count sit idle.
Symptom Likely cause
Lag on one partition only Hot key or poison message
Lag on all partitions, consumers busy Slow downstream or too few consumers
Lag jumps, then drops, repeatedly Frequent rebalances
Consumers idle, lag still grows Consumers not assigned partitions or stuck in poll

Fixes follow the diagnosis: batch downstream writes, add consumers up to the partition count, tune max.poll.records, or add partitions if parallelism is capped.

Take quiz
Lag is high on only one partition while others are near zero. What is the most likely cause?
The topic has too few brokers
Too many consumers in the group
acks=0 on the producer
A hot key or a poison message on that partition
Lag keeps growing but your group already has more consumers than partitions. What does adding more consumers do?
Nothing, the extra consumers stay idle
It lowers the log-end offset
It doubles throughput per partition
It forces Kafka to add partitions

4. Why does a consumer group keep rebalancing?

A rebalance starts whenever group membership changes or a member is considered dead. Constant rebalancing usually means members keep leaving and rejoining, even if you did not deploy anything.

The common triggers are:

  1. Poll timeout: processing a batch takes longer than max.poll.interval.ms (default 5 minutes), so the consumer is removed.
  2. Missed heartbeats: long GC pauses or network blips exceed session.timeout.ms.
  3. Pod churn: Kubernetes liveness probes killing slow consumers, autoscalers flapping, rolling deploys.
  4. Subscription changes: regex subscriptions picking up newly created topics.

Search the consumer logs for messages like "consumer poll timeout has expired" or the broker logs for "Member ... has failed"; they tell you which trigger you are hitting.

Common fixes: lower max.poll.records or speed up processing, use the CooperativeStickyAssignor so only the affected partitions move, and set group.instance.id for static membership so a quick restart does not trigger a rebalance at all.

Take quiz
The log says 'consumer poll timeout has expired'. Which setting is being exceeded?
linger.ms
retention.ms
max.poll.interval.ms
fetch.max.bytes
Which assignor limits rebalance disruption to only the partitions that need to move?
RangeAssignor with auto.offset.reset
A custom partitioner on the producer
CooperativeStickyAssignor
RoundRobinPartitioner

5. What happens when a broker fails with replication factor 3 and min.insync.replicas=2?

The controller notices the broker is gone (a session expiry in ZooKeeper mode, missed heartbeats in KRaft) and moves leadership of every partition that was led by it to another replica in the ISR. Clients see a short burst of NotLeaderOrFollowerException, refresh metadata and retry against the new leader.

Each affected partition now has an ISR of 2, which still meets min.insync.replicas=2. Producers with acks=all keep writing, and consumers keep reading. Nothing is lost, because the new leader was in sync.

The cluster has lost its safety margin though. If a second broker holding a replica of the same partition fails, the ISR drops to 1. Reads still work, but acks=all producers get NotEnoughReplicasException until a replica returns.

flowchart TD
  A["Broker fails"] --> B["Controller detects failure"]
  B --> C["New leader elected from ISR"]
  C --> D{ISR size at least 2?}
  D -- Yes --> E["acks=all writes continue"]
  D -- No --> F["Producers get NotEnoughReplicasException"]
  E --> G["Restarted broker catches up and rejoins ISR"]
Take quiz
With RF=3 and min.insync.replicas=2, one broker dies. Can acks=all producers keep writing?
Only after the controller restarts
Only if unclean.leader.election.enable is true
No, all three replicas must be alive
Yes, the ISR is still 2 which meets the minimum
What happens if a second replica of the same partition is lost?
The leader deletes older segments
Consumers stop reading immediately
Kafka silently lowers min.insync.replicas
acks=all writes fail until the ISR is back to 2

6. Why do producers throw NotEnoughReplicasException?

The broker throws it when a producer uses acks=all and the partition's ISR is smaller than min.insync.replicas. The broker refuses the write rather than accept data it cannot replicate safely.

Work through these checks:

  1. Run kafka-topics.sh --describe and compare the ISR column with the replica list.
  2. Find out why a replica left: broker down, slow disk, network issue, GC pause.
  3. Check whether the topic overrides the broker-level min.insync.replicas.
  4. Check the replication factor. With RF=2 and min.insync.replicas=2 you tolerate zero failures, so even a routine restart blocks producers.

The right fix is to bring the missing replica back in sync, not to lower the setting to 1. Lowering it trades durability for availability and should be a deliberate decision.

A related error, NotEnoughReplicasAfterAppendException, means the record was appended but the ISR shrank before it was fully replicated. The producer will retry, which can create a duplicate unless enable.idempotence=true.

Take quiz
A topic has RF=2 and min.insync.replicas=2. What happens during a routine broker restart?
acks=all producers fail because the ISR drops below the minimum
Writes continue with acks=0 automatically
The topic is deleted and recreated
Kafka promotes a consumer to replica
Which setting prevents a retry after NotEnoughReplicasAfterAppendException from creating a duplicate?
auto.offset.reset=earliest
fetch.min.bytes=1
enable.idempotence=true
log.retention.hours=1

7. Why do duplicate messages appear after a consumer restart?

Kafka's default consumer behavior is at-least-once. If a consumer processes a record but crashes before its offset is committed, the next consumer to take the partition starts from the last committed offset and processes that record again.

The common sources of duplicates are:

  • enable.auto.commit=true with an interval that lags behind actual processing.
  • A rebalance that happens between processing and commit.
  • A producer retry after a lost acknowledgement, when idempotence is off.

You cannot remove duplicates by tuning commits alone. The reliable approach is to make processing idempotent:

  1. Turn on enable.idempotence=true on the producer to stop retry duplicates.
  2. Commit manually, only after the work is done.
  3. In the sink, use an upsert or a unique key such as topic-partition-offset or a business id, so reprocessing the same record changes nothing.

For Kafka-to-Kafka pipelines, transactions give exactly-once semantics. They do not cover side effects like a REST call or a database write outside Kafka.

Take quiz
A consumer processes a record, then crashes before committing. What happens on restart?
The broker deletes the record
The record is skipped permanently
The record is processed again from the last committed offset
Kafka moves it to a dead letter topic
Which sink design makes reprocessing duplicates harmless?
A shorter session.timeout.ms
An append-only insert with no key
An upsert keyed by a business id or topic-partition-offset
A larger max.poll.records

8. Why do messages arrive out of order in Kafka?

Kafka guarantees ordering only within a single partition. If related events land on different partitions, or are handled by different threads, their order is not preserved.

Check these causes in order:

  1. No key or the wrong key: events for one entity must share a key so they hash to the same partition.
  2. Producer retries: with max.in.flight.requests.per.connection above 1 and idempotence off, a failed batch can be retried after a later batch succeeds. Set enable.idempotence=true, which preserves order with up to 5 in-flight requests.
  3. Partition count change: adding partitions changes the key-to-partition mapping, so a key's new events may go to a different partition than its old ones.
  4. Parallel processing in the consumer: handing records of one partition to a thread pool can finish them in any order.

If you need parallelism with ordering, route records to worker threads by key, so all records of one key go through the same worker.

Take quiz
Where does Kafka guarantee message ordering?
Across all topics of a cluster
Within a single partition
Across all partitions of a topic
Only when acks=0
Which producer setting preserves order during retries with up to 5 in-flight requests?
compression.type=none
linger.ms=0
enable.idempotence=true
request.timeout.ms=1

9. How do you fix one partition having huge lag while the others are fine?

Start by deciding whether it is a data skew problem or a stuck consumer problem. They look similar in the lag column but need different fixes.

Describe the group and compare the two offset columns for the bad partition:

  • If LOG-END-OFFSET grows much faster than on other partitions, you have a hot key: one key (a big customer, a null-heavy default value) is producing most of the traffic.
  • If CURRENT-OFFSET is frozen, the consumer is stuck on that partition, often on a poison message or a slow downstream call for one specific record.

For skew, change the partitioning: use a composite key (customer id plus a bucket number), a custom partitioner, or split the hot key's work in the consumer. You lose strict per-key ordering for that key if you spread it, so confirm that is acceptable.

For a stuck consumer, check the logs at that offset, apply a retry limit and send the failing record to a dead letter topic. Adding more consumers will not help either way, because one partition is only ever read by one consumer in a group.

Take quiz
One partition's CURRENT-OFFSET is frozen while its LOG-END-OFFSET keeps rising. What does this suggest?
The producer is using acks=0
The consumer is stuck on that partition, often on a bad record
The partition is compacted
The topic has too many replicas
Why does adding more consumers not fix a single hot partition?
Each consumer needs its own topic
Consumers cannot read from leaders
A partition is read by only one consumer in a group
Kafka caps groups at two consumers

10. How do you troubleshoot a producer TimeoutException saying records expired?

The message looks like "Expiring 15 record(s) for orders-3: 120000 ms has passed since batch creation". It means a batch sat in the producer's buffer or in-flight for longer than delivery.timeout.ms (default 120 seconds) without being acknowledged, so the producer gave up on it.

The question is why the broker did not acknowledge in time. Check:

  1. Connectivity: can the producer reach every broker's advertised address, not only the bootstrap server?
  2. Leader availability: an ongoing election or an offline partition leaves batches waiting.
  3. Broker load: high request queue time, a slow disk, or an acks=all write waiting on slow followers.
  4. Quotas: client throttling shows up as a growing produce-throttle-time-avg.
  5. Producer pressure: a full buffer (buffer.memory) blocks send() and ages batches.

Raising the timeout only hides the cause. It is reasonable if you expect short leader elections, but the permanent fix is on the network or broker side. Log the callback exception and handle failures; an expired batch is lost if you ignore the callback.

Take quiz
The error says 'Expiring N record(s)... ms has passed since batch creation'. Which setting bounds this?
replica.lag.time.max.ms
session.timeout.ms
delivery.timeout.ms
max.poll.interval.ms
Which metric points to client quota throttling as the cause?
ActiveControllerCount
records-lag-max
produce-throttle-time-avg
UnderReplicatedPartitions

11. What happens when a consumer exceeds max.poll.interval.ms?

The consumer's heartbeat runs on a background thread, so the broker still sees it as alive. But the client tracks the time between poll() calls itself. If that gap goes beyond max.poll.interval.ms (default 5 minutes), the client assumes the processing thread is stuck, leaves the group and triggers a rebalance.

The partitions are given to other members. When the slow consumer finally finishes and tries to commit, it gets a CommitFailedException, and its records are processed again by the new owner. That is where many duplicate-processing incidents begin.

flowchart LR
  A["poll returns batch"] --> B["Slow processing"]
  B --> C{Gap above max.poll.interval.ms?}
  C -- No --> D["Commit and poll again"]
  C -- Yes --> E["Consumer leaves group"]
  E --> F["Rebalance, partitions reassigned"]
  F --> G["Late commit fails, records reprocessed"]

Fix it by reducing max.poll.records so each batch finishes sooner, speeding up the work, or raising the interval to match realistic worst-case processing time. For genuinely long jobs, hand work to a thread pool and use pause() on the partitions while it runs, continuing to call poll() so the consumer stays in the group.

Take quiz
Which component notices that poll() was not called in time?
The producer's sender thread
The consumer client itself
The ZooKeeper session
The log cleaner thread
Which approach handles very long record processing without being kicked out of the group?
Disable heartbeats
Use acks=0 on the consumer
Pause partitions and keep calling poll() while a worker thread runs
Set session.timeout.ms to 0

12. How do you fix RecordTooLargeException for large messages?

A message has to fit under several limits along its path, and the smallest one wins. The exception usually comes from the producer-side or broker-side limit.

Where Setting
Producer request size max.request.size (default 1 MB)
Broker or topic batch size message.max.bytes / topic max.message.bytes
Follower fetch replica.fetch.max.bytes
Consumer fetch max.partition.fetch.bytes, fetch.max.bytes

You can raise all of them consistently, but large messages hurt broker memory, replication and latency. Before doing that, consider alternatives:

  1. Turn on compression (zstd or lz4); text and JSON shrink a lot.
  2. Use the claim-check pattern: store the payload in S3 or blob storage and send only a reference and metadata through Kafka.
  3. Split the payload into ordered chunks with a shared id.

Note that the limit applies to the compressed record batch on the broker, while the producer checks the uncompressed size against max.request.size first.

Take quiz
Which pattern keeps big payloads out of Kafka while still sending an event?
Claim check: store the payload externally and send a reference
Setting acks=all
Using a single partition
Lowering retention.ms
Raising only max.request.size on the producer is not enough because:
Kafka ignores producer settings
ZooKeeper caps all writes at 1 KB
The broker and topic limit message.max.bytes must also allow the size
Consumers reject all messages

13. What do you do when a Kafka broker's disk is full?

A full disk can crash the broker or, with multiple log directories, take that directory offline and raise KafkaStorageException. Act quickly, but carefully.

  1. Find the biggest consumers of space: kafka-log-dirs.sh --describe shows size per topic-partition.
  2. Free space through Kafka, not the shell: temporarily lower retention on large, non-critical topics, for example kafka-configs.sh --alter --entity-type topics --entity-name clicks --add-config retention.ms=3600000. The log cleaner deletes old segments on its next check.
  3. Never delete segment files by hand while the broker is running; you can corrupt the log and indexes.
  4. Add capacity: grow the volume, or move partitions to other brokers with kafka-reassign-partitions.sh (with a throttle).
  5. Restart the broker if it stopped, and confirm the ISR recovers.

Prevent a repeat with disk alerts at around 70-80%, retention.bytes on high-volume topics, a capacity plan for replication overhead, and tiered storage if your version supports it.

Take quiz
Which is the safe way to free space on a running broker?
Set acks=0
Restart the producers
Delete .log files with rm
Temporarily lower retention.ms on large topics and let the cleaner delete segments
Which tool shows the size of each topic-partition on a broker's disks?
kafka-preferred-replica-election.sh
kafka-delegation-tokens.sh
kafka-console-producer.sh
kafka-log-dirs.sh --describe

14. What happens when a partition leader fails and no in-sync replica is available?

The partition goes offline. With the default unclean.leader.election.enable=false, Kafka refuses to elect an out-of-sync replica, so producers and consumers see LEADER_NOT_AVAILABLE until an ISR member returns.

If you set it to true, the controller may choose a replica that was behind. The partition comes back online immediately, but any records the old leader had acknowledged and the new leader lacks are lost. Consumers that already read past that point may also see offsets that no longer match.

Setting Outcome
false (default) Consistency first; partition stays offline until ISR replica returns
true Availability first; possible data loss and divergence

Choose per topic. Log or metrics topics can tolerate loss for uptime. Payments or orders usually cannot. Watch OfflinePartitionsCount and UncleanLeaderElectionsPerSec, and try to restart the failed brokers first rather than flipping the flag in the middle of an incident.

Take quiz
With unclean.leader.election.enable=false and no ISR replica alive, the partition:
Stays offline until an in-sync replica returns
Switches to acks=0 automatically
Deletes its oldest segment
Elects a random consumer as leader
What is the risk of enabling unclean leader election?
Producers can no longer use compression
Acknowledged records missing on the new leader can be lost
Topics lose their keys
Consumers lose group membership permanently

15. How do you troubleshoot slow consumer processing?

Slow consumers are usually slow because of what happens between polls, not because of Kafka. Start by timing the pieces.

  1. Log or record the time taken by poll() itself and by your processing of each batch.
  2. Find the blocking call: a per-record database insert, a synchronous REST call, a lock, or a retry loop with sleeps.
  3. Check CPU, memory pressure and GC logs on the consumer.
  4. Look at how many records each poll returns; tiny batches mean too many network round trips.

Typical fixes are batching database writes, calling downstream services asynchronously with a bounded concurrency limit, and scaling consumers up to the partition count. If you add a worker pool, keep one worker per key so ordering is retained.

When the work is slow per record, decouple it from the poll loop but keep polling:

consumer.pause(consumer.assignment());
Future f = pool.submit(() -> handle(records));
while (!f.isDone()) { consumer.poll(Duration.ofMillis(100)); }
consumer.resume(consumer.assignment());

This keeps the consumer in the group while the long work runs, so it avoids a poll timeout.

Take quiz
A consumer does one INSERT per record and falls behind. What is the best first fix?
Disable heartbeats
Reduce the partition count
Increase retention.ms
Batch the database writes
What does pause() on assigned partitions let the consumer do?
Skip offsets permanently
Keep calling poll() without fetching new records while work finishes
Change the topic's leader
Commit offsets for other groups

16. Why did consumer offsets reset unexpectedly to earliest or latest?

A consumer falls back to auto.offset.reset (earliest or latest) only when it has no valid committed offset. So the question is why the committed offset disappeared or became invalid.

Common reasons:

  1. Offsets expired: committed offsets are deleted offsets.retention.minutes (7 days by default) after the group becomes empty. A group that was stopped over a long weekend or holiday can lose its position.
  2. Offset out of range: retention deleted the segments containing the committed offset, so it is lower than the log-start offset.
  3. Different group.id: a config change or a new deployment name creates a brand new group.
  4. Topic recreated: the topic was deleted and recreated, so the old offsets point to nothing.

With latest you silently skip data, and with earliest you reprocess everything. Pick the one that fits your pipeline on purpose, increase offsets.retention.minutes for batch-style groups, and alert when lag suddenly jumps to zero or to millions.

Take quiz
auto.offset.reset is applied when:
There is no valid committed offset for the group and partition
Every time poll() is called
When the broker restarts
Only during producer retries
A consumer group stayed stopped for 10 days with default broker settings. What is likely on restart?
Kafka replays the topic from a snapshot
It resumes exactly where it stopped
Its committed offsets expired and it falls back to auto.offset.reset
The group is promoted to the controller

17. How do you replay messages from a specific point in time?

You move the consumer group's committed offsets back to the position that matches the timestamp, then restart the consumers. The group must be inactive (no running members) for the CLI to change its offsets.

# preview first
kafka-consumer-groups.sh --bootstrap-server broker1:9092 \
  --group orders-cg --topic orders \
  --reset-offsets --to-datetime 2026-11-27T10:00:00.000 --dry-run

# apply
kafka-consumer-groups.sh --bootstrap-server broker1:9092 \
  --group orders-cg --topic orders \
  --reset-offsets --to-datetime 2026-11-27T10:00:00.000 --execute

Other options are --to-earliest, --to-offset and --shift-by -5000. From code, use offsetsForTimes() followed by seek().

Before you replay, check three things. The data must still exist, because retention may have removed it. Your downstream systems must tolerate duplicates, so make the sink idempotent. And consider using a new group id for the replay so the production group's offsets are untouched.

Take quiz
The group must be in which state for the CLI offset reset to work?
Rebalancing
Leader of the controller quorum
Reading with isolation.level=read_committed
Inactive, with no running members
Which consumer API finds the offset for a given timestamp?
offsetsForTimes()
endOffsets() only
assignment()
commitAsync()

18. How do you handle a poison pill message that blocks a consumer?

A poison pill is a record that makes processing fail every time, such as malformed JSON, an unexpected null or a bad business value. If the consumer throws, does not commit and polls again, it fetches the same record forever, and that partition's lag climbs while the others look fine.

The design that avoids this has three parts:

  1. Catch and classify errors. Transient ones (a database timeout) deserve a few retries with backoff. Permanent ones (bad data) do not.
  2. Send the failing record to a dead letter topic with headers carrying the original topic, partition, offset and exception message.
  3. Commit and move on so the partition continues.
try {
  process(record);
} catch (BadDataException e) {
  producer.send(new ProducerRecord<>("orders.DLT", record.key(), record.value()));
}
// offset is committed as usual

Alert on DLT volume and keep a replay tool. In a real emergency you can skip a single record by moving the group's offset one past it, but record the skipped offset first.

Take quiz
Why does a poison pill make one partition's lag grow?
The producer uses idempotence
Replicas stop fetching
The broker deletes the partition
The consumer keeps re-reading the same failing record without committing
What should a dead letter record carry for later diagnosis?
Only a new random key
Nothing, it should be anonymous
The consumer's heap dump
Original topic, partition, offset and error details in headers

19. How do you troubleshoot deserialization errors in a Kafka consumer?

Deserialization fails inside poll(), before your code sees the record. Because the offset is never advanced, the consumer fails on the same record again and again, so the app seems to hang.

Find out what is actually in the record. Use kafka-console-consumer.sh with --property print.key=true --property print.offset=true or a tool like kcat at the failing offset, and compare it to what your deserializer expects.

The usual causes:

  • The producer writes JSON but the consumer uses an Avro deserializer, or the reverse.
  • With Schema Registry, an error such as Unknown magic byte! means the bytes were not written with the registry serializer.
  • A topic that carries mixed message types.
  • Null values (tombstones) the deserializer does not handle.

Make the consumer resilient: read as ByteArrayDeserializer and convert inside a try/catch, or use a wrapper such as Spring's ErrorHandlingDeserializer, and route bad records to a dead letter topic. Fix the producer or agree on a schema contract so it does not return.

Take quiz
The error 'Unknown magic byte!' usually indicates:
The broker disk is full
The record was not written with the Schema Registry serializer
The topic has too many partitions
The consumer group is empty
Where does a deserialization failure occur in the consumer?
Inside the producer's partitioner
Inside poll(), before the application code receives the record
Only when committing offsets
In the broker's log cleaner

20. How do you handle a breaking schema change safely with Schema Registry?

Schema Registry checks every new schema version against the previous ones using the subject's compatibility mode. A breaking change, such as adding a required field with no default, is rejected at registration time (HTTP 409), so it never reaches consumers.

Mode Meaning Upgrade first
BACKWARD (default) New schema can read old data Consumers
FORWARD Old schema can read new data Producers
FULL Both directions Either

Safe changes in practice: add fields with default values, remove optional fields, and never rename or change types in place. Use the _TRANSITIVE variants to check against all earlier versions, not only the latest.

When the change is truly incompatible, do not force it. Create a new topic (for example orders-v2) or a new subject, dual-write for a while, migrate consumers, then retire the old topic.

Take quiz
Which change is generally safe under BACKWARD compatibility?
Adding a new field with a default value
Adding a required field with no default
Changing a field's type from string to int
Renaming an existing field
For BACKWARD compatibility, which side should be upgraded first?
Producers
ZooKeeper nodes
Brokers only
Consumers

21. How do you troubleshoot NotLeaderOrFollowerException and LEADER_NOT_AVAILABLE errors?

Both errors mean the client's idea of who leads a partition is wrong, or no leader exists right now. NotLeaderOrFollowerException appears when leadership moved (an election, a restart, a reassignment) and the client's cached metadata is stale. LEADER_NOT_AVAILABLE means the partition currently has no leader at all.

A few of these during a deploy are normal. The producer refreshes metadata and retries on its own. Investigate when they persist:

  1. Run kafka-topics.sh --describe. If a partition shows Leader: none, it is offline; find out why all replicas are gone.
  2. Look for leader election storms: a flapping broker, GC pauses, or session timeouts causing repeated elections.
  3. Check the controller logs and ActiveControllerCount.
  4. If the topic was just auto-created, the first produce may briefly return LEADER_NOT_AVAILABLE before leaders are assigned.

On the client, make sure retries are enabled and delivery.timeout.ms is long enough to ride out an election. Tuning retry.backoff.ms and metadata.max.age.ms helps clients discover new leaders faster.

Take quiz
LEADER_NOT_AVAILABLE persisting on a partition means:
Schema Registry is down
The partition has no leader, so check why all replicas are unavailable
The consumer group has too many members
The topic is compacted
A short burst of NotLeaderOrFollowerException during a broker restart is:
A sign of a full disk
A reason to delete the topic
Proof that data was lost
Normal, because clients refresh metadata and retry

22. How do you diagnose high request latency on a Kafka broker?

Every request goes through a pipeline: a network thread reads it, it waits in the request queue, an I/O handler thread processes it (often touching disk), it may wait in purgatory for followers, and finally goes through the response queue back out. Kafka reports time spent at each stage, so you can see exactly where it goes.

Metric (RequestMetrics) High value points to
RequestQueueTimeMs Too few handler threads or overloaded broker
LocalTimeMs Slow disk or log append on the leader
RemoteTimeMs Waiting for followers (acks=all) or fetch wait
ResponseQueueTimeMs / ResponseSendTimeMs Network threads or bandwidth saturation

Also watch RequestHandlerAvgIdlePercent and NetworkProcessorAvgIdlePercent. Sustained values below roughly 30% mean the thread pools are close to saturation, so consider raising num.io.threads or num.network.threads, or spreading load to more brokers.

Take quiz
A high RemoteTimeMs for produce requests most often indicates:
Time waiting for follower replication with acks=all
An expired TLS certificate
A slow consumer
A bad schema
Persistently low RequestHandlerAvgIdlePercent means:
The topic has no keys
Retention is too high
The I/O handler threads are close to saturation
Producers are idle

23. What happens when the active KRaft controller fails?

In KRaft mode the cluster metadata lives in an internal log, __cluster_metadata, replicated across a quorum of controller nodes using the Raft protocol. One controller is the active leader; the others are hot standbys with the same metadata.

If the active controller fails, the remaining voters hold an election and one of them becomes active, typically within seconds. Because the standbys already have the full metadata, there is no slow state reload from an external system.

During the election, metadata changes pause: no new topics, no partition leader elections and no ISR updates. Producers and consumers using partitions whose leaders are healthy carry on, since data traffic goes directly to the brokers.

The real danger is losing a majority of the controller voters. With 3 controllers you can lose 1; with 5 you can lose 2. Beyond that, the metadata quorum cannot make progress, and any partition that needs a new leader stays stuck.

Place controller nodes in separate failure domains and alert on ActiveControllerCount (the sum across controllers should be exactly 1).

Take quiz
In a 3-node KRaft controller quorum, how many controllers can fail while metadata stays available?
Two
None
One
Three
While a new active controller is being elected, what continues to work?
Produce and consume on partitions with healthy leaders
Creating new topics
Partition leader elections
ISR updates

24. Why does a consumer get CommitFailedException?

CommitFailedException is thrown by commitSync() when the group has already rebalanced, so the commit comes from a consumer that no longer owns those partitions or belongs to an older generation. The broker rejects it to stop a stale member from overwriting a newer position.

The root cause is almost always the consumer being removed from the group first:

  • The time between poll() calls went over max.poll.interval.ms.
  • Heartbeats were missed beyond session.timeout.ms because of GC or network trouble.

Fix the cause, not the exception: reduce max.poll.records, speed up processing, and look at GC logs. Then make the code tolerate it. Records from a failed commit will be processed again by the new owner, so the handler must be idempotent.

try {
  consumer.commitSync();
} catch (CommitFailedException e) {
  log.warn("Rebalanced before commit, records will be redelivered", e);
}

Use a ConsumerRebalanceListener to commit in onPartitionsRevoked so finished work is saved before the partitions leave.

Take quiz
CommitFailedException means:
The topic is full
The group rebalanced and this consumer no longer owns the partitions
The broker lost its disk
The offset topic was compacted
Where can you commit finished work just before partitions are taken away?
In onPartitionsRevoked of a ConsumerRebalanceListener
In the producer callback
In the Schema Registry client
In the broker's server.properties

25. How do you build exactly-once consume-transform-produce processing in Kafka?

Use Kafka transactions. The output records and the input offsets are committed atomically, so either both happen or neither does. After a crash, a retried batch cannot produce duplicate output.

  1. Set a unique transactional.id on the producer (this implicitly turns on idempotence).
  2. Set enable.auto.commit=false on the consumer and isolation.level=read_committed for downstream readers.
  3. Wrap each batch in one transaction.
producer.initTransactions();
while (true) {
  var records = consumer.poll(Duration.ofMillis(500));
  producer.beginTransaction();
  for (var r : records) producer.send(transform(r));
  producer.sendOffsetsToTransaction(offsetsOf(records), consumer.groupMetadata());
  producer.commitTransaction();
}

If an error occurs, call abortTransaction(); consumers using read_committed never see the aborted records.

The guarantee covers Kafka to Kafka only. A database write or HTTP call inside the loop is not part of the transaction, so keep those idempotent. Kafka Streams offers the same behavior with processing.guarantee=exactly_once_v2.

Take quiz
Which call ties the consumed offsets to the output transaction?
seekToBeginning()
flush() on the producer
commitAsync() on the consumer
sendOffsetsToTransaction()
What does isolation.level=read_committed do for a consumer?
It hides records from aborted or open transactions
It forces acks=all
It disables consumer groups
It encrypts the messages

26. How do you troubleshoot ProducerFencedException in a transactional producer?

ProducerFencedException means another producer started with the same transactional.id and a higher epoch, so the broker rejects the older one. This is by design: it fences off zombie instances, such as an app that was partitioned from the network and then replaced.

It also shows up when a transaction exceeds transaction.timeout.ms (60 seconds by default) and the coordinator aborts it, or when you accidentally start two live instances with the same id.

How to handle it:

  1. Treat it as fatal for that producer instance. Do not retry; close it and create a new one, or shut the instance down.
  2. Make sure each active instance has a unique transactional.id, usually derived from the input partition or a stable pod ordinal.
  3. Keep processing per transaction shorter than the timeout, or raise it carefully (it must stay under the broker's transaction.max.timeout.ms).
  4. Investigate why an old instance was still running: long GC pauses, network partitions, or autoscaling overlap.

Fencing is protecting you from duplicate output, so the fix is to correct the deployment, not to suppress the error.

Take quiz
ProducerFencedException is thrown when:
A newer producer with the same transactional.id has taken over
acks is set to 0
The topic has no replicas
The consumer group is empty
How should the application react to ProducerFencedException?
Close that producer and create a new one, do not retry the send
Disable transactions in production
Increase max.poll.records
Retry the same transaction forever

27. How do you safely increase the partition count of a live topic?

Adding partitions is easy; keeping your data model correct afterwards is the hard part.

kafka-topics.sh --bootstrap-server broker1:9092 \
  --alter --topic orders --partitions 24

You can only increase the count, never decrease it. The catch is that the default partitioner picks a partition with hash(key) % numPartitions. When the number changes, keys move: new events for a key can land on a different partition than its old events, so per-key ordering is broken across the change, and stateful consumers (like Kafka Streams aggregations) see their state split.

Safer options:

  1. If ordering does not matter, just add partitions and let the group rebalance.
  2. If it does, create a new topic with the target count, dual-write or mirror into it, migrate consumers, then retire the old topic.
  3. Or pause producers, let consumers drain to zero lag, then add partitions and resume.

Compacted topics and keyed state stores need extra care. Plan the partition count up front with some headroom, so you rarely need to do this on a live system.

Take quiz
What changes for existing keys after you add partitions with the default partitioner?
Nothing, the mapping is permanent
Keys are hashed to broker ids
Keys are deleted
Keys may map to different partitions, breaking per-key ordering
Which is the safest approach when per-key ordering is critical?
Disable the consumer group
Set retention.ms to 0
Create a new topic with more partitions and migrate to it
Reduce partitions on the old topic

28. How do you rebalance data after adding a new broker to a cluster?

A new broker joins empty. Kafka does not move existing partitions to it automatically, only new topics may land there. You have to reassign partitions yourself or use a tool such as Cruise Control.

  1. List the topics to move in a JSON file.
  2. Generate a plan: kafka-reassign-partitions.sh --generate --topics-to-move-json-file topics.json --broker-list 1,2,3,4.
  3. Review it, save the proposed layout and execute with a throttle:
    kafka-reassign-partitions.sh --execute --reassignment-json-file plan.json --throttle 50000000
  4. Poll with --verify until all moves finish; this also removes the throttle.
  5. Run a preferred leader election so leaders spread out too.

The throttle (bytes per second) keeps the data copy from starving live traffic. Move in batches, not everything at once, and confirm there are no under-replicated partitions between batches.

If you forget --verify, the throttle can remain set and later hold followers out of the ISR, so always clear it.

Take quiz
Does Kafka automatically move existing partitions onto a newly added broker?
Yes, but only for compacted topics
No, you must reassign them yourself or use a tool like Cruise Control
Yes, immediately
Only when the controller restarts
Why use --throttle with kafka-reassign-partitions.sh?
To delete old topics
To stop the data copy from starving live traffic
To encrypt the replicas
To raise the replication factor

29. How do you troubleshoot long GC pauses on a Kafka broker?

Long GC pauses hurt a broker in specific, visible ways: followers drop out of the ISR, the controller session expires, leaders flap, and request latency spikes. If a broker looks healthy on CPU but keeps leaving the cluster, suspect GC.

  1. Enable GC logging (-Xlog:gc*:file=gc.log on modern JVMs) and look for pauses of a second or more.
  2. Check the heap size. Kafka depends on the OS page cache for fast reads, not a huge heap. A heap of 6-8 GB is usually plenty; a much bigger one leaves less memory for the page cache and makes pauses longer.
  3. Use G1 with pause-time goals, for example -XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35.
  4. Look for causes of heap pressure: too many partitions per broker, very large messages, or old clients that force down-conversion of message formats.

Align timeouts too: if a pause of 10 seconds is unavoidable, make sure it is below the session and replica lag timeouts, but treat that as a stopgap. The real fix is a right-sized heap, fewer partitions on the broker and removing the allocation hot spots.

Take quiz
Why is a very large heap not ideal for a Kafka broker?
Heap size controls topic retention
Kafka relies on OS page cache, and a huge heap reduces it and lengthens pauses
Large heaps disable replication
Kafka cannot use more than 1 GB
Which symptom can a long GC pause on a broker cause?
Schemas being deleted
Topics gaining partitions
Producers switching to acks=0
Followers dropping out of the ISR

30. How do you troubleshoot a failed Kafka Connect task?

A connector can be RUNNING while one of its tasks is FAILED, so always check the task level. The REST API shows the stack trace.

curl -s http://connect:8083/connectors/orders-sink/status
curl -X POST http://connect:8083/connectors/orders-sink/tasks/0/restart

Read the trace to find the category of failure:

  • Converter errors: the data does not match the configured Avro/JSON converter.
  • SMT errors: a transform fails on an unexpected null or field.
  • Sink errors: constraint violations, type mismatches, a database or target system outage.
  • Source errors: lost connection, permission problems, binlog or offset problems.

Restarting only helps for transient failures. For bad records in a sink, set error handling so one bad message does not stop the pipeline:

errors.tolerance=all
errors.deadletterqueue.topic.name=orders-sink-dlq
errors.deadletterqueue.context.headers.enable=true
errors.log.enable=true

Dead letter queues are supported for sink connectors. Also check worker logs for rebalance loops and resource limits.

Take quiz
Which REST call restarts only task 0 of a connector?
POST /connectors/{name}/tasks/0/restart
DELETE /topics/{name}
PUT /groups/{name}/offsets
GET /brokers/0/restart
Which setting sends bad sink records to a dead letter topic?
delivery.timeout.ms
retention.bytes
errors.deadletterqueue.topic.name
group.instance.id

31. How do you troubleshoot MirrorMaker 2 replication lag?

MirrorMaker 2 is a set of Kafka Connect connectors: a source consumer reads from the source cluster and a producer writes to the target. Lag can build at either end or in between, so measure first.

  1. Check the MM2 metrics replication-latency-ms and record-age-ms, and the consumer lag of the MM2 connector group on the source cluster.
  2. Check tasks.max. Fewer tasks than source partitions caps parallelism.
  3. Look at the link between regions. Cross-region latency and bandwidth limit throughput; a single TCP connection can be slow on a long, high-latency path.
  4. Tune the source consumer and target producer used by MM2: larger fetch.max.bytes, bigger batch.size, some linger.ms and compression, for example via source.consumer.* and target.producer.* overrides.
  5. Check the target brokers for throttling or under-replication.

Also confirm checkpoints and offset sync are working (emit.checkpoints.enabled, sync.group.offsets.enabled), otherwise consumers failing over to the target cannot resume from the right position even when replication itself is healthy.

Take quiz
Which MM2 setting caps how many parallel replication tasks run?
acks
retention.ms
tasks.max
num.io.threads
Why do MM2 checkpoints matter for a disaster-recovery failover?
They create new partitions
They let consumers resume at the right offsets on the target cluster
They compress the replicated data
They rotate TLS certificates

32. How do you troubleshoot SSL handshake failures between Kafka clients and brokers?

Handshake failures are certificate or protocol mismatches. The client log usually names the problem, and a quick test from the command line narrows it down.

openssl s_client -connect broker1:9093 -showcerts
# client-side debug
-Djavax.net.debug=ssl:handshake

Error text Usual fix
PKIX path building failed Add the CA chain to the client truststore
No subject alternative names matching... Issue the broker cert with a SAN for the advertised hostname
certificate_expired Renew and reload the certificate
handshake_failure with mutual TLS Provide a client keystore trusted by the broker

Also check that the client is talking to an SSL listener, not a plaintext one. A security.protocol=SSL client hitting a PLAINTEXT port fails with confusing errors.

Avoid turning off hostname verification (ssl.endpoint.identification.algorithm=) as a fix. It hides the real problem and removes protection against man-in-the-middle attacks. Fix the SAN instead.

Take quiz
Which tool lets you inspect the certificate a broker presents?
kafka-log-dirs.sh
kafka-acls.sh --add
kafka-topics.sh --describe
openssl s_client -connect host:port -showcerts
'No subject alternative names matching' means:
The topic has no keys
Consumer offsets expired
The certificate does not list the hostname the client connected to
The disk is full

33. How do you troubleshoot SASL authentication failures in Kafka?

An authentication failure means the broker could not verify who the client is. It is different from an authorization failure, where the client is known but not allowed.

  1. Match the mechanism: the client's sasl.mechanism (PLAIN, SCRAM-SHA-512, OAUTHBEARER, GSSAPI) must be enabled on the broker listener through sasl.enabled.mechanisms.
  2. Match the protocol: SASL_SSL versus SASL_PLAINTEXT must match the listener the client connects to.
  3. Check credentials: the JAAS config (sasl.jaas.config) username and password. For SCRAM, the user must exist in the cluster:
    kafka-configs.sh --alter --entity-type users --entity-name alice --add-config 'SCRAM-SHA-512=[password=secret]'
  4. Kerberos: verify keytab, principal name, and clock skew between client, broker and KDC.
  5. Read the broker log; it records Failed authentication entries with the reason and client address.

Test with kafka-console-producer.sh and a small client.properties file to separate application bugs from broker configuration problems.

Take quiz
What must exist in the cluster for a SCRAM login to succeed?
A schema for the username
A dedicated topic per user
A new partition per user
A SCRAM credential created for that user
Which Kerberos-specific issue commonly causes SASL failures?
Large message size
Consumer lag
Clock skew between client, broker and KDC
Too many partitions

34. How do you troubleshoot TopicAuthorizationException?

The client authenticated successfully, but the ACLs do not allow the operation. First find out which principal the broker sees; with TLS it is the certificate subject, with SASL it is the username, written as User:alice.

kafka-acls.sh --bootstrap-server broker1:9092 \
  --command-config admin.properties --list --topic orders

Typical permissions needed:

  • Producer: Write and Describe on the topic (plus Create if it relies on auto-creation).
  • Consumer: Read on the topic and Read on the consumer group. A missing group ACL raises GroupAuthorizationException instead.
  • Transactional producer: Write on the TransactionalId resource.

Grant it with, for example, --add --allow-principal User:alice --operation Read --topic orders, and use --resource-pattern-type prefixed for naming conventions.

If the principal name looks wrong (a long certificate DN), check ssl.principal.mapping.rules. Turn on DEBUG for kafka.authorizer.logger to see exactly which principal and operation were denied.

Take quiz
A consumer needs which ACLs to read from a topic as part of a group?
Write on the topic only
Create on the cluster only
Read on the topic and Read on the consumer group
Describe on the controller
Which log setting reveals the denied principal and operation?
auto.create.topics.enable
num.partitions
log.retention.hours
DEBUG on kafka.authorizer.logger

35. Why can clients connect to the bootstrap server but fail to reach the brokers?

The bootstrap address is used only for the first connection. The broker answers with metadata containing each broker's advertised.listeners address, and the client connects to those addresses from then on. If an advertised address is unreachable from the client's network, you see errors like Connection to node 1 could not be established. Broker may not be available.

This is very common with Docker, Kubernetes and cloud load balancers, where the broker advertises its internal hostname or localhost.

The fix is to give each network its own listener with an address that network can reach:

listeners=INTERNAL://0.0.0.0:9092,EXTERNAL://0.0.0.0:9094
advertised.listeners=INTERNAL://kafka-1:9092,EXTERNAL://kafka1.example.com:9094
listener.security.protocol.map=INTERNAL:PLAINTEXT,EXTERNAL:SSL
inter.broker.listener.name=INTERNAL

Test from the client machine with kcat -b host:9094 -L and read the broker addresses in the metadata output. If those names do not resolve or are blocked by a firewall, the client will fail even though the bootstrap connection succeeded.

Take quiz
Where does the client get the addresses it uses after the first connection?
From the topic's retention settings
From the bootstrap.servers list only
From metadata containing each broker's advertised.listeners
From the consumer group coordinator logs
What does kcat -L help you check here?
The broker addresses returned in the cluster metadata
The disk usage of each topic
The JVM heap of the broker
The number of consumers in a group

36. What problems do too many partitions cause in a Kafka cluster?

Partitions are Kafka's unit of parallelism, but each one has a cost, and the costs add up across brokers.

  • File handles and memory: every partition has segment, index and time-index files, all open.
  • Slower recovery: a broker restart must recover and load logs for every partition, and failover requires electing leaders for each one it led.
  • Replication overhead: more partitions mean more fetch requests and smaller batches, which raises latency.
  • Controller load: metadata grows, and operations like topic creation or reassignment slow down.
  • Consumer side: more partitions per consumer means more in-memory buffers and slower rebalances.

Older ZooKeeper-based guidance suggested staying around a few thousand partitions per broker and about 200,000 per cluster. KRaft raises these limits, but the principle holds: don't over-provision.

To pick a count, take your target throughput T, the producer rate per partition P and the consumer rate per partition C, then use max(T/P, T/C) with a small safety margin, rather than "100 partitions just in case".

Take quiz
Which formula gives a reasonable starting partition count?
Retention hours times 10
max(T/P, T/C) based on target and per-partition throughput
Number of consumers divided by brokers
Always 100 partitions
Which cost grows with partition count and slows broker restarts?
Schema Registry lookups
Log recovery and leader election work per partition
Producer compression ratio
TLS handshakes per client

37. How do you troubleshoot log compaction that is not cleaning up a topic?

Compaction is done by background log cleaner threads. If a compacted topic keeps growing and old keys never disappear, check these in order:

  1. Is the cleaner thread alive? A cleaner can die on an exception, for example a record larger than the dedupe buffer. Look in log-cleaner.log, and watch the max-clean-time-secs and time-since-last-run-ms metrics. If it died, fix the cause and restart the broker.
  2. Is the topic eligible? Confirm cleanup.policy=compact (or compact,delete).
  3. Dirty ratio: a log is cleaned only when the dirty fraction exceeds min.cleanable.dirty.ratio (0.5 default). Lower it for faster compaction.
  4. Active segment: the newest segment is never compacted. On low-traffic topics set segment.ms so it rolls regularly.
  5. Tombstones: deleted keys remain for delete.retention.ms (24 hours default) before being removed.

If the dedupe buffer (log.cleaner.dedupe.buffer.size) is too small for the number of unique keys, cleaning takes many passes. Increase it on topics with a large key space.

Take quiz
Which segment is never compacted?
The active segment
The oldest segment
The segment holding offset 0
Any segment with a tombstone
What can silently stop all compaction on a broker?
Adding a consumer group
The log cleaner thread dying from an exception
Setting acks=all
Using SSL on the listener

38. Why is data retained longer than retention.ms?

Kafka deletes data in whole log segments, never record by record, and it never deletes the active segment, which is still being written to. So a message is removed only after its segment is closed and every record in it is older than the retention limit.

A segment rolls when it reaches segment.bytes (1 GB default) or is older than segment.ms (7 days default). On a quiet topic, a 1 GB segment may take weeks to fill, so data stays far beyond a one-hour retention.ms.

Other factors:

  • The retention check runs every log.retention.check.interval.ms (5 minutes by default), so deletion is not instant.
  • Retention is judged by the largest timestamp in the segment. One record with a future timestamp keeps the whole segment alive.
  • With message.timestamp.type=CreateTime, producer-supplied timestamps decide, so clock skew or replayed data matters.

To enforce tighter retention on a low-volume topic, lower segment.ms (for example to an hour) so segments roll and become eligible.

Take quiz
Which segment can retention never delete?
A segment with no keys
The active segment currently being written
Any segment older than an hour
The segment with the smallest offset
A low-traffic topic keeps data much longer than retention.ms. Which setting helps?
Set acks=all
Lower segment.ms so segments roll sooner
Enable idempotence
Raise num.io.threads

39. How does static membership reduce rebalances during rolling deployments?

Normally a restarted consumer gets a new member id, so the group sees one member leave and another join, and it rebalances twice. During a rolling deployment of many pods, that means a storm of rebalances and paused processing.

With static membership each consumer sets a stable group.instance.id. If a consumer restarts and rejoins with the same id within session.timeout.ms, the coordinator recognizes it and gives back the same partitions without a rebalance.

group.instance.id=orders-consumer-0
session.timeout.ms=60000
partition.assignment.strategy=org.apache.kafka.clients.consumer.CooperativeStickyAssignor

  1. Give each instance a unique, stable id, for example a Kubernetes StatefulSet pod name.
  2. Set session.timeout.ms long enough to cover a restart.

The trade-off: if a static member really dies, its partitions sit idle until the session times out, so failure detection is slower. Pick a timeout that balances restart time against how long you can tolerate a dead consumer. Two live consumers using the same id will fence each other, so ids must be unique.

Take quiz
Which setting identifies a consumer for static membership?
transactional.id
group.instance.id
client.id only
group.min.session.timeout.ms
What is the cost of a long session.timeout.ms with static membership?
Brokers stop replicating
Producers lose idempotence
Topics lose retention
A truly dead consumer's partitions stay idle longer

40. How do you troubleshoot slow state restore in a Kafka Streams application?

A stateful Streams app keeps state in local RocksDB stores, backed by compacted changelog topics in Kafka. If the local state is lost (a pod restarts without a persistent volume) or the task moves to another instance, the app must replay the whole changelog before it can process. For large state this can take minutes or hours.

Ways to cut it down:

  1. Keep state across restarts: mount a persistent volume for state.dir, so only the missing tail is replayed.
  2. Use standby replicas: num.standby.replicas=1 keeps a warm copy on another instance, so failover is fast.
  3. Keep the state small: use windowed retention and avoid storing unneeded fields.
  4. Tune the restore consumer (for example restore.consumer.max.poll.records and fetch sizes) for faster replay.
  5. Check the changelog: make sure it is compacted properly, otherwise it contains far more than the current state.

When scaling out, warm-up replicas (max.warmup.replicas) let new instances catch up before they take over tasks. Watch the restore metrics and the task state to see which store is slow.

Take quiz
What backs a Kafka Streams state store so it can be rebuilt?
A local file copied to S3 nightly
A compacted changelog topic in Kafka
A ZooKeeper node
The __consumer_offsets topic
Which setting keeps a warm copy of state on another instance for quick failover?
max.poll.records
linger.ms
replication.factor of the output topic
num.standby.replicas

41. How do you handle a Kafka Streams thread that dies from an exception?

If an exception escapes your processing code and no handler is set, the stream thread dies. The app keeps running with fewer threads, so throughput drops quietly until every thread is gone and the client moves to the ERROR state. Always register a handler.

streams.setUncaughtExceptionHandler(ex -> {
  log.error("Stream thread failed", ex);
  return StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.REPLACE_THREAD;
});

Response Effect
REPLACE_THREAD Start a new thread; good for transient errors
SHUTDOWN_CLIENT Stop this instance only
SHUTDOWN_APPLICATION Signal all instances to stop

Replacing a thread forever on a poison record just loops, so also deal with bad data directly. Use a DeserializationExceptionHandler (LogAndContinueExceptionHandler skips bad bytes, the default fails) and a ProductionExceptionHandler for send failures. Catch business exceptions inside the topology and route the bad record to a dead letter topic.

Expose the Streams state listener to your health checks so a stuck ERROR or PENDING_SHUTDOWN state restarts the pod.

Take quiz
What happens to a Streams app with no uncaught exception handler when a thread throws?
The changelog is deleted
Kafka restarts the broker
That thread dies and the app keeps running with fewer threads
The topology is rewritten
Which response starts a replacement thread after a failure?
SKIP_RECORD
REPLACE_THREAD
SHUTDOWN_APPLICATION
LogAndFail

42. How do you perform a rolling restart of Kafka brokers safely?

The rule is one broker at a time, and never start the next until the cluster is fully healthy again. Restarting a second broker while the first is still catching up can drop partitions below min.insync.replicas or take them offline.

flowchart TD
  A["Check URP is 0 and all brokers are up"] --> B["Stop one broker gracefully"]
  B --> C["Controlled shutdown moves leaders"]
  C --> D["Apply change and start broker"]
  D --> E["Wait until ISR is full again"]
  E --> F{URP is 0?}
  F -- No --> E
  F -- Yes --> G["Next broker"]
  1. Confirm UnderReplicatedPartitions is 0 first.
  2. Stop with a normal SIGTERM and keep controlled.shutdown.enable=true, so leaders move away before the process exits.
  3. Start the broker and wait for it to rejoin the ISR of its partitions.
  4. Only then continue; restart the controller or active metadata leader last if you can.
  5. Run a preferred leader election at the end (or rely on auto.leader.rebalance.enable) to restore even leadership.

Make sure min.insync.replicas is lower than the replication factor, for example RF=3 and min ISR=2, so one broker down does not block acks=all producers.

Take quiz
What must be true before restarting the next broker?
Schema Registry is restarted
Under-replicated partitions are back to 0
The topic count equals the broker count
All consumers have zero lag
Why keep controlled.shutdown.enable=true?
It raises min.insync.replicas
It disables ZooKeeper
Leaders are moved away gracefully before the broker exits
It deletes old log segments

43. How do you handle a sudden 10x spike in Kafka traffic?

Kafka is built to absorb bursts because it buffers on disk, so the first question is what actually saturates: producer buffers, broker network, disk, request threads, or the consumers.

  1. Look at the broker first: network and disk throughput, request handler idle percent, and produce latency.
  2. Cut bytes cheaply: enable compression.type=lz4 or zstd and larger batches (batch.size, linger.ms). This often relieves network and disk right away.
  3. Protect other tenants: apply client quotas so one noisy producer cannot starve the cluster.
  4. Let consumers lag temporarily if retention is long enough, rather than risking an unstable scale-out under pressure.
  5. Scale consumers up to the partition count, ideally automatically on lag metrics (for example with KEDA).
  6. Scale the cluster if the spike is permanent: add brokers and reassign partitions, or add partitions with the ordering caveats in mind.

Check that producers are not blocking on a full buffer.memory, and that retention and disk space can hold the extra data for as long as the backlog lasts.

Take quiz
Which change often relieves broker network and disk quickly during a spike?
Reduce the replication factor to 0
Delete consumer groups
Enable compression and larger batches
Set acks=0 for all topics
Why add client quotas during a traffic spike?
To add partitions
To encrypt traffic
To stop one noisy producer from starving the rest of the cluster
To reset offsets

44. How can you reduce end-to-end latency in a real-time Kafka pipeline?

Latency is added at every hop: producer batching, broker replication, consumer fetching and your processing. Measure each stage by comparing timestamps, then tune the biggest one.

Stage Latency-friendly setting
Producer linger.ms 0-5, modest batch.size
Durability acks=1 is faster than acks=all, but riskier
Broker Fast disks, enough network threads, fewer partitions per broker
Consumer fetch.min.bytes=1, low fetch.max.wait.ms

Beyond settings, keep consumer lag near zero (a lagging consumer reads old data by definition), avoid rebalances, and keep producers, brokers and consumers in the same region or zone.

Be careful with acks. Dropping to acks=1 removes the wait for followers, but a leader crash right after the ack can lose that record. For most real-time use cases, acks=all with healthy replicas adds only a few milliseconds, so keep it and fix the real bottleneck first.

Take quiz
Which producer setting adds a deliberate wait to build bigger batches?
fetch.min.bytes
retention.ms
session.timeout.ms
linger.ms
Which consumer setting makes the broker answer a fetch as soon as any data exists?
fetch.min.bytes=1
auto.offset.reset=none
max.poll.interval.ms=1
fetch.min.bytes=1048576

45. How do you improve Kafka producer throughput?

Producer throughput comes mostly from sending fewer, bigger, compressed requests. The defaults favor low latency, so a few settings make a large difference.

batch.size=131072
linger.ms=10
compression.type=lz4
buffer.memory=67108864
acks=1            # or all, if durability matters

  1. batch.size: the default is 16 KB. Raising it to 64-256 KB lets more records share a request.
  2. linger.ms: waiting a few milliseconds fills batches. Older versions default to 0; recent ones use a small non-zero default.
  3. compression.type: lz4 for speed, zstd for a better ratio. It reduces network and disk use.
  4. buffer.memory: enough room so send() does not block when brokers are briefly slow.
  5. Parallelism: more partitions, and several producer instances if one thread is the limit.

Choose acks deliberately. acks=all costs some throughput, but it is the safe choice for important data. Keep enable.idempotence=true; it adds little overhead. Test with kafka-producer-perf-test.sh before and after each change.

Take quiz
Which two settings together let a producer fill larger batches?
batch.size and linger.ms
group.id and client.id
acks and retries
retention.ms and segment.bytes
Which tool benchmarks producer throughput?
kafka-producer-perf-test.sh
kafka-acls.sh
kafka-reassign-partitions.sh
kafka-metadata-quorum.sh

46. How do you troubleshoot replicas repeatedly falling out of the ISR because of network problems?

A follower leaves the ISR if it does not catch up within replica.lag.time.max.ms. Frequent ISR shrink and expand events (IsrShrinksPerSec, IsrExpandsPerSec) mean followers are intermittently too slow to keep up.

  1. Find which broker is the common factor. Grep broker logs for Shrinking ISR and see which replica keeps appearing.
  2. Check the network between that broker and the leaders: packet loss, saturated bandwidth, cross-AZ links, a noisy neighbor.
  3. Look for a leftover replication throttle. After a reassignment, an unremoved leader.replication.throttled.rate or follower.replication.throttled.rate can throttle healthy replication and push followers out.
  4. Check follower resources: slow disk, GC pauses, CPU starvation.
  5. Tune fetching for busy clusters: num.replica.fetchers for more parallel fetch threads, and replica.fetch.max.bytes if big batches are involved.

Raising replica.lag.time.max.ms only reduces the symptom. It also lengthens the time a dead follower stays in the ISR, which can stall acks=all writes, so fix the underlying slowness first.

Take quiz
Which leftover setting after a partition reassignment can push healthy followers out of the ISR?
A compacted topic
A larger batch.size
A replication throttle that was never removed
A new consumer group
A follower leaves the ISR when it fails to catch up within:
session.timeout.ms
delivery.timeout.ms
max.poll.interval.ms
replica.lag.time.max.ms

47. How do you fix uneven load across Kafka brokers?

When one broker has much higher CPU, network or disk than others, look for leader skew and partition skew. Reads and writes go to the leader, so a broker that leads too many busy partitions does more work even if replica counts look equal.

  1. Compare leader counts and bytes in/out per broker.
  2. After restarts, leadership often stays on whichever brokers stayed up. Restore the preferred leaders:
    kafka-leader-election.sh --bootstrap-server broker1:9092 --election-type PREFERRED --all-topic-partitions
    Keep auto.leader.rebalance.enable=true (it acts when imbalance passes leader.imbalance.per.broker.percentage, 10% by default).
  3. If the partition placement itself is uneven, move partitions with kafka-reassign-partitions.sh, or let Cruise Control compute and execute a balanced plan.
  4. Check for a single huge topic or hot partition dominating one broker.

Set broker.rack so replicas spread across zones. To cut cross-zone traffic and relieve leaders, consumers can fetch from the closest replica using client.rack and replica.selector.class=RackAwareReplicaSelector.

Take quiz
Which tool command restores leadership to each partition's preferred replica?
kafka-console-consumer.sh --from-beginning
kafka-topics.sh --delete
kafka-leader-election.sh --election-type PREFERRED
kafka-acls.sh --remove
Which tool can compute and execute a balanced partition plan automatically?
Schema Registry
MirrorMaker 2
Kafka Connect
Cruise Control

48. How do you fix 'Too many open files' on a Kafka broker?

The error is java.io.IOException: Too many open files. A broker keeps file descriptors for every log segment, index and time index, plus one for every client and replica socket connection. Thousands of partitions and thousands of clients can exceed the OS default limit of 1024 very fast.

  1. Check usage: ls /proc/<pid>/fd | wc -l against the limit in /proc/<pid>/limits.
  2. Raise the limit to something like 100,000 or more. For systemd services, set LimitNOFILE=100000 in the unit file; editing only limits.conf may not apply.
  3. Look for connection leaks: a classic bug is creating a new producer or consumer per request without closing it. Producers and consumers should be long-lived and shared.
  4. Reduce segment count: too many small segments (a tiny segment.bytes or segment.ms) multiplies open files.
  5. Limit connections: max.connections.per.ip and connections.max.idle.ms keep runaway clients under control.

After the change, restart the broker and confirm the new limit with /proc/<pid>/limits. Then fix the client or partition design that caused the pressure.

Take quiz
Which file descriptors does a broker hold open per partition?
Only the TLS keystore
One ZooKeeper file
Log segment, index and time-index files
Only the consumer group file
A service creates a new KafkaProducer per HTTP request without closing it. What is the likely result?
Better throughput
Smaller segments
Leaked sockets and file descriptors until the limit is hit
Faster leader election

49. Which metrics should you alert on to monitor Kafka health?

Alert on symptoms that need action, and keep the rest on dashboards. These are the usual ones, grouped by what they protect.

Metric Alert when
OfflinePartitionsCount Greater than 0
UnderMinIsrPartitionCount Greater than 0 (writes with acks=all failing)
UnderReplicatedPartitions Greater than 0 for several minutes
ActiveControllerCount Cluster sum is not exactly 1
UncleanLeaderElectionsPerSec Greater than 0
IsrShrinksPerSec Sustained spikes
RequestHandlerAvgIdlePercent Persistently below about 30%
Consumer lag (per group and partition) Growing trend or above business threshold
Disk usage Above 70-80%

Add p99 produce and fetch latency, JVM GC pause time and network saturation. For consumers, alert on lag trend and rebalance rate, not only an absolute number. Pair every alert with a runbook so whoever is on call knows the first command to run.

Take quiz
Which metric shows partitions where acks=all writes are being rejected?
PartitionCount
records-lag-max
BytesInPerSec
UnderMinIsrPartitionCount
What should the cluster-wide sum of ActiveControllerCount be?
2
0
Exactly 1
Equal to the broker count

50. What happens when an entire availability zone fails in a Kafka cluster?

The outcome depends on how replicas were placed. With broker.rack set to the zone and RF=3 across three zones, each partition has exactly one replica per zone. Losing a zone removes one replica of every partition, never two.

flowchart TD
  A["AZ-1 fails"] --> B["Leaders in AZ-1 lost"]
  B --> C["Controller elects new leaders from ISR in AZ-2 and AZ-3"]
  C --> D{min.insync.replicas = 2?}
  D -- ISR is 2 --> E["acks=all writes continue"]
  D -- Not enough replicas --> F["Writes rejected"]
  E --> G["AZ-1 returns, followers catch up, preferred leaders restored"]

Leaders for affected partitions move to the surviving zones within seconds, the ISR becomes 2, and with min.insync.replicas=2 producers keep writing. Clients reconnect through metadata refresh.

Plan for the side effects:

  1. Capacity: the surviving brokers take the load of the lost zone, so size them to run at an acceptable level with one zone gone.
  2. Controller quorum: spread KRaft controllers across three zones, otherwise losing one zone can lose the majority.
  3. Only two zones? RF=3 cannot place one replica per zone, and one zone failure may break the quorum or min ISR. A third zone, even a small one for controllers, matters.

When the zone returns, followers catch up and a preferred leader election restores balance.

Take quiz
With RF=3 across three zones and min.insync.replicas=2, what is the state after one zone fails?
All partitions go offline
The ISR is 2 and acks=all writes continue
Writes switch to acks=0
Consumers must be redeployed
Why spread KRaft controller nodes across three zones?
To speed up compression
To lower the replication factor
To disable rack awareness
So one zone failure cannot take out the controller majority
«
»

Comments & Discussions