00:00

Kafka Broker Failure and Recovery

Last updated:

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

Partition leader failover in KafkaBroker 1 leads partition orders-0 with followers on brokers 2 and 3, all in sync. The producer writes with acks=all and gets an acknowledgement after all in-sync replicas have the batch. Broker 1 crashes. The KRaft controller stops receiving its heartbeats, and after the broker session timeout it marks broker 1 as fenced, elects broker 2 as the new leader from the ISR and increments the leader epoch. The producer's next request fails or times out, it refreshes metadata and retries the same batch to broker 2; the idempotent producer prevents a duplicate. Consumers move their fetches to broker 2. Later broker 1 restarts, truncates any records the new leader does not have, catches up and rejoins the ISR, and preferred leader election can move leadership back to it. Producer Broker 1leader, epoch 5 Broker 2follower (ISR) Broker 3follower (ISR) ControllerKRaft ① write, acks=all replicate acknowledged ✕② crash ③ no heartbeats for ~9 s: fence broker 1,elect broker 2 from the ISR, epoch 6 metadata: leader = broker 2 ④ refresh metadata, retry same batch acknowledged, no duplicate ⑤ Broker 1 restarts: truncates its divergent tail, catches up from broker 2,rejoins the ISR; preferred leader election can later make it leader again
The controller detects the missing heartbeats, elects a new leader from the ISR, and clients follow the metadata change; the idempotent producer keeps the retry duplicate-free.
  1. 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.
  2. 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.
  3. 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.
  4. Clients follow. Producers and consumers receive errors such as NOT_LEADER_OR_FOLLOWER or 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 a TimeoutException.

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 settingWas the record acknowledged?Outcome
acks=allNo, the leader waits for all in-sync replicasThe producer retries to the new leader; nothing acknowledged is lost
acks=1Yes, right after the leader wrote itThe new leader does not have it; when the old broker returns it truncates the record. Acknowledged data is lost
acks=0Not waited for at allLost 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

  1. 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.dir controls the parallelism.
  2. Register and catch up. The broker registers with the controller, truncates any divergent records, and fetches everything it missed from the current leaders.
  3. 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.
  4. 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:

SettingValueWhy
Replication factor3Two copies remain after one broker fails
min.insync.replicas (topic or broker)2Every acknowledged record exists on at least two brokers; writes fail with NOT_ENOUGH_REPLICAS instead of being acknowledged with one copy
acks (producer)allAcknowledgement only after all in-sync replicas have the record
enable.idempotencetrueRetries to the new leader cannot create duplicates or reorder records
unclean.leader.election.enablefalse (default)Only replicas that have every acknowledged record can become leader
delivery.timeout.mslonger than a failoverRetries keep going through the election instead of failing the send
Rack awareness (broker.rack)one rack or zone per replicaA 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

DurablePaymentProducer.java
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:

Terminal
$ 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=all with min.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.ms that 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.

12. References