Kafka Consumer Groups: Rebalancing Without Pauses
Senior level ยท How partitions get handed between instances, and how to stop every deploy from stalling the pipeline.
Prerequisites
- !Consumer offsets and commit semantics
- !Kafka topic partitioning
What You'll Learn
- 1Walk through the rebalance protocol step by step and name the broker role that drives it
- 2Pick an assignment strategy based on partition count and restart behaviour
- 3Tune session, heartbeat and poll timeouts so they reinforce each other
- 4Use static membership and a rebalance listener to remove stop-the-world pauses
Why a group rather than a connection
A consumer group is a named set of cooperating instances that together own every partition of one or more topics. Ownership is exclusive: at any moment exactly one consumer in the group is assigned a given partition, which is what lets you scale processing horizontally without adding coordination code to your handlers. Ten consumers on a topic with twenty partitions each receive two partitions; an eleventh consumer receives nothing, because partitions are the unit of parallelism and you cannot subdivide one.
The group also stores its progress centrally. Offsets are committed to an internal topic keyed by group and partition, so any instance can be replaced and pick up where its predecessor stopped. Two consequences follow that catch teams out. Adding consumers beyond the partition count buys nothing, and a single slow partition caps throughput for that key no matter how many other consumers are idle.
The rebalance protocol, one message at a time
A rebalance is triggered when a consumer joins, leaves, misses heartbeats, or takes longer than max.poll.interval.ms between polls. From that trigger to resumed processing the coordinator runs four steps.
Trigger: join, crash, missed heartbeat, poll interval exceeded, or topic metadata change
1. JoinGroup each member announces itself; one member is elected group leader
2. SyncGroup the leader computes the assignment and returns it per member
3. Assign every member receives its partitions and rejoins the fetch pool
4. Resume fetch and processing continue from the committed offsets
Meanwhile: members keep heartbeating from a background thread so a long
handler does not look like a dead consumer, provided max.poll.interval.ms
has not been exceeded.
The elected leader is an ordinary consumer, not the broker, and it runs the assignor algorithm locally. That is why every instance in the group must run the same assignor version: a mismatched leader silently produces an assignment other members cannot interpret.
Assignment strategies and where each one hurts
| Strategy | How it divides work | Rebalance cost | Use it when |
|---|---|---|---|
| RangeAssignor | First consumer gets a contiguous block per topic | Full reassignment, uneven across topics | One topic per group and simple topologies |
| CooperativeSticky | Keeps existing owners, moves only what must move | Incremental, two-phase, minimal movement | Long-running groups that restart often |
| RoundRobin | Cycles through consumers across all subscribed topics | Full reassignment, even spread | Several topics of similar partition counts |
| StaticGroupMembership | Reuses the previous assignment for a known instance id | No rebalance within the session timeout | Fixed instance ids and rolling deployments |
RangeAssignor is the default and behaves badly when a group subscribes to several topics of different sizes, because it restarts the range calculation per topic and can hand one consumer far more work than another. RoundRobin fixes the spread but still throws the whole assignment away on every event. CooperativeSticky, available since Kafka 2.4, lets the group revoke only the partitions that must change, so a single consumer restarting costs a short pause for one instance instead of the whole group.
๐กPick the assignor before you need it
Timeouts that decide how failure looks
Three timeouts interact, and misreading them is the most common cause of mystery rebalances.
# Broker side, per group configuration
session.timeout.ms=30000 # how long silence is tolerated
heartbeat.interval.ms=10000 # keep it near one third of session timeout
# Client side
max.poll.interval.ms=300000 # longest allowed gap between poll calls
fetch.min.bytes=1
max.poll.records=500
session.timeout.ms bounds the gap between heartbeats, which a background thread sends independently of your handler. max.poll.interval.ms bounds the gap between calls to poll, and it cannot be hidden behind a heartbeat: if your handler processes a batch for six minutes with a five-minute limit, the coordinator evicts the member even though heartbeats flowed the whole time. Raising max.poll.interval.ms without shrinking the batch usually just delays the eviction.
The rule of thumb is to keep heartbeat.interval.ms at roughly a third of session.timeout.ms so one lost heartbeat never threatens membership, and to size max.poll.records so a batch completes well inside max.poll.interval.ms including retries.
Static membership and rolling restarts
Without static membership, every restart is a leave followed by a join, and the group pays a full rebalance for a planned deployment. Setting group.instance.id gives each instance a stable identity, so a process that returns within session.timeout.ms is handed back its previous assignment without a rebalance at all.
# One stable identity per instance, typically from the pod name
export GROUP_INSTANCE_ID="order-processor-${HOSTNAME}"
kafka-console-consumer.sh \
--bootstrap-server kafka1:9092 \
--group order-processor \
--consumer.config /etc/kafka/consumer.properties
# Confirm membership and lag after a rollout
kafka-consumer-groups.sh --bootstrap-server kafka1:9092 \
--describe --group order-processor --members --verbose
Deployments then become invisible to the group as long as each pod is replaced within the session window. Set instance ids from something stable such as a Kubernetes pod name, never from a random suffix, or the group treats every new pod as a stranger.
The rebalance listener you should always register
Silent rebalances are how data gets processed twice. Registering a listener lets you commit what you already finished and release resources before partitions move away.
consumer.subscribe(Collections.singletonList("orders"), new ConsumerRebalanceListener() {
@Override
public void onPartitionsRevoked(Collection<TopicPartition> revoked) {
// Partitions are about to move: flush progress for them only
if (!revoked.isEmpty()) {
consumer.commitSync(currentOffsets(revoked));
}
openCursors.keySet().retainAll(assigned);
}
@Override
public void onPartitionsAssigned(Collection<TopicPartition> assigned) {
// Rebuild per-partition state: file handles, caches, rate limiters
assigned.forEach(tp -> openCursors.put(tp, buildCursor(tp)));
log.info("processing partitions {}", assigned);
}
});
Commit inside onPartitionsRevoked rather than after each record. Per-record synchronous commits turn a healthy consumer into the slowest member in the group and invite the very rebalances you are trying to avoid.
Watching lag instead of guessing
kafka-consumer-groups.sh --bootstrap-server kafka1:9092 \
--describe --group order-processor
# GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG
# order-processor orders 0 918224 918310 86
# order-processor orders 1 918102 918102 0
# order-processor orders 2 901455 918109 16654
The aggregate lag hides the story: two partitions are current and one is sixteen thousand behind, which points at a hot key or a stuck instance rather than a capacity problem. Alert on per-partition lag and on the number of active consumers versus partitions, because both failure modes present as rising end-to-end latency.
When rebalances go wrong in production
The most common rebalance incident is not a broker problem; it is a consumer whose poll loop does too much work. When a single poll takes longer than max.poll.interval.ms, the member is evicted even though its heartbeat thread is healthy and connected. From the outside the group looks stable until the eviction fires, at which point every partition assigned to the evicting member is revoked and reassigned, often to a member that was already near its own poll limit. The result is a cascade: one slow member triggers a rebalance that stalls several others, and the group oscillates between joined and rebalancing for minutes.
The second failure mode is a rebalance storm during a rolling restart without static membership. Each pod termination triggers a full stop-the-world rebalance on a large group, and if the restart policy brings pods back faster than the session timeout expires, the group can enter a loop of JoinGroup and SyncGroup that never completes before the next departure. Teams that deploy twenty consumer pods in a single rollout without static membership or cooperative assignment routinely see rebalances that last longer than the deploy itself, during which end-to-end latency spikes well past the SLO.
The third mode is subtle and worth calling out: a rebalance listener that commits offsets after partitions have already been revoked. Committing an offset for a partition you no longer own writes progress for another member's partition, and that member may have already advanced past your position. When the group stabilizes, some records are skipped because the offset was moved forward by a member that did not process them. The fix is structural, not tunable: commit inside onPartitionsRevoked, before the assignment change takes effect, so the offsets you write are always for partitions you still hold.
A fourth operational pattern is a consumer that joins a group for the first time and starts from the wrong position. Without a committed offset, the default is auto.offset.reset, and if that is set to latest the consumer silently skips everything that arrived while it was down. For critical pipelines set auto.offset.reset to earliest and let the application decide, or commit an explicit initial offset during a controlled startup, rather than inheriting a default that silently drops a backlog.
None of these problems is fixed by raising a timeout. The timeouts exist to bound failure detection; the underlying cause is almost always work in the poll loop that belongs in a separate thread pool, a batch size that is too large for the processing budget, or a deployment strategy that ignores how the assignor behaves under concurrent departures.
Common Mistakes
Scaling consumers past the partition count and expecting more throughput
Fix: Add partitions first, then consumers. An extra consumer on a fully assigned topic sits idle while still triggering rebalances on every restart.
Raising session.timeout.ms to stop rebalances
Fix: Find the real cause, usually a batch that exceeds max.poll.interval.ms or a GC pause. Longer session timeouts only slow down detection of genuinely dead members.
Leaving the default RangeAssignor on a group subscribed to many topics
Fix: Move to CooperativeSticky so restarts revoke only the affected partitions and rolling deploys stop stopping the world.
Committing offsets after every single record
Fix: Commit per poll batch or inside the rebalance listener. Per-record commits add a round trip per message and push your consumer to the back of the ISR.
Best Practices
- Set group.instance.id on every long-lived instance so planned restarts never rebalance
- Size max.poll.records so a worst-case batch finishes in under half of max.poll.interval.ms
- Commit offsets in batches and always in onPartitionsRevoked before partitions move
- Track per-partition lag and consumer count against partition count as first-class dashboards
- Upgrade assignor implementations across the whole group in one rollout
Interview Questions
Q1: What is the difference between session.timeout.ms and max.poll.interval.ms?
session.timeout.ms bounds missed heartbeats, which a background thread sends regardless of handler work. max.poll.interval.ms bounds the gap between poll calls and cannot be masked by heartbeats; exceeding it evicts the member even while it is healthy and connected.
Q2: Why does adding an eleventh consumer not increase throughput?
Partitions are the unit of assignment and a partition is owned by exactly one consumer at a time. With ten partitions the eleventh consumer receives none, so it contributes only rebalance overhead.
Q3: Explain what CooperativeStickyAssignor changes about a rebalance.
It performs an incremental cooperative rebalance: members keep their existing partitions and only the partitions that must move are revoked, in a second phase. The default eager assignors revoke everything and pause the whole group first.
Q4: A consumer keeps getting kicked out of the group under load. What do you check?
Compare batch processing time against max.poll.interval.ms first, then check GC pauses and network stalls that delay poll, then confirm heartbeat.interval.ms is well inside session.timeout.ms. Raising session.timeout.ms rarely fixes a poll interval violation.
Q5: How does static group membership change restart behaviour?
With group.instance.id set, a member that reconnects within session.timeout.ms is restored to its previous assignment instead of triggering JoinGroup and SyncGroup, so a rolling restart causes no rebalance at all.
Key Takeaways
- A consumer group gives exclusive partition ownership plus centrally stored offsets, so parallelism is bounded by partition count
- Rebalances run JoinGroup, leader-side assignment in SyncGroup, distribution, then resume; the leader is a consumer, not the broker
- CooperativeStickyAssignor revokes only the partitions that must move, turning a group-wide pause into a targeted one
- session.timeout.ms guards heartbeats while max.poll.interval.ms guards poll cadence, and only the second one your handler can violate
- Static membership plus a rebalance listener removes rebalances from planned deploys and stops duplicate processing on unplanned ones