Leader Election in Apache Kafka
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.
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
- 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). - 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.
- It increases the partition's leader epoch and writes the new leader and ISR to the metadata log.
- 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
| Setting | Default (Kafka 4.4) | Purpose |
|---|---|---|
unclean.leader.election.enable | false | Allow out-of-sync replicas to become leader |
auto.leader.rebalance.enable | true | Move leadership back to preferred replicas automatically |
leader.imbalance.check.interval.seconds | 300 | How often the controller checks leader balance |
broker.session.timeout.ms | 9000 | Time without heartbeats before a broker is fenced |
controller.quorum.bootstrap.servers | none | Controllers 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.
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):
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
# 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 (
OfflinePartitionsCountmetric), 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=falseand override it per topic only for data where availability matters more than loss. - Use replication factor 3 and
min.insync.replicas=2so 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
Kafka Leader Election Interview Questions and Answers
Common interview questions on Kafka Leader Election, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. Who elects partition leaders in a KRaft-based Kafka cluster?
Answer: The active controller. It detects failed brokers through missed heartbeats, chooses new leaders from the ISR and writes the result to the metadata log, which all brokers replicate. There is no ZooKeeper involvement in Kafka 4.x.
Q. What is a preferred leader?
Answer: The first replica in a partition's replica list. Kafka tries to keep leadership on preferred replicas because the initial assignment spreads them evenly across brokers. Automatic leader rebalancing or kafka-leader-election.sh --election-type preferred restores them after failures.
Intermediate questions
Q. What is controlled shutdown, and why does it matter during maintenance?
Answer: When a broker is stopped gracefully, it first asks the active controller to move leadership of all its partitions to other in-sync replicas, and only then shuts down. Clients see a quick leader change instead of request timeouts, and no partition is left without a leader while the broker restarts. A hard kill skips this step, so leaders are only replaced after the broker’s session times out. Always stop brokers with kafka-server-stop.sh or a normal process signal during rolling restarts.
Q. What is a leader epoch used for?
Answer: It is a number that increases on every leader change. When a follower starts fetching from a new leader, it uses the epoch to find where its log diverges and truncates records the old leader never committed. Brokers also reject requests carrying an older epoch, which fences a former leader that has not yet noticed it was replaced.
Tricky and scenario questions
Q. What happens to partition leaders when the active controller itself fails?
Answer: Usually nothing visible. The remaining controllers elect a new active controller through Raft, typically within a few seconds, and it already has the full metadata log, so it continues where the old one stopped. Partition leaders on the brokers do not change, and producers and consumers keep working. Only metadata operations, such as creating topics or electing new partition leaders after a broker failure, wait until the new controller is active.
Q. All replicas in a partition's ISR are down. What are your options?
Answer: Wait for an ISR replica to come back, which keeps all committed data but leaves the partition offline. Or run an unclean election (kafka-leader-election.sh --election-type unclean or the topic setting), which restores availability but loses records the chosen replica never received. The decision depends on whether the data or the downtime is more costly.