Scrivio Interview library
Kafka13 August 202613 min read

How Kafka Rebalances a Consumer Group, Step by Step

Try it yourself

Consumer group: who reads which partition

Change the number of partitions and consumers, and see who owns what, who is idle, and where ordering holds.

Read this example as text

Who reads which partition

  1. 3 partitions, 2 consumers. C0 reads P0, P1; C1 reads P2.
  2. 4 partitions, 2 consumers. C0 reads P0, P1; C1 reads P2, P3.
  3. 3 partitions, 3 consumers. C0 reads P0; C1 reads P1; C2 reads P2.
  4. 6 partitions, 4 consumers. C0 reads P0, P1; C1 reads P2, P3; C2 reads P4; C3 reads P5.
  5. 2 partitions, 4 consumers. C0 reads P0; C1 reads P1; C2 is idle; C3 is idle.

A partition has exactly one reader in the group. A consumer beyond the number of partitions is idle.

Six records with 3 partitions and 2 consumers

  1. Record A1. Key A goes to P0, read by C0.
  2. Record B1. Key B goes to P1, read by C0.
  3. Record A2. Key A goes to P0, read by C0.
  4. Record C1. Key C goes to P2, read by C1.
  5. Record B2. Key B goes to P1, read by C0.
  6. Record A3. Key A goes to P0, read by C0.

A1, A2 and A3 sit in one partition and are read in that order. Nothing orders a record in one partition against a record in another.

What this example leaves out
  • One topic, and Kafka's range assignor, the first in the default list. Other assignors spread partitions differently.
  • A, B and C stand for key hashes 0, 1 and 2. The real client hashes the key bytes; the rule shown, same key to the same partition, is the same.
  • A rebalance is shown as instant. In a real group, consumers stop briefly while partitions move.

Adding a Consumer Stops the Whole Group#

The orders topic has six partitions. Consumer A owns 0 through 2, consumer B owns 3 through 5, and both are keeping pace with the write rate. Ahead of a traffic spike you start a third instance, consumer C, expecting each consumer to settle onto two partitions and the group to get a little more headroom. Within a second or two, consumer lag starts climbing on all six partitions. Not just the two that C is about to take: all six, including the ones A was reading and nobody proposed to move.

Nothing crashed. No broker went offline, no consumer threw an exception, and the logs on A and B say Revoking previously assigned partitions followed by a wait. Then, a few hundred milliseconds or a few minutes later, everything resumes with a fresh assignment and the lag drains. The system is behaving exactly as designed. That is the puzzle worth understanding: why does adding a healthy consumer stop the healthy ones?

The answer starts with a design decision that looks wasteful until you see what it buys. Under Kafka's original eager rebalancing protocol, a rebalance is not a negotiation between the consumers that are affected and the ones that are not. When a rebalance starts, every consumer in the group drops all of its assigned partitions, and onPartitionsRevoked fires before the consumer sends its JoinGroup request to the coordinator1. A and B give up their partitions because that is the only state the protocol allows them to be in while a new assignment is computed. Consumption resumes only after the new assignment comes back and onPartitionsAssigned runs.

With three consumers and six partitions, the pause is short enough that you might only notice it as a lag blip on a dashboard. The cost scales with the group, though: every eager rebalance is a stop-the-world pause for the entire group, and at high partition counts those pauses turn into real latency spikes1. Multiply it by a rolling restart across three pods, where each pod stopping and each pod starting is its own trigger, and a routine deploy becomes several minutes of a group that is mostly not reading anything.

Two things have to be true for that behavior to make sense. Something has to decide who is in the group, and something has to decide which consumer gets which partition. In Kafka those are not the same component. Following the orders group through a rebalance answers both: who tracks membership, who computes the assignment, and what the group is doing during each observable phase between the trigger and the first record fetched under the new assignment.

The Coordinator Tracks Membership; the Leader Computes the Assignment#

Two parties run a rebalance, and neither does the other's job. Kafka designates one broker per consumer group as that group's coordinator, chosen by the group's name, and every offset commit and offset fetch from that group's members goes to it2. The second party is not a broker at all. One ordinary consumer in the group, elected leader when the group forms, computes the partition assignment.

The coordinator's job list is short: it knows which members are currently alive and responding, it holds the group's committed offsets, and it fences off stale members with a generation number that increments on every rebalance. That is the whole picture it maintains. It has no opinion about which member should own partition 4.

Assignment lives on the client because assignment strategy is application logic. Range, round-robin, sticky, rack-aware, and custom assignors all plug into the consumer, and Kafka Streams goes further, placing stateful tasks near their existing local state. A broker would have to run all of that on behalf of every group it coordinates. Instead the consumer client carries it, and adapts on its own as the partitions it fetches migrate within the cluster3.

This is what the six-partition group from the opening ran into. When C joined, the coordinator saw it immediately: three members, one of them holding nothing. What the coordinator could not do was hand C two of the six partitions, because it holds no map of who should own what and has no assignor to build one. Only the leader can produce that map, and the leader produces it as a complete assignment for the whole group rather than as a diff. Under the default eager protocol, the existing assignment therefore has to be torn down before the new one can exist: the stop-the-world constraint that cooperative rebalancing escapes1. More on that protocol shortly.

Tearing down and rebuilding an assignment is not a single instant, though, and the group's throughput does not resume the moment the leader finishes computing. C's arrival sets four distinct moves in motion, in this order: revoke, join, sync, and re-fetch.

Walking the Rebalance: Revoke, JoinGroup, SyncGroup, Re-fetch#

"Attempting to rejoin the group" is the line most people see first, and by itself it tells you nothing useful: it opens a rebalance that finishes in 200 milliseconds and it opens one that eats forty seconds. Four phases run between that line and the next record your application handles, and each one leaves a different fingerprint. With a log file open, you can place your group in one of them:

  • Revoke. Revoke previously assigned partitions orders-0, orders-1. Stalls for as long as your onPartitionsRevoked callback takes: offset commits, cache flushes, a slow database write.
  • JoinGroup. (Re-)joining group with no follow-up. Stalls until the last member sends its JoinGroup request; the slowest consumer sets the pace for everyone.
  • SyncGroup. Successfully joined group with generation 42, then silence. Stalls while the leader computes the assignment and the coordinator distributes it.
  • Re-fetch. Setting offset for partition orders-3 to the committed offset FetchPosition{offset=91744}. Stalls on the OffsetFetch round trip, once per newly assigned partition.

Consumers A, B and C from the opening scenario move through all four together, as the diagram below shows. A finishes its in-flight batch and runs onPartitionsRevoked; C does the same. Each commits the maximum offset it has consumed on the partitions it is surrendering2, because whichever member picks those partitions up will resume from that committed position and reprocess anything past it3. Only when the callback returns does a member send JoinGroup.

From there the group is idle by design. The coordinator holds every JoinGroup request open until the last member arrives, elects one of them leader, and hands it the full membership list. The leader computes the assignment and returns it in SyncGroup, and the coordinator slices that plan into per-member responses. Still nobody has data. Each member then issues an OffsetFetch for its new partitions and sets its position before poll can return a single record.

Your observability hook into all of this is ConsumerRebalanceListener, which fires whenever the set of assigned partitions changes. It applies only when Kafka auto-manages group membership: partitions you handed the consumer through assign() are never reassigned, and the callback never runs4. Saving offsets inside onPartitionsRevoked guarantees they are persisted on every assignment change, and it is the usual place to flush caches of intermediate results before the partitions move away4.

B's forty seconds sat almost entirely in JoinGroup. B was midway through a slow batch, and a member only joins the rebalance from inside its poll loop, so A and C waited with completed JoinGroups while the coordinator waited for B. Revoke, assignment and offset fetch cost well under a second between them.

Diagram as text
sequenceDiagram
    participant Coord as Group Coordinator
    participant A as Consumer A
    participant B as Consumer B
    participant C as Consumer C

    rect rgb(255, 235, 235)
        Note over A,C: Silent window, zero throughput
        Note over A,C: onPartitionsRevoked, commit offsets
        A->>Coord: JoinGroup
        B->>Coord: JoinGroup
        C->>Coord: JoinGroup
        Coord-->>A: JoinGroup response, leader
        A->>A: Compute assignment
        A->>Coord: SyncGroup with plan
        Coord-->>A: Assigned partitions
        Coord-->>B: Assigned partitions
        Coord-->>C: Assigned partitions
        B->>Coord: OffsetFetch
        Coord-->>B: Committed offset
    end
    Note over A,C: Resume from committed offset

Liveness or Slowness: Which Timeout Actually Fired#

Java
Properties props = new Properties();
props.put("bootstrap.servers", "kafka:9092");
props.put("group.id", "order-enrichment");
props.put("max.poll.records", "500");
props.put("session.timeout.ms", "45000");
props.put("max.poll.interval.ms", "300000");
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
consumer.subscribe(List.of("orders"));
while (running) {
for (ConsumerRecord<String, String> record : consumer.poll(Duration.ofSeconds(1))) {
enrich(record); // 20 ms normally; 90 s when the vendor API stalls
}
}
}

Nothing here is wrong. Most of the time a batch of 500 finishes in ten seconds. Then the vendor API degrades, a handful of records in the batch take 90 seconds each, the loop needs six minutes to drain one batch, and the coordinator kicks that member out of the group even though the JVM is healthy, the socket is open, and heartbeats never stopped.

They never stopped, because heartbeats do not travel through your handler. Kafka sends them independently of the processing loop, which is what makes the two failure modes separable: the session timeout asks whether the member still exists, and the poll interval asks whether the member is still making progress. In the logs both arrive as the same line about the member being removed from the group and the offset commit failing, so the log alone will not tell you which clock ran out.

ConfigQuestion it answersWhat resets the clockTypical cause when it firesFix
session.timeout.msIs this member still there?An incoming heartbeatProcess death, GC pause, network partition, host evictionFix the pause or the network; raise only if the pauses are expected
max.poll.interval.msIs this member still making progress?The next call to poll()A slow handler: blocking I/O, an unbounded retry, an oversized batchShrink max.poll.records, move slow work off the poll thread, or raise the interval

The two rows prescribe opposite fixes. Raising the session timeout for a slow handler buys nothing, and shrinking the batch for a GC pause buys nothing either.

The version caveat matters before you tune anything. Under the next-generation consumer rebalance protocol, enabled on the server by default since Apache Kafka 4.0, the heartbeat interval and session timeout are controlled by the broker through group.consumer.heartbeat.interval.ms and group.consumer.session.timeout.ms rather than by your client properties5. Setting them in application code on such a cluster changes nothing; the poll interval remains yours.

Whichever clock fired, the consequence lands on the group. The coordinator revokes that member's partitions, and every consumer whose assignment changes runs its ConsumerRebalanceListener callbacks4. How much of the group stops consuming while that happens depends on which rebalance protocol is in use.

Eager vs. Cooperative: Stopping the World, or Just the Moving Parts#

C joins a group where A holds p0, p1, p2 and B holds p3, p4, p5. Both protocols end in the same place: A on p0 and p1, B on p3 and p4, C on p2 and p5. What happens in between is not the same.

PartitionUnder eagerUnder cooperative
p0Revoked from A, reassigned to AHeld by A throughout
p1Revoked from A, reassigned to AHeld by A throughout
p2Revoked from A, assigned to CRevoked from A, assigned to C
p3Revoked from B, reassigned to BHeld by B throughout
p4Revoked from B, reassigned to BHeld by B throughout
p5Revoked from B, assigned to CRevoked from B, assigned to C

Four of those six rows change nothing, and eager still walks them through revocation, because onPartitionsRevoked fires on every member before its JoinGroup request goes out1. That closes the loop opened earlier: the coordinator tracks membership, the leader computes assignment, and the leader has no channel for saying "keep what you already have." Destroying the old assignment is how the protocol guarantees no partition has two owners while the new one is being built.

Incremental cooperative rebalancing, shipped as an alternative in Kafka 2.3 through 2.51, reaches the same final state in two passes. In the first pass, each member reports the partitions it currently owns in its JoinGroup request, and the leader compares that picture against the target assignment. The SyncGroup response it sends back is the target with the contested partitions withheld: A is told it owns p0 and p1, B is told it owns p3 and p4, and nobody is told they own p2 or p5 yet. A and B notice partitions missing from their new assignment, revoke exactly those two, and immediately request another rebalance. In the second pass, p2 and p5 are unowned, so the leader can hand them to C safely.

The extra round trip is real. A cooperative rebalance takes longer end to end than an eager one, and it costs a second JoinGroup and SyncGroup exchange with the coordinator. What it buys is that p0, p1, p3 and p4 never stop being polled, so the pause is scoped to the two partitions that change hands rather than to the group. That scoping matters most exactly where eager hurts most: the cost of a stop-the-world pause scales with the group's partition count1, so a group of a hundred consumers spanning a thousand partitions freezes all thousand to admit one new member. And the event that most often admits new members is not a broker failure. It is a rolling restart.

Diagram as text
gantt
    title Consumer C joins: partition downtime by protocol
    dateFormat X
    axisFormat %S
    todayMarker off

    section Eager
    All six revoked and idle :crit, 0, 6
    p0 p1 resume on A        :active, 6, 14
    p3 p4 resume on B        :active, 6, 14
    p2 p5 start on C         :active, 6, 14

    section Cooperative
    p0 p1 keep fetching on A :active, 0, 14
    p3 p4 keep fetching on B :active, 0, 14
    p2 p5 still fetching     :active, 0, 4
    p2 p5 revoked and idle   :crit, 4, 8
    p2 p5 resume on C        :active, 8, 14

Making Rolling Restarts Cheaper#

Watch consumer lag for the orders group during a rolling restart and the shape gives the protocol away: three pods, three bounces, and a staircase of lag that climbs while the group re-forms, then drains once assignments settle. Each pod actually costs two rebalances, one when it leaves and one when it rejoins. Under the eager protocol every one of those six events stops all three consumers, because a rebalance revokes every partition from every member before anyone sends JoinGroup1. Two of the pods were healthy the whole time.

Three changes flatten that graph, listed in rough order of payoff:

  • Switch the assignor. Move the group to the cooperative-incremental protocol, available since Kafka 2.31. What it buys you: a bounce pauses only the partitions that are actually moving, so the two untouched consumers keep fetching through the whole restart.
  • Pin a stable identity. Give each pod a fixed group.instance.id so the coordinator treats a returning member as the same member. What it buys you: a pod that comes back inside its session timeout reclaims its old partitions with no rebalance at all, which removes the event from the restart path instead of making it cheaper.
  • Bound the handler. Keep worst-case processing per poll comfortably under max.poll.interval.ms, using smaller max.poll.records or offloading slow work. What it buys you: the poll loop stops being the thing that triggers rebalances during ordinary traffic, so the timeouts above only fire when a consumer is genuinely gone.

Kafka's own direction of travel goes further than either of the first two fixes. The next generation of the rebalance protocol, KIP-848, is generally available from Apache Kafka 4.0 and enabled on the broker by default, gated by the group.version feature flag5. It drops the global synchronization barrier entirely and moves assignment computation server-side, which is what makes it interesting for groups large enough that the client-side leader is itself a bottleneck5.

A reasonable next step is to run the same rolling restart twice, once with your current settings and once with cooperative assignment plus static instance IDs, and keep the lag graph open both times. The gap between the two runs is the cost your deploy currently pays.

And the puzzle from the beginning has a plain answer: the two healthy consumers stopped because the partition assignment belongs to the group protocol rather than to the broker, and every member has to agree on a new generation before any of them can fetch again. The assignor, the member identity, and the poll loop are the three places you can change that.

Sources

  1. Incremental Cooperative Rebalancing in Kafka • TheAnigtheanig.dev
  2. Distribution | Apache Kafkakafka.apache.org
  3. KafkaConsumer (kafka 2.7.0 API)kafka.apache.org
  4. ConsumerRebalanceListener (kafka 2.5.0 API)kafka.apache.org
  5. Consumer Rebalance Protocol | Apache Kafkakafka.apache.org

Keep reading

Kafka12 August 2026

How Kafka Handles Backpressure: Durable Log, Pull Consumers, Blocking Producers

send() is asynchronous in a specific and limited sense: it hands a record to an in-memory buffer and returns. When that buffer has no room, it does not return. A payments service...

14 min readRead the article
Kafka6 August 2026

Debugging Kafka in Production: Four Failure Modes and Their Parameters

The orders-events topic has 12 partitions, consumed by six instances of a payments-enrichment service. Roughly every five minutes, the group logs a rebalance, all 12 partitions...

15 min readRead the article
Kafka22 May 2026

Five Kafka Design Patterns Every Backend Engineer Should Know

Kafka is a distributed commit log. Producers append records to topics; consumers read those records independently, each maintaining their own offset into the log. Unlike a...

18 min readRead the article