解决 Kafka 报错 LeaderNotAvailableException 分区选举中断
分析 Kafka 客户端报 LeaderNotAvailableException 与 NOT_LEADER_OR_FOLLOWER 根因,提供 Broker 副本重平衡与 controller 恢复步骤。
问题现象
Kafka 生产者向指定 Topic 发送消息或消费者订阅消费时,客户端频繁抛出警告并伴随消息发送失败:
org.apache.kafka.common.errors.LeaderNotAvailableException:
There is no leader for this topic-partition as we are in the middle of a leadership election.
或者提示:NOT_LEADER_OR_FOLLOWER。Topic 部分分区处于离线状态,数据流发生断流。
触发根因
- 原 Leader 副本所在 Broker 宕机或网络分区:Controller 正在为该分区重新从同步副本集合(In-Sync Replicas, ISR)中选举新 Leader,在选举完成前(微秒到数秒)抛出该异常。
- 所有副本全部脱离 ISR(脏选举未开启):如果分区的所有副本都发生网络延迟或挂掉,且集群配置了
unclean.leader.election.enable=false,Controller 无法选举出合法 Leader,导致分区永久处于 Offline 状态。 - Kafka Controller 节点发生脑裂或卡顿:Active Controller 出现长时间 Full GC,未能及时处理集群元数据变更。
诊断排查步骤
- 查询该 Topic 的详细分区拓扑与 Leader 状态:
kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic my-topic
重点观察是否存在 Leader: none 或 Isr: 列表为空的分区。
- 查询当前集群中所有的离线分区:
kafka-topics.sh --bootstrap-server localhost:9092 --describe --unavailable-partitions
解决步骤与操作命令
步骤一:拉起离线的 Broker 节点
登录掉线的 Broker 节点检查磁盘与内存,重新启动 Kafka 进程:
sudo systemctl restart kafka
Broker 启动并重新向 ZooKeeper / KRaft 注册后,ISR 会自动恢复同步并重新分配 Leader。
步骤二:紧急恢复无主分区(开启脏选举,评估数据一致性)
若原 ISR 节点彻底物理损坏无法修复,可通过动态配置临时允许非 ISR 副本竞选 Leader(注意:可能丢失少量未同步数据):
kafka-configs.sh --bootstrap-server localhost:9092 --entity-type topics --entity-name my-topic --alter --add-config unclean.leader.election.enable=true
步骤三:客户端参数调优(抵御短暂网络闪断)
在生产者参数中配置合理的自动重试,平滑抵御 Leader 切换期的秒级抖动:
retries=10
retry.backoff.ms=500
request.timeout.ms=30000
步骤四:执行分区重平衡验证
kafka-leader-election.sh --bootstrap-server localhost:9092 --election-type preferred --all-topic-partitions
验证所有分区状态恢复为正常数值,客户端写入平稳顺畅。


