Kafka Consumer Rebalancing
A rebalance is the process in which a Kafka consumer group redistributes partitions among its members. It happens whenever the group changes: a consumer joins, leaves, crashes, or the subscribed topics gain partitions.
Rebalances keep a group working when instances come and go, but a badly tuned group can rebalance constantly and stop making progress. This tutorial explains the triggers, the difference between eager and cooperative rebalancing, the broker-driven protocol from KIP-848, and how to avoid losing or duplicating work during a rebalance.
1. What Is Consumer Rebalancing?
Rebalancing is the reassignment of partitions to consumers in a group. During a rebalance some partitions are revoked from their current owner and assigned to another member. Each partition still has exactly one owner when the rebalance completes.
2. What Triggers a Rebalance?
- A new consumer joins the group (for example a scale-out).
- A consumer leaves cleanly by calling
close(). - A consumer stops sending heartbeats for longer than the session timeout (45 seconds by default), for example after a crash.
- A classic consumer does not call
poll()withinmax.poll.interval.ms(5 minutes by default) and leaves the group proactively. - Partitions are added to a subscribed topic, or a new topic matches a regex subscription.
3. How Rebalancing Works
3.1 Eager rebalancing
With an eager assignor such as RangeAssignor alone, every member gives up all its partitions at the start of a rebalance, then receives a new assignment. No one consumes during the rebalance: a "stop-the-world" pause.
3.2 Cooperative (incremental) rebalancing
With CooperativeStickyAssignor, members keep the partitions that do not move. Only partitions that must change owner are revoked, and a second, quick rebalance assigns them to their new owner.
3.3 The KIP-848 consumer protocol
With group.protocol=consumer (GA in Kafka 4.0), the broker-side group coordinator computes assignments and sends each member only its own changes through heartbeats. There is no group-wide synchronisation barrier, and a slow member no longer delays the others. Client-side settings such as partition.assignment.strategy, session.timeout.ms and heartbeat.interval.ms are not used with this protocol; the broker's group.consumer.* settings apply instead.
3.4 Static membership
For classic groups, setting a unique group.instance.id per instance makes a member static. When it restarts within session.timeout.ms, it rejoins with the same identity and gets its old partitions back without a rebalance. This suits rolling restarts on Kubernetes.
4. Key Settings
| Property | Default (Kafka 4.4) | Effect on rebalancing |
|---|---|---|
group.protocol | classic | consumer enables KIP-848 incremental rebalancing |
partition.assignment.strategy | RangeAssignor, CooperativeStickyAssignor | Classic only; the first strategy supported by all members is used |
session.timeout.ms | 45000 | Classic: time without heartbeats before a member is removed |
heartbeat.interval.ms | 3000 | Classic: heartbeat frequency, about one third of the session timeout or less |
max.poll.interval.ms | 300000 | Maximum time between poll() calls before the member leaves |
max.poll.records | 500 | Fewer records per poll shortens processing time per loop |
group.instance.id | null | Enables static membership |
5. Java Example: Committing Safely on Revoke
When partitions are revoked, a consumer should commit what it has processed, otherwise the next owner reprocesses those records. This consumer tracks processed offsets and commits them in onPartitionsRevoked. It uses the cooperative assignor, so only moving partitions are revoked.
package com.javabytechie.kafka;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.CooperativeStickyAssignor;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
public class ShipmentConsumer {
public static void main(String[] args) throws InterruptedException {
new Thread(() -> run("C1")).start();
Thread.sleep(10_000); // C2 joins later and triggers a rebalance
new Thread(() -> run("C2")).start();
}
static void run(String name) {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "shipping");
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
props.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG,
CooperativeStickyAssignor.class.getName());
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
Map<TopicPartition, OffsetAndMetadata> processed = new HashMap<>();
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
consumer.subscribe(List.of("shipments"), new ConsumerRebalanceListener() {
@Override
public void onPartitionsRevoked(Collection<TopicPartition> parts) {
if (parts.isEmpty()) {
return;
}
Map<TopicPartition, OffsetAndMetadata> toCommit = new HashMap<>();
for (TopicPartition tp : parts) {
OffsetAndMetadata offset = processed.remove(tp);
if (offset != null) {
toCommit.put(tp, offset);
}
}
consumer.commitSync(toCommit);
System.out.println(name + " revoked " + parts + ", committed before handing over");
}
@Override
public void onPartitionsAssigned(Collection<TopicPartition> parts) {
if (!parts.isEmpty()) { // cooperative rebalances also report empty sets
System.out.println(name + " assigned " + parts);
}
}
});
while (true) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(500))) {
// process the shipment here
processed.put(new TopicPartition(r.topic(), r.partition()),
new OffsetAndMetadata(r.offset() + 1));
}
consumer.commitAsync(processed, null);
}
}
}
}
Output (Kafka 4.4, shipments topic with 4 partitions):
C1 assigned [shipments-0, shipments-1, shipments-2, shipments-3]
C1 revoked [shipments-2, shipments-3], committed before handing over
C2 assigned [shipments-2, shipments-3]
C1 first owns all four partitions. When C2 joins, C1 gives up only partitions 2 and 3 and keeps reading 0 and 1; there is no "revoked all" step as with an eager assignor. With cooperative rebalancing, the listener is also called with empty collections, which is why the code skips them.
5.1 Spring Boot
Spring for Apache Kafka commits pending offsets before partitions are revoked when it manages commits (the default AckMode.BATCH). Static membership and the assignor are ordinary consumer properties:
spring:
kafka:
consumer:
group-id: shipping
properties:
group.instance.id: ${HOSTNAME}
partition.assignment.strategy: org.apache.kafka.clients.consumer.CooperativeStickyAssignor
6. Common Mistakes
- Long processing in the poll loop: a batch that takes longer than
max.poll.interval.mscauses a rebalance, and the uncommitted batch is processed again by another member. - Switching directly from eager to cooperative: changing a live group from
RangeAssignortoCooperativeStickyAssignorneeds two rolling restarts (first list both, then remove the eager one). - Not committing on revoke with manual commits, which causes duplicates after every rebalance.
- Using the same
group.instance.idon two instances: the second one fences the first.
7. Best Practices
- Keep each poll loop short: lower
max.poll.recordsor hand records to a worker pool and commit only completed offsets. - Prefer cooperative or KIP-848 rebalancing for large groups and frequent deployments.
- Use static membership with a stable identity (for example a StatefulSet pod name) to make restarts invisible.
- Make processing idempotent, because a rebalance after a crash always replays records since the last commit.
- Watch rebalance metrics such as
rebalance-rate-per-hourandfailed-rebalance-totalon the consumer.
8. Conclusion
Rebalancing keeps a consumer group balanced as members change, but each rebalance can pause work and replay uncommitted records. Use cooperative or KIP-848 rebalancing, static membership, short poll loops and commits on revoke to keep rebalances rare and cheap. See Kafka Consumer Groups for group basics and Kafka Offset Management for commit strategies.
9. References
Kafka Consumer Rebalancing Interview Questions and Answers
Common interview questions on Kafka Consumer Rebalancing, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. Name four events that trigger a consumer group rebalance.
Answer: A consumer joining the group, a consumer leaving with close(), a consumer missing heartbeats for longer than the session timeout, and a consumer exceeding max.poll.interval.ms between polls. Adding partitions to a subscribed topic also triggers one.
Intermediate questions
Q. What is the difference between session.timeout.ms and max.poll.interval.ms?
Answer: They detect two different failures. session.timeout.ms (45 seconds, classic protocol) covers a dead or disconnected process: heartbeats come from a background thread, and if none arrive in time, the coordinator removes the member. max.poll.interval.ms (5 minutes) covers a live process whose poll loop is stuck or too slow: if poll() is not called in time, the client itself leaves the group. A long garbage-collection pause can trigger the first; slow record processing triggers the second.
Q. How does static membership reduce rebalances?
Answer: A static member has a fixed group.instance.id. When it restarts, the coordinator keeps its partitions reserved until session.timeout.ms expires. If the instance returns in time it gets the same partitions back with no rebalance. Static members also do not send a leave-group request on shutdown.
Tricky and scenario questions
Q. How do you migrate a running group from RangeAssignor to CooperativeStickyAssignor?
Answer: Do two rolling restarts. First deploy all members with both assignors, CooperativeStickyAssignor and RangeAssignor, so the group keeps using the eager assignor that everyone supports. Then deploy again with only the cooperative assignor. Changing directly would make old and new members disagree on the protocol.
Q. Why should offsets be committed in onPartitionsRevoked rather than onPartitionsAssigned?
Answer: onPartitionsRevoked runs on the old owner before the partition moves, so it is the last chance to record progress. Committing there lets the new owner start at the right offset. By the time onPartitionsAssigned runs, the revoked partitions belong to someone else and committing for them fails.