00:00

Kafka Consumer Rebalancing

Last updated:

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.

Definition: A consumer rebalance moves partition ownership between group members after membership or subscription changes, coordinated by the group coordinator broker.

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() within max.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.

Eager and cooperative rebalancing when consumer C2 joinsBefore the rebalance, C1 owns partitions 0 to 3. In an eager rebalance, C1 gives up all four partitions, then C1 gets 0 and 1 and C2 gets 2 and 3, and nothing is consumed in between. In a cooperative rebalance, C1 keeps partitions 0 and 1 the whole time and only gives up 2 and 3, which are then assigned to C2. Eager C1: P0 P1 P2 P3C2 joins C1: (none) C2: (none)all revoked, nobody consumes C1: P0 P1 C2: P2 P3new assignment Cooperative C1: P0 P1 P2 P3C2 joins C1: P0 P1 C2: (none)only P2, P3 revoked C1: P0 P1 C2: P2 P3second, short rebalance In the cooperative case C1 keeps reading P0 and P1 during the whole rebalance.
Cooperative rebalancing revokes only the partitions that move, so most of the group keeps consuming.

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

PropertyDefault (Kafka 4.4)Effect on rebalancing
group.protocolclassicconsumer enables KIP-848 incremental rebalancing
partition.assignment.strategyRangeAssignor, CooperativeStickyAssignorClassic only; the first strategy supported by all members is used
session.timeout.ms45000Classic: time without heartbeats before a member is removed
heartbeat.interval.ms3000Classic: heartbeat frequency, about one third of the session timeout or less
max.poll.interval.ms300000Maximum time between poll() calls before the member leaves
max.poll.records500Fewer records per poll shortens processing time per loop
group.instance.idnullEnables 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.

ShipmentConsumer.java
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):

Output
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:

application.yml
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.ms causes a rebalance, and the uncommitted batch is processed again by another member.
  • Switching directly from eager to cooperative: changing a live group from RangeAssignor to CooperativeStickyAssignor needs 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.id on two instances: the second one fences the first.

7. Best Practices

  • Keep each poll loop short: lower max.poll.records or 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-hour and failed-rebalance-total on 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