Video in progress
Every rolling update of a service with Kafka consumers causes a rebalance storm and lag shoots up. How do you reduce it?
Every time a pod leaves or joins, the consumer group rebalances, and with the eager protocol the whole group stops. The cooperative-sticky assignor, static membership (group.instance.id), proper graceful shutdown and matching rollout settings shorten these stops considerably.
📖 Answer
A consumer group of 12 pods, with a rolling update one by one. Every pod going down is a rebalance, and every new pod joining is another rebalance. That is 24 rebalances, and with the eager protocol, in each of them all consumers give up their partitions and stop. The deploy takes 10 minutes and lag grows to thousands of messages.
- Cooperative rebalancing: with
CooperativeStickyAssignor, only the partitions that must move are given up, and the rest keep working.
spring.kafka.consumer.properties.partition.assignment.strategy=\
org.apache.kafka.clients.consumer.CooperativeStickyAssignor
Moving a running group from eager to cooperative takes a two-step rollout: first both assignors in the list, then in the next deploy only the cooperative one.
-
Static membership: if a consumer is given a stable
group.instance.idand it comes back withinsession.timeout.ms, there is no rebalance at all, and the partitions wait for it. In a Deployment the pod name is new on every rollout, so this fits a StatefulSet better. The cost: the partitions of a consumer that really died are not handed to anyone until the timeout ends. -
Graceful shutdown: if the consumer exits after calling
close(), the group is told immediately. If it dies with SIGKILL, the broker waits forsession.timeout.ms(default 45 s since Kafka 3.0), and for that time the partitions have no owner. Make sure the grace period is long enough for the offset commit andclose(). -
Rollout parameters: raising
maxSurge/maxUnavailableto batch the changes into fewer waves reduces the number of rebalances. But account for the temporary drop in capacity. -
The new protocol: in Kafka 4.0, KIP-848 (
group.protocol=consumer) became GA. Assignment happens on the broker side, incrementally, and clients do not do a stop-the-world. If your broker and client versions allow it, this is the most fundamental fix.
Monitoring: consumer lag, the number and duration of rebalances. These are in the Kafka client's Micrometer metrics. Comparing these graphs before and after a deploy proves the improvement.
Sign up to mark studied questions and save your progress.