Symptoms
All partitions are online and the ISR is full, but:
- One or two brokers run at much higher CPU, network and request latency than the others.
- Producers log warnings like
Received invalid metadata error in produce request on partition ... due to org.apache.kafka.common.errors.NotLeaderOrFollowerException ... Going to request metadata update now. - Consumers or the admin tools show
LEADER_NOT_AVAILABLEfor a few seconds after a topic is created or a broker restarts. - A broker that came back from a rolling restart sits mostly idle.
Every partition has one leader, and that leader handles all its produce and fetch traffic (unless consumers fetch from followers). If leadership is uneven, the load is uneven too, even when the replicas are spread perfectly.
Is it a real problem or normal noise?
NOT_LEADER_OR_FOLLOWER and LEADER_NOT_AVAILABLE are retriable errors. The client refreshes metadata, finds the new leader and retries. A burst during a restart, a reassignment or a leader election is expected.
| What you see | Likely cause | Action |
|---|---|---|
| Warnings for a few seconds during a restart or deploy | Leadership moved during controlled shutdown | None. Check that the producer's delivery.timeout.ms was not exceeded |
LEADER_NOT_AVAILABLE right after topic creation | Leaders are not elected yet, or auto-creation is in progress | None, unless it lasts more than a few seconds |
| Warnings that never stop for one partition | Partition has no leader (Leader: -1 or none) | Not this post. Follow the offline partitions runbook |
| No errors, but one broker leads most partitions | Leaders not moved back after a restart, or auto rebalance disabled | Preferred leader election (below) |
| Election runs but imbalance stays | The preferred replicas themselves are skewed | Reassign with a corrected replica order |
Producer TimeoutException during leader moves | Retries outlasted delivery.timeout.ms | Find out why the election took so long. Don't just raise the timeout |
Check 1: rule out offline and under-replicated partitions
BS=broker1:9092
kafka-topics.sh --bootstrap-server $BS --describe --unavailable-partitions
kafka-topics.sh --bootstrap-server $BS --describe --under-replicated-partitions
kafka-topics.sh --bootstrap-server $BS --describe --under-min-isr-partitions
If any of these return rows, deal with them first. A preferred leader election cannot move leadership to a replica that is not in the ISR.
Check 2: measure leader distribution
The preferred leader is the first broker in the Replicas: list. Kafka tries to keep the leader on that broker.
Leaders per broker:
kafka-topics.sh --bootstrap-server $BS --describe \
| awk '/Leader:/ {for(i=1;i<=NF;i++) if($i=="Leader:") print $(i+1)}' \
| sort | uniq -c | sort -rn
Partitions whose leader is not the preferred replica:
kafka-topics.sh --bootstrap-server $BS --describe \
| awk '/Leader:/ {
for(i=1;i<=NF;i++){ if($i=="Leader:") l=$(i+1); if($i=="Replicas:") r=$(i+1) }
split(r,a,","); if(a[1]!=l) { n++; print } }
END { print "not on preferred leader:", n+0 }'
Preferred replicas per broker, which shows the balance you get after a perfect election:
kafka-topics.sh --bootstrap-server $BS --describe \
| awk '/Replicas:/ {for(i=1;i<=NF;i++) if($i=="Replicas:") {split($(i+1),a,","); print a[1]}}' \
| sort | uniq -c | sort -rn
If the second count is even and the first is not, an election will fix it. If the second count is skewed as well, an election won't help (see "Fix 2").
Metrics to watch
| Metric (JMX) | Meaning |
|---|---|
kafka.server:type=ReplicaManager,name=LeaderCount | Partitions led by this broker. Compare across brokers |
kafka.server:type=ReplicaManager,name=PartitionCount | Replicas hosted by this broker |
kafka.controller:type=KafkaController,name=PreferredReplicaImbalanceCount | Partitions not led by their preferred replica (reported by the active controller) |
Metric names can differ between ZooKeeper and KRaft mode and across versions. Check your build's JMX tree before you alert on them.
Why leaders end up in the wrong place
- Rolling restart. Controlled shutdown moves leadership off the broker being stopped. When the broker comes back it is a follower for everything. It gets leadership back only when the controller runs the automatic rebalance or someone triggers an election.
- Auto rebalance is off or slow. Three broker settings control it:
| Setting | Default | Effect |
|---|---|---|
auto.leader.rebalance.enable | true | Controller periodically moves leaders back to preferred replicas |
leader.imbalance.check.interval.seconds | 300 | How often the controller checks |
leader.imbalance.per.broker.percentage | 10 | Imbalance per broker (as a percentage) that triggers a rebalance |
With these defaults a returning broker can wait 5 minutes or more. A small imbalance below the 10% threshold is never corrected.
- Skewed replica order. Topics created while a broker was down, or reassigned with a hand-written plan, can list the same broker first for most partitions. The preferred leader is then itself in the wrong place.
Check the live values:
kafka-configs.sh --bootstrap-server $BS --entity-type brokers --entity-name 1 \
--describe --all | grep -E 'auto.leader.rebalance|leader.imbalance'
Fix 1: run a preferred leader election
This is safe during business hours on a healthy cluster. Each moved partition gives producers and consumers a short burst of retriable errors.
Start with one topic:
kafka-leader-election.sh --bootstrap-server $BS \
--election-type PREFERRED --topic orders --partition 0
Then all partitions:
kafka-leader-election.sh --bootstrap-server $BS \
--election-type PREFERRED --all-topic-partitions
Or a list from a JSON file, to move leaders in batches on a large cluster:
{"partitions": [
{"topic": "orders", "partition": 0},
{"topic": "orders", "partition": 1},
{"topic": "payments", "partition": 3}
]}
kafka-leader-election.sh --bootstrap-server $BS \
--election-type PREFERRED --path-to-json-file elect.json
Partitions whose leader is already the preferred replica are skipped. Partitions whose preferred replica is not in the ISR fail and are listed in the output. Re-run Check 2 afterwards.
Caution
Do not use
--election-type UNCLEANto "fix" imbalance. An unclean election can make an out-of-sync replica the leader and permanently lose acknowledged messages. It is a last resort for offline partitions only, and only with sign-off from the data owner.
Fix 2: correct the replica order
If the preferred replicas are skewed, generate a balanced plan and apply it with a throttle. Leaders follow the first broker in each new replica list.
echo '{"topics":[{"topic":"orders"}],"version":1}' > topics.json
kafka-reassign-partitions.sh --bootstrap-server $BS \
--topics-to-move-json-file topics.json --broker-list "1,2,3" --generate
Save the proposed plan to plan.json. If the replica sets don't change and only their order does, no data is copied. Apply and verify:
kafka-reassign-partitions.sh --bootstrap-server $BS \
--reassignment-json-file plan.json --execute --throttle 50000000
kafka-reassign-partitions.sh --bootstrap-server $BS \
--reassignment-json-file plan.json --verify
--verify also removes the throttle when the reassignment is complete. Run Fix 1 afterwards so the leaders move to the new preferred replicas.
Warning
--generatecan propose moving replicas to different brokers, not only reordering them. Moving replicas copies data and loads disks and the network. Review the plan, keep--throttle, and run large topics in batches.
Client settings that ride out leader moves
Defaults on modern Java clients handle elections well. Check that nobody has overridden them downwards:
| Client setting | Default | Note |
|---|---|---|
retries | 2147483647 | Keep high. delivery.timeout.ms sets the real limit |
delivery.timeout.ms | 120000 | Total time to deliver a record, including retries |
retry.backoff.ms | 100 | Pause between retries |
metadata.max.age.ms | 300000 | Forced metadata refresh. Leader errors trigger an earlier refresh anyway |
Producers with retries=0 or a very short delivery.timeout.ms turn a normal election into lost or failed writes.
Prevent it next time
- Make a preferred leader election the last step of every rolling restart runbook, after the final broker rejoins the ISR.
- Keep
auto.leader.rebalance.enable=trueunless a balancing tool such as Cruise Control manages leadership for you. - Alert when the spread of
LeaderCountbetween brokers stays high for more than 15 minutes, not on individualNOT_LEADER_OR_FOLLOWERlog lines. - Create topics only when all brokers are up, and check the preferred replica count after large reassignments.
- Review producer configs for
retries=0and short delivery timeouts during onboarding.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get