Kafka 重平衡
Kafka 重平衡
- 协调者
- Rebalance
- Rebalance 条件
- Rebalance 避免
Rebalance :
- 让单 Group 下所有的 Consumer 怎么消费订阅主题的所有分区
- Rebalance 时 , 所有 Consumer 要共同参与 (无法消费),在协调者 (Coordinator) 协调下,完成订阅主题分区的分配
协调者
协调者 (Coordinator) :
- 给 Group 执行 Rebalance 时,提供位移管理和组成员管理
- Consumer 提交位移 , 就是向 Coordinator 所在的 Broker 提交位移
- 当 Consumer 启动时,会向 Coordinator 所在的 Broker 发送各种请求,由 Coordinator 负责执行消费者组的注册、成员管理记录
所有 Broker 启动时,会创建 Coordinator
- 所有 Broker 都有各自的 Coordinator 组件
- 在
__consumer_offsets
能找 Group 的 Coordinator 在那个 Broker
某个 Group 确定 Coordinator 所在的 Broker 的步骤 :
- 找位移主题的哪个分区保存该 Group 数据:
partitionId = Math.abs(groupId.hashCode() % offsetsTopicPartitionCount)
- 找该分区 Leader 副本的 Broker,该 Broker 为 Coordinator
例子 : 计算该 Group 的 Coordinator
- 当 Group 的
group.id
设置为test-group
,则 hashCode 值 = 627841412 __consumer_offsets
的分区数 (50 个分区)- 将哈希值对分区数进行取模 , 求绝对值计算 :
abs(627841412 % 50) = 12
- 得出位移主题的分区 12 负责保存该 Group 的数据
- 只要找出位移主题分区 12 的 Leader 副本在哪个 Broker 。该 Broker就是 Coordinator
Java Consumer API,能自动发现并连接正确的 Coordinator,能解决定位问题 :
- 当 Consumer Group 出现问题,排查 Broker 端日志时,只要根据该算法就能准确定位 Coordinator 对应的 Broker
Rebalance
Rebalance 弊端 :
- Rebalance 影响 Consumer 端 TPS。Rebalance 时 , Consumer 都搁置
- 当 Group 下成员很多 ,Rebalance 慢
- Rebalance 效率低
例子 : 一个 Group 下有 10 个成员,每个成员平均消费 5 个分区
- 当一个成员退出,就要进行 Rebalance,把该成员之前负责的 5 个分区给其他成员
- 好的做法 : 维持当前 9 个成员消费分区的方案不变,将 5 个分区随机分配给这 9 个成员,能最大限度减少 Rebalance 对剩余 Consumer 的影响
- 默认情况,每次 Rebalance 时,不会考虑之前的分配方案
因此,Kafka-0.11.0.0 推出 StickyAssignor (有粘性的分区分配策略) :
- 每次 Rebalance 时,会尽可能保留之前的分配方案,实现分区分配的最小变动
- 该策略有 bug
Rebalance 条件
Rebalance 发生条件 :
- 组成员数量发生变化
- 订阅主题数量发生变化
- 订阅主题的分区数发生变化
Coordinator 误认为某个 Consumer 已挂要退组
- 当 Group 进行 Rebalance 后,每个 Consumer 都会定期向 Coordinator 发送心跳请求,表明它还活着
- 当某个 Consumer 没有及时发送心跳请求,Coordinator 就认为该 Consumer 挂了,就从 Group 中移除,并进行 Rebalance
Consumer 存活性的时间间隔 : session.timeout.ms
( 默认值是 10 秒)
- Coordinator 在 10 秒内没收到 Group 下某 Consumer 实例的心跳,就认为该 Consumer 挂了
session.timout.ms
决定 Consumer 存活性的时间间隔
控制发送心跳请求频率 : heartbeat.interval.ms
- 该值越小,Consumer 发送心跳请求的频率越高
- 频繁发送心跳请求会额外消耗带宽资源,好处 : 能更快得知是否 Rebalance
- Coordinator 通知各个 Consumer 进行 Rebalance,是将
REBALANCE_NEEDED
封装到心跳请求中
控制 Consumer 实际消费能力 : max.poll.interval.ms
- 限定 Consumer 两次调用 poll 方法的最大时间间隔 (默认值是 5 分钟)
- Consumer 在 5 分钟之内无法消费完 poll 的消息, Consumer 会主动发起离开组请求,Coordinator 就会 Rebalance
Rebalance 避免
Rebalance 避免 :
- Rebalance 因未能及时发送心跳,导致 Consumer 被踢出 Group 而引发
- Rebalance 由 Consumer 消费时间过长导致
- Consumer 端的 GC 频繁 , 排除 GC 停顿
发送心跳配置 :
- 设置
session.timeout.ms = 6s
: 让 Coordinator 能更快定位已挂掉的 Consumer - 设置
heartbeat.interval.ms = 2s
- 保证能发送至少 3 轮的心跳请求,即
session.timeout.ms >= 3 * heartbeat.interval.ms
Consumer 消费时间过长 :
max.poll.interval.ms
> 下游最大处理时间。如 : 下游最长时间是 7 分钟,就设置为 8 分钟左右