00:00

Leader Election in Apache Kafka

Last updated:

Every Kafka partition has one leader replica that handles all writes. When the broker holding a leader fails or shuts down, Kafka must choose a new leader quickly and safely. This process is called leader election.

There are two kinds of election in a modern Kafka cluster: the election of the active controller inside the KRaft quorum, and the election of partition leaders, which the controller performs. This tutorial explains both, how Kafka avoids losing data during an election, and how to restore balanced leadership.

1. What Is Leader Election?

Partition leader election is the choice of which replica becomes the leader of a partition. The new leader is normally taken from the in-sync replicas (ISR), because they are known to have every committed record.

Definition: Leader election in Kafka is the process by which the active KRaft controller chooses a new partition leader, normally from the ISR, and publishes the decision to all brokers through the metadata log.

2. Why Leader Election Matters

  • Availability: a partition without a leader accepts no reads or writes. Fast elections keep downtime to seconds.
  • Durability: electing a replica that is missing records would lose acknowledged data.
  • Load balance: leaders do most of the work, so the placement of leaders affects broker load.

3. How Leader Election Works

3.1 Controller election in KRaft

Since Kafka 4.0, the cluster metadata is managed by a group of controllers using the KRaft protocol, a Raft-based consensus protocol; ZooKeeper is no longer supported. One controller is the active controller (the Raft leader). If it fails, the remaining controllers elect a new one by majority vote. With three controllers, the quorum survives one controller failure; with five, two. See KRaft for setup details.

3.2 Partition leader election

Partition leader election after a broker failurePartition 0 has replicas on brokers 1, 2 and 3, with broker 1 as leader and all three in the ISR. Broker 1 stops sending heartbeats to the active controller. The controller removes broker 1 from the ISR, picks broker 2 as the new leader with leader epoch 8, and writes the change to the metadata log. Brokers 2 and 3 apply the change; producers and consumers refresh their metadata and switch to broker 2. broker 1 (leader)stops heartbeating broker 2 (follower)in ISR broker 3 (follower)in ISR active controller 1. fence broker 12. pick first live ISR replica3. bump leader epoch to 8 metadata logP0 leader=2 isr=[2,3] clientsrefresh metadata missed brokers 2 and 3 apply the new leadership
The active controller chooses a new leader from the ISR and publishes it through the metadata log.
  1. Every broker sends heartbeats to the active controller. If a broker stops (crash or network partition), the controller fences it after broker.session.timeout.ms (9 seconds by default).
  2. For every partition led by that broker, the controller selects a new leader: the first replica in the replica list that is alive and in the ISR.
  3. It increases the partition's leader epoch and writes the new leader and ISR to the metadata log.
  4. Brokers apply the record; clients receive NotLeaderOrFollowerException, refresh metadata and continue with the new leader.

During a planned shutdown, a broker first asks the controller to move its leaders away (controlled shutdown), so clients see almost no interruption.

3.3 Leader epochs

The leader epoch is a counter that increases with every leader change. Followers use it to truncate any records that the old leader wrote but never committed, and brokers reject requests from an old leader with a stale epoch. This prevents "zombie" leaders from causing divergent logs.

3.4 Unclean leader election

If no ISR member is alive, Kafka has two choices. By default (unclean.leader.election.enable=false) the partition stays offline until an ISR replica returns, so no committed data is lost. If unclean election is enabled, an out-of-sync replica may become leader: the partition comes back sooner, but records it never received are lost. Kafka 4.x also adds Eligible Leader Replicas (KIP-966), enabled by default on new clusters since Kafka 4.1, which tracks replicas that are safe to elect even after they leave the ISR and reduces the need for unclean elections. See In-Sync Replicas (ISR) for a worked example.

3.5 Preferred leaders

The first replica in a partition's replica list is its preferred leader. After failures, leadership can pile up on a few brokers. With auto.leader.rebalance.enable=true (the default), the controller checks every leader.imbalance.check.interval.seconds (300) and moves leadership back when a broker's imbalance exceeds leader.imbalance.per.broker.percentage (10%).

4. Configuration

SettingDefault (Kafka 4.4)Purpose
unclean.leader.election.enablefalseAllow out-of-sync replicas to become leader
auto.leader.rebalance.enabletrueMove leadership back to preferred replicas automatically
leader.imbalance.check.interval.seconds300How often the controller checks leader balance
broker.session.timeout.ms9000Time without heartbeats before a broker is fenced
controller.quorum.bootstrap.serversnoneControllers that brokers and controllers contact

5. Java Example: Watching a Leader Fail Over

This program uses the Admin API to print the leader and ISR of partition 0 of the payments topic every second, but only when they change. Run it, then stop the broker that leads the partition, and you can watch the election happen.

LeaderWatcher.java
package com.javabytechie.kafka;

import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.TopicPartitionInfo;

public class LeaderWatcher {

    public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092,localhost:9093,localhost:9094");

        try (Admin admin = Admin.create(props)) {
            String last = "";
            while (true) {
                TopicPartitionInfo p0 = admin.describeTopics(List.of("payments"))
                        .allTopicNames().get().get("payments").partitions().get(0);
                String state = "leader " + p0.leader().id() + ", isr " + ids(p0.isr());
                if (!state.equals(last)) {
                    System.out.println("payments-0: " + state);
                    last = state;
                }
                Thread.sleep(1000);
            }
        }
    }

    static String ids(List<Node> nodes) {
        return nodes.stream().map(n -> String.valueOf(n.id())).collect(Collectors.joining(",", "[", "]"));
    }
}

Typical output on a three-broker cluster when broker 1 leads payments-0 and is shut down (broker IDs depend on your cluster):

Output
payments-0: leader 1, isr [1,2,0]
payments-0: leader 2, isr [2,0]

When broker 1 stops, the controller removes it from the ISR and makes the next live ISR replica in the replica list, broker 2, the leader. When broker 1 restarts and catches up, it rejoins the ISR, and automatic leader rebalancing later makes it leader again because it is the preferred replica.

5.1 Triggering elections from the command line

Terminal
# move leadership back to preferred replicas for all partitions
bin/kafka-leader-election.sh --bootstrap-server localhost:9092 \
  --election-type preferred --all-topic-partitions

# last resort when every ISR replica is lost (may lose data)
bin/kafka-leader-election.sh --bootstrap-server localhost:9092 \
  --election-type unclean --topic payments --partition 0

6. Common Mistakes

  • Enabling unclean leader election cluster-wide for convenience, which can silently drop acknowledged records.
  • Running only one or two controllers: a two-node quorum cannot survive the loss of either node.
  • Hard-killing brokers during upgrades instead of a clean shutdown, which turns a planned change into many unplanned elections.
  • Ignoring offline partitions (OfflinePartitionsCount metric), which mean no leader is available.

7. Best Practices

  • Run three or five dedicated controllers in production, in different failure domains.
  • Keep unclean.leader.election.enable=false and override it per topic only for data where availability matters more than loss.
  • Use replication factor 3 and min.insync.replicas=2 so an ISR replica is usually available for election.
  • Shut brokers down cleanly and let automatic leader rebalancing restore balance after maintenance.

8. Conclusion

Leader election keeps Kafka available when brokers fail. The KRaft quorum elects the active controller by majority vote, and the controller elects partition leaders from the ISR and fences old leaders with leader epochs. Keep unclean election disabled, run an odd number of controllers, and use preferred leader election to rebalance load. See Replication in Apache Kafka for how the ISR is maintained.

9. References