Inside Kafka consumer groups: rebalancing, assignors, static membership and liveness
Coordinator and group leader, JoinGroup/SyncGroup, four assignment strategies measured on Kafka 4.3, static membership for rolling deploys, heartbeats versus max.poll.interval.ms, the endless reprocessing loop, and poison pills.
On this page
1. The problem
A service has 20 pods, one consumer each, reading a 60-partition topic. Every rolling deploy, lag spikes for 10 minutes: about 40 rebalances, each stopping the whole group. The same month, a consumer reprocesses the same 5 records from offset 0 all afternoon while its heartbeat stays steady.
2. Key idea
The coordinator is the broker leading partition hash(group.id) % 50 of __consumer_offsets; it tracks members, offsets and liveness. In the classic protocol, assignment is done by one consumer: the group leader. Each rebalance creates a new generation; commits carrying an old generation are rejected.
| Assignor | Adding c3 to a 2-consumer group | Use when | Don't use when |
|---|---|---|---|
| Range (eager) | 10 revocations (c1), 4 partitions move | you need co-partitioning (joining two topics) | many topics: remainders pile onto one consumer |
| CooperativeSticky | 4 revocations, 2 partitions move | the default choice for classic | you need co-partitioning |
KIP-848 (group.protocol=consumer) |
4 revocations, 2 move, no barrier | broker and client are both 4.x | old clients |
Measured on Kafka 4.3 with two topics of 3 partitions each. The Java client's default is [RangeAssignor, CooperativeStickyAssignor], which means it still uses range: to get cooperative you must say so, across two rolling deploys.
2.1 Alive, or still working?
| Check | Who does it | Default | Fails when |
|---|---|---|---|
| Alive | the heartbeat thread | session.timeout.ms 45 s |
the process dies, the network breaks, long GC pauses |
| Still working | the client, between poll() calls |
max.poll.interval.ms 300 s |
batches take too long, a thread hangs |
Missing the poll deadline → leave the group → the commit is rejected (CommitFailedException) → the next poll restarts from the old offset → miss the deadline again. Raising session.timeout.ms does not help. Plan ahead: max.poll.records × p99 per record < max.poll.interval.ms, with 2× headroom.
Static membership: dynamic members send LeaveGroup on close and trigger an immediate rebalance; static members don't, and the coordinator waits out the session timeout. The gain: rolling deploys without rebalances. The cost: when a pod really dies, nobody reads its partitions until the timeout expires.
3. In Java
Config for 20 pods, and skipping a poison pill.
props.put(ConsumerConfig.GROUP_INSTANCE_ID_CONFIG, System.getenv("POD_NAME")); // static member
props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 60_000); // > restart time
props.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG,
CooperativeStickyAssignor.class.getName());
props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 100); // 100 × p99 1.2 s = 120 s < 300 s
while (running) {
try {
for (var r : consumer.poll(Duration.ofMillis(500))) handle(r);
consumer.commitSync();
} catch (RecordDeserializationException e) {
deadLetter.send(e.topicPartition(), e.offset(), e); // keep it for investigation
consumer.seek(e.topicPartition(), e.offset() + 1); // skip the broken record
}
}Without the seek, poll() throws the same error forever and the whole partition stalls. With group.protocol=consumer, remove partition.assignment.strategy and session.timeout.ms from the client: setting them together throws ConfigException. Spring Kafka: ErrorHandlingDeserializer + DefaultErrorHandler + DeadLetterPublishingRecoverer.
Rebalance listeners, poison pills and ordering
onPartitionsRevoked: the consumer is still a valid member, so commit what you finished for partitions you're losing.onPartitionsLost(kicked out, session expired): you can no longer commit; clean up local state and accept that part will be reprocessed.- Sending a poison pill to a DLT lets later events of the same key run before the broken one: it breaks per-key ordering. Flows needing strict order (ledgers) should stop the partition and page someone, or block that key and send its later events to the DLT too.
- Retry a few times for transient errors (DB timeouts), DLT immediately for permanent ones (deserialisation, validation).
- The
time-between-poll-maxmetric approachingmax.poll.interval.msis an early warning before the loop starts. - A
KafkaConsumerwithoutgroup.idcallingsubscribe()throwsInvalidGroupIdException; the randomconsole-consumer-xxxxxgroups belong to the CLI tool.
4. Working with AI
Hand to AI: computing max.poll.records from p99, tests that kill a consumer mid-batch.
Check in AI-written code:
- The assignor is explicit (cooperative) or
group.protocol=consumeris used; not the default range. -
max.poll.records × p99 < max.poll.interval.ms / 2. -
RecordDeserializationExceptionis handled (seek past it, DLT). - Commits happen in
onPartitionsRevoked, not inonPartitionsLost. - Static membership has a
session.timeout.msabove the p99 pod restart time.
5. Exercises
Exercise 1: Read a reprocessing-loop incident
Consumer log: poll -> 5 records from offset 0, 6 seconds later commitSync FAILED: CommitFailedException ... kicked out of the group, then LOST [orders-0], assigned [orders-0], and again poll -> 5 records from offset 0. It repeats 3 times. Config: max.poll.interval.ms=4000, max.poll.records=5, 1.2 s per record. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.
Solution to Exercise 1
- Diagnosis: 5 × 1.2 s = 6 s > 4 s. The consumer is kicked for missing the poll deadline, its commit is rejected, and the partition goes back to offset 0. The heartbeat is fine, so it looks healthy; side effects repeat every round.
- 15 minutes: drop
max.poll.recordsto 1 or raisemax.poll.interval.ms, and redeploy. - Root fix: size
max.poll.recordsby the formula with 2× headroom; if a single record is inherently slow, hand it off to a separate work queue and commit after handing off; processing must be idempotent because the loop already duplicated work.
Exercise 2: Choose how to cut deploy lag
20 pods, 60 partitions, the default assignor, about 40 seconds per pod restart. The AI suggests raising session.timeout.ms to 5 minutes. Evaluate it and propose steps in order.
Solution to Exercise 2
Raising the session timeout alone doesn't help: dynamic members still send LeaveGroup on close and trigger an immediate rebalance; and when a pod really dies, nobody reads its partitions for 5 minutes.
In order:
- Broker and client both on 4.x:
group.protocol=consumer, no barrier, each pod affects only its own share. - Still on classic:
CooperativeStickyAssignor, across two rolling deploys. - Static membership:
group.instance.id=${POD_NAME}(a StatefulSet for stable names),session.timeout.msaround 60 s. - Check
max.poll.interval.msis short enough that rebalances don't wait on long batches.
Summary
- Eager rebalancing stops the whole group; cooperative moves only what must move.
- The Java client still defaults to range: declare cooperative or use KIP-848.
- Static membership avoids rebalances on restart, at the cost of slower failure detection.
- A batch longer than
max.poll.interval.msbecomes a reprocessing loop. - Poison pills: seek past and send to a DLT, knowing the ordering cost.
Read more: Part 1: Inside the producer.
Practice interview questions on this topic
- How do Kafka consumer groups work, and when does a rebalance happen?
- How do heartbeats, session.timeout.ms and max.poll.interval.ms differ, and how do you handle records that take minutes?
- How do eager, cooperative and KIP-848 rebalances differ, and how do you rolling-deploy 50 pods without a lag spike?
- How do you commit Kafka offsets correctly: is auto-commit safe, and when does auto.offset.reset apply?
- One record always makes the consumer throw: what happens, and how do you design retries and a DLQ that keep ordering?
Comments
Community rules