Kafka Broker Failure and Recovery
When a Kafka broker fails, every partition it was leading needs a new leader, producers and consumers need to find it, and the failed broker must later catch up before it can be trusted again. Kafka automates all of this. Whether any acknowledged data is lost depends on a few settings chosen before the failure, not on anything you do during it.
This article follows a broker or partition-leader failure step by step, from detection to recovery, from the point of view of the cluster, the producer and the consumer. It ends with the configuration that ensures no acknowledged messages are lost. Background on the individual mechanisms is in Leader Election, In-Sync Replicas and Fault Tolerance.
1. What Happens When a Broker Fails
A broker hosts replicas of many partitions. For some it is the leader, which handles all writes and, by default, all reads; for others it is a follower that copies the leader. When the broker fails:
- Partitions where it was a follower keep working; the follower simply leaves the in-sync replica set (ISR).
- Partitions where it was the leader are unavailable until the controller elects a new leader from the remaining in-sync replicas.
In a KRaft cluster, the active controller makes these decisions and publishes them as metadata updates to all brokers.
2. Failover Step by Step
- Detection. Every broker sends heartbeats to the active controller (every 2 seconds by default). If none arrive within
broker.session.timeout.ms(9 seconds by default), the controller fences the broker. A broker that shuts down cleanly instead tells the controller first, and its leaderships are moved before it stops, which is much faster. - Election. For each partition the failed broker led, the controller picks a new leader from the remaining in-sync replicas and increments the leader epoch. With unclean leader election disabled (the default), a replica outside the ISR is never chosen.
- Propagation. The change is written to the metadata log and replicated to all brokers. The new leader starts accepting writes; the other followers start fetching from it.
- Clients follow. Producers and consumers receive errors such as
NOT_LEADER_OR_FOLLOWERor time out, refresh their metadata, and send their requests to the new leader.
3. What the Producer Experiences
During the few seconds without a leader, sends to that partition cannot complete. The producer handles this by itself:
- Batches stay in the buffer and are retried automatically with backoff, until
delivery.timeout.ms(2 minutes by default) expires. - After a metadata refresh, the retries go to the new leader. Because the partition’s producer state (producer ID and sequence numbers) is replicated with the log, the new leader recognises a batch that the old leader had already written and replicated, and does not append it twice.
- The application sees nothing unless the failover takes longer than
delivery.timeout.ms; then the send callback receives aTimeoutException.
4. What the Consumer Experiences
Consumers fetch from the leader (or a nearby follower if follower fetching is configured). When the leader disappears, fetches for that partition fail, the consumer refreshes its metadata and continues from its current position on the new leader. Committed offsets are not affected, because they are stored in __consumer_offsets, which is itself replicated. If the failed broker was the group coordinator, the coordinator role moves with the leadership of the relevant __consumer_offsets partition, and the group continues after a short pause.
Consumers never see records that were not fully committed by the ISR: they can only read up to the high watermark, the offset that all in-sync replicas have. This is why a failover does not make a record visible and then take it away again.
5. What Happens to Unreplicated Records
The old leader may have appended records that no follower copied yet. What happens to them depends on acks:
| Producer setting | Was the record acknowledged? | Outcome |
|---|---|---|
acks=all | No, the leader waits for all in-sync replicas | The producer retries to the new leader; nothing acknowledged is lost |
acks=1 | Yes, right after the leader wrote it | The new leader does not have it; when the old broker returns it truncates the record. Acknowledged data is lost |
acks=0 | Not waited for at all | Lost silently |
The truncation uses the leader epoch: the returning broker asks the current leader where its epoch ended and removes everything after that point, so all replicas agree on one history.
6. Recovery of the Failed Broker
- Restart and log recovery. After an unclean shutdown, the broker checks the segments that may not have been flushed and rebuilds indexes where needed. With many partitions this can take a while;
num.recovery.threads.per.data.dircontrols the parallelism. - Register and catch up. The broker registers with the controller, truncates any divergent records, and fetches everything it missed from the current leaders.
- Rejoin the ISR. Once a replica is caught up with the leader, it is added back to the ISR, and the partition is fully protected again.
- Leadership rebalance. Leadership does not move back immediately. With
auto.leader.rebalance.enable=true(the default), the controller periodically moves leadership back to each partition’s preferred replica, so load is balanced again across brokers.
7. Ensuring No Acknowledged Messages Are Lost
Scenario: a partition leader crashes while a producer is publishing. To guarantee that no acknowledged message is lost when one broker fails:
| Setting | Value | Why |
|---|---|---|
| Replication factor | 3 | Two copies remain after one broker fails |
min.insync.replicas (topic or broker) | 2 | Every acknowledged record exists on at least two brokers; writes fail with NOT_ENOUGH_REPLICAS instead of being acknowledged with one copy |
acks (producer) | all | Acknowledgement only after all in-sync replicas have the record |
enable.idempotence | true | Retries to the new leader cannot create duplicates or reorder records |
unclean.leader.election.enable | false (default) | Only replicas that have every acknowledged record can become leader |
delivery.timeout.ms | longer than a failover | Retries keep going through the election instead of failing the send |
Rack awareness (broker.rack) | one rack or zone per replica | A zone outage cannot take all replicas at once |
“Under the expected failure conditions” matters: these settings tolerate one broker failure without losing acknowledged data or stopping writes. Losing two of three replicas at once stops writes to that partition (fewer than 2 in sync), which is the correct, safe behaviour.
8. Producer Example for Failover
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "broker1:9092,broker2:9092,broker3:9092");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
props.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 120_000); // covers a leader election comfortably
try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
producer.send(new ProducerRecord<>("payments", paymentId, json), (metadata, e) -> {
if (e == null) {
log.info("payment {} stored at {}-{}@{}", paymentId, metadata.topic(), metadata.partition(), metadata.offset());
} else {
// Retries exhausted, typically a TimeoutException whose message names the cause
// (no leader, or not enough in-sync replicas). The record is NOT stored: alert and
// keep it somewhere durable instead of calling send() again from here.
alerting.raise("payment " + paymentId + " not stored", e);
fallbackStore.save(paymentId, json);
}
});
}
During a normal failover, the callback reports success after a delay of a few seconds. It reports an error only if no leader with enough in-sync replicas becomes available before delivery.timeout.ms. Errors such as NotLeaderOrFollowerException and NotEnoughReplicasException are retriable, so the producer keeps retrying them until that timeout instead of failing immediately.
Create the topic with the matching settings:
$ bin/kafka-topics.sh --bootstrap-server broker1:9092 --create --topic payments \
--partitions 12 --replication-factor 3 --config min.insync.replicas=2
$ bin/kafka-topics.sh --bootstrap-server broker1:9092 --describe --under-replicated-partitions
The second command lists partitions that have lost a replica, which is the first thing to check after a broker failure.
9. Common Mistakes
acks=allwithmin.insync.replicas=1: when followers fall out of the ISR, the leader alone acknowledges, and its crash loses the data.- Replication factor 2 with
min.insync.replicas=2: any single broker failure stops writes. - Enabling unclean leader election on business topics to “stay available”, trading silent data loss for uptime.
- A short
delivery.timeout.msthat fails sends during an ordinary leader election. - Resending from the application after a timeout, which can duplicate a record that was in fact written.
- All replicas in one availability zone.
10. Summary
When a broker fails, the KRaft controller notices the missing heartbeats, elects new leaders from the in-sync replicas with a higher leader epoch, and publishes the change. Producers retry to the new leader without duplicates thanks to idempotence, and consumers continue from their position, reading only up to the high watermark. The failed broker later truncates divergent records, catches up, rejoins the ISR and gets its preferred leaderships back. With replication factor 3, min.insync.replicas=2, acks=all, idempotence and unclean election disabled, one broker failure loses no acknowledged message.
11. Related Reading
- Kafka Delivery Semantics: At-Most-Once, At-Least-Once and Exactly-Once
- Idempotent Producer in Kafka
- Kafka Replication
12. References
- Apache Kafka design: Replication, ISR and unclean leader election
- Apache Kafka 4.4: Broker configs (broker.session.timeout.ms, min.insync.replicas, auto.leader.rebalance.enable)
- Apache Kafka 4.4: Producer configs (acks, delivery.timeout.ms)
- Apache Kafka 4.4: Basic operations (graceful shutdown, balancing leadership)
- Apache Kafka 4.4: KRaft
Kafka Broker Failure and Recovery Interview Questions and Answers
Common interview questions on Kafka Broker Failure and Recovery, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What happens, step by step, when the broker leading a partition crashes?
Answer: The broker stops sending heartbeats to the KRaft controller. After broker.session.timeout.ms (9 seconds by default) the controller fences it and, for each partition it led, elects a new leader from the remaining in-sync replicas, incrementing the leader epoch. The change is published as metadata to all brokers. Producers and consumers get errors or timeouts on the old leader, refresh their metadata and continue with the new one. Partitions where the broker was only a follower keep working with a smaller ISR.
Q. How long does a leader failover take, and what affects it?
Answer: For a crash, mostly the detection time: broker.session.timeout.ms, 9 seconds by default, plus a short election and metadata propagation, then the clients’ metadata refresh and retry backoff. A controlled shutdown is much faster because the broker hands over its leaderships before stopping. Clusters with very many partitions per broker take longer, and producers whose delivery.timeout.ms is shorter than the failover turn it into visible errors.
Intermediate questions
Q. After failover, the producer retries a batch the old leader had already replicated. Why is no duplicate written?
Answer: With the idempotent producer, each batch carries the producer ID and sequence numbers, and the partition’s producer state is part of the replicated log. The new leader therefore knows the last sequence numbers it has from that producer, recognises the retried batch as already written, and acknowledges it without appending it again. Without idempotence, the retry would create a duplicate.
Q. The old leader had written records that no follower copied yet. What happens to them?
Answer: They are discarded. When the old broker comes back, it uses the leader epoch to find where its history diverges from the new leader’s and truncates everything after that point, then fetches the new leader’s data. With acks=all, those records were never acknowledged, so the producer retried them to the new leader. With acks=1, they may have been acknowledged, and that acknowledged data is lost.
Tricky and scenario questions
Q. A partition leader crashes while the producer is publishing. How does Kafka recover, and how do you ensure no acknowledged messages are lost?
Answer: The controller elects an in-sync follower as the new leader, and the producer, which retries automatically until delivery.timeout.ms, refreshes metadata and resends its in-flight batches there. To ensure acknowledged messages survive, decide before the failure: replication factor 3, min.insync.replicas=2, acks=all, idempotence enabled, unclean leader election disabled, a delivery timeout longer than a failover, and replicas spread across racks or zones. Then every acknowledged record exists on at least two brokers, and only a replica holding all of them can become leader.
Q. A broker came back an hour ago, but it still leads no partitions and load is uneven. Is something wrong?
Answer: Not necessarily. A returning broker first truncates, catches up and rejoins the ISR as a follower; leadership does not move back automatically at that moment. With auto.leader.rebalance.enable=true (the default), the controller periodically moves leadership back to preferred replicas when the imbalance exceeds a threshold. You can also trigger it with kafka-leader-election.sh --election-type PREFERRED. If the broker is still out of the ISR, check its replication lag and logs first.