Lesson 04 / 10 · Performance

Kafka Rebalancing: Eager vs Cooperative, Tested

Kafka consumer rebalancing measured on a real cluster: eager vs cooperative-sticky vs KIP-848, max.poll.interval.ms, static membership and the common mistakes.

2-3 hours advanced Not completed

On this page · 14 sections
  1. Why rebalances cause incidents
  2. What happens during a rebalance
  3. Worked example: eager vs cooperative on a real cluster
  4. The three timeouts that remove consumers
  5. Worked example: a slow batch that never finishes
  6. Static membership: restarts without rebalances
  7. Common mistakes
  8. Monitoring rebalances
  9. A sane starting configuration (Java consumer)
  10. Hands-on exercise 1: watch the protocols side by side
  11. Hands-on exercise 2: restart a consumer without a rebalance
  12. Hands-on exercise 3: break and fix a slow consumer
  13. Key takeaways
  14. Quiz

Why rebalances cause incidents

A rebalance is the consumer group deciding again who owns which partition. It happens whenever a member joins, leaves, misses heartbeats, or the topic gains partitions. On its own a rebalance takes a few seconds. The incidents come from rebalances that feed each other:

  1. One consumer spends longer than max.poll.interval.ms on a batch, so the client leaves the group.
  2. The group rebalances. With the old eager protocol, every consumer drops all its partitions while that happens.
  3. The kicked consumer rejoins and gets a batch it already processed but never committed, so it’s just as slow again.
  4. It gets kicked again, and every round adds lag across the whole group.

You can end up with a group that is busy all night and makes almost no progress. The rest of this lesson shows each piece of that loop on a real cluster, then how to break it.

What happens during a rebalance

With the classic protocol (every Kafka version, and still the default in most clients):

  1. Trigger. The group coordinator (a broker) notices a change: a JoinGroup from a new member, a LeaveGroup, a missed session timeout, or new partitions.
  2. Join. Every member must send a JoinGroup request. Members only notice on their next heartbeat or poll(), so the slowest member decides how long this phase takes.
  3. Assign. The coordinator picks one member as group leader. The leader runs the assignor (range, round-robin, sticky, cooperative-sticky) on the client side and sends the result back.
  4. Sync. Each member receives its partitions and resumes from the group’s last committed offsets.

The broker logs each round. These lines came from the run below and are what you’d grep for:

Preparing to rebalance group g-eager2 in state PreparingRebalance with old generation 1
  (reason: Adding new member rdkafka-5f3d8699-... with group instance id null; client reason: not provided).
Stabilized group g-eager2 generation 2 with 3 members.

The generation number goes up by one per rebalance. If you see it climbing every minute, you have a storm.

Worked example: eager vs cooperative on a real cluster

Setup: Kafka 4.4 in KRaft mode, a 6-partition orders topic, and Python consumers using confluent-kafka 2.16. Each consumer prints every partition it is given or loses (rebalance_demo.py):

import os, signal, sys, time
from confluent_kafka import Consumer

name, group, strategy = sys.argv[1], sys.argv[2], sys.argv[3]
t0 = float(os.environ.get("START", time.time()))
slow = float(os.environ.get(f"SLOW_{name}", 0))

def log(event, partitions):
    parts = sorted(p.partition for p in partitions)
    print(f"{time.time() - t0:6.2f}s {name} {event:<8} {parts}", flush=True)

conf = {"bootstrap.servers": "localhost:9092", "group.id": group,
        "auto.offset.reset": "earliest"}
if strategy == "consumer":
    conf["group.protocol"] = "consumer"  # KIP-848: the broker computes assignments
else:
    conf["partition.assignment.strategy"] = strategy

signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))  # so close() runs on kill
consumer = Consumer(conf)
consumer.subscribe(["orders"],
                   on_assign=lambda c, ps: log("assigned", ps),
                   on_revoke=lambda c, ps: log("revoked", ps))
try:
    while True:
        consumer.poll(0.5)
        time.sleep(slow)  # stand-in for slow processing: no poll() while we work
finally:
    consumer.close()

The scenario (run_scenario.sh): start c1 and c2, add c3 at 15 s, stop c3 at 30 s. To make it realistic, c2 is slow: after each poll it “works” for 10 s (SLOW_c2=10), the way a consumer making API calls per batch would.

Eager (range assignor)

  6.13s c1 assigned [3, 4, 5]
 10.57s c2 assigned [0, 1, 2]
 15.13s c1 revoked  [3, 4, 5]      <- c3 joins; c1 drops everything at once
 21.07s c1 assigned [4, 5]         <- ...and waits 6 s for slow c2 to rejoin
 21.07s c2 revoked  [0, 1, 2]
 21.07s c2 assigned [0, 1]
 21.07s c3 assigned [2, 3]
 30.06s c3 revoked  [2, 3]         <- c3 stops; another full stop-the-world round
 30.08s c1 revoked  [4, 5]
 31.57s c1 assigned [3, 4, 5]
 31.57s c2 revoked  [0, 1]
 31.57s c2 assigned [0, 1, 2]

When c3 joined, c1 gave up all three of its partitions at 15.13 s and got work back only at 21.07 s. For those 6 seconds partitions 3, 4 and 5 had no consumer at all, purely because c2 was in the middle of a slow batch and didn’t rejoin until its next poll(). In production that wait is bounded by max.poll.interval.ms, which defaults to 5 minutes.

Cooperative sticky

Same scenario, partition.assignment.strategy=cooperative-sticky:

  6.11s c1 assigned [1, 3, 5]
 10.55s c2 assigned [0, 2, 4]
 18.13s c1 revoked  [1]            <- only the partition that has to move
 21.05s c2 revoked  [0]
 21.13s c3 assigned [0, 1]         <- second round hands them to c3
 30.05s c3 revoked  [0, 1]
 31.07s c1 assigned [0]
 31.55s c2 assigned [1]

(Empty assigned [] callbacks between rounds are removed for readability.) c1 kept partitions 3 and 5 the whole time and c2 kept 2 and 4. Only partitions 0 and 1 paused, and only until the second round. The slow member still delays the hand-over of its own partition 0, but it no longer stalls everybody else.

That’s the whole idea of incremental cooperative rebalancing: two short rounds, where round one revokes only the partitions that need to move and round two assigns them.

The new protocol (KIP-848, group.protocol=consumer)

Kafka 4.0 made the new consumer group protocol generally available. The broker computes assignments and pushes them on heartbeats; there is no group-wide join/sync barrier at all. Same scenario, no slow consumer:

  0.10s c2 assigned [0, 1, 2, 3, 4, 5]
  5.11s c2 revoked  [3, 4, 5]
 10.11s c1 assigned [3, 4, 5]
 15.11s c1 revoked  [5]
 15.11s c2 revoked  [2]
 20.11s c3 assigned [2, 5]
 30.06s c3 revoked  [2, 5]
 30.12s c1 assigned [2]
 30.12s c2 assigned [5]

(Empty assigned [] callbacks removed again.) Only moved partitions pause. Notice the 5-second gaps: a revoked partition is handed to its new owner on that owner’s next heartbeat, and the broker default group.consumer.heartbeat.interval.ms is 5000. So the pause per moved partition is around one heartbeat interval, and it never depends on how slow some other member is.

Which should you use? For new Java or librdkafka consumers against Kafka 4.x brokers, try group.protocol=consumer first. If you’re on older brokers or a client that doesn’t support it yet, use cooperative-sticky. There’s no good reason to run eager assignors on a new service in 2026.

In the Java client, switching an existing group from eager to cooperative takes two rolling restarts: first list both assignors everywhere (CooperativeStickyAssignor first, then RangeAssignor), then do a second roll that removes RangeAssignor. Doing it in one step can leave the group with members that can’t agree on a protocol.

The three timeouts that remove consumers

SettingDefaultWhat gets you kicked outWho checks it
session.timeout.ms45 sNo heartbeat for this long (process dead, network cut, very long GC)Broker
heartbeat.interval.ms3 sNot a kick-out rule; keep it at a third of the session timeout or lessClient
max.poll.interval.ms5 minToo long between poll() calls, even though heartbeats are fineClient (it leaves the group itself)

Heartbeats run on a background thread in both the Java client and librdkafka. That’s why a consumer stuck in a 10-minute batch keeps heartbeating happily and is still removed: max.poll.interval.ms is the “is the application actually making progress” check.

Worked example: a slow batch that never finishes

Here is the failure from the top of the lesson, reproduced. slow_worker.py sets max.poll.interval.ms=10000 and each batch of 100 records takes 12 s to process. In naive mode it processes inside the poll loop:

  3.1s assigned [0, 1, 2, 3, 4, 5]
  3.2s got 100 records
%4|...|MAXPOLL|rdkafka#consumer-1| Application maximum poll interval (10000ms) exceeded by 402ms
     (adjust max.poll.interval.ms for long-running message processing): leaving group
 15.2s commit failed: KafkaError{code=_ASSIGNMENT_LOST, ... "Group partition assignment lost"}
 15.2s revoked [0, 1, 2, 3, 4, 5]
 18.2s assigned [0, 1, 2, 3, 4, 5]
 18.2s got 100 records                 <- the same 100 records again
 30.2s commit failed: KafkaError{code=_ASSIGNMENT_LOST, ...}

The work was done, the commit was rejected because the consumer no longer owned the partitions, and the next owner (here, the same process) got the same records. This loops forever, and every downstream side effect happens again on each lap. Raising the timeout would hide it until batches got a bit slower.

Two fixes, best first:

  1. Make each batch smaller. In Java, lower max.poll.records (default 500) until the worst-case batch finishes well inside max.poll.interval.ms. librdkafka has no max.poll.records; use consume(num_messages=N) with a small N.
  2. Process off the poll thread and pause. Hand the batch to a worker, pause() the assigned partitions, and keep calling poll()/consume() so the client stays in the group without fetching more. Commit and resume() when the worker finishes:
worker = None
while running:
    if worker is not None and not worker.is_alive():   # batch finished
        c.commit(asynchronous=False)
        c.resume(c.assignment())
        worker = None
    msgs = [m for m in c.consume(num_messages=100, timeout=0.5) if not m.error()]
    if msgs:
        c.pause(c.assignment())          # keep polling, fetch nothing new
        worker = threading.Thread(target=process, args=(msgs,))
        worker.start()

Same 12-second batches in pause mode:

  3.1s assigned [0, 1, 2, 3, 4, 5]
  3.2s got 100 records
 15.2s batch done, committed, resumed
 15.2s got 100 records
 27.2s batch done, committed, resumed

No eviction, no duplicates. The catch: if a rebalance revokes partitions while the worker is still running, you must wait for it (or abandon its results) inside the on_revoke callback before the partitions move, otherwise two consumers process the same records.

Static membership: restarts without rebalances

Rolling deploys are the most common rebalance trigger. Each pod stop is a leave, each start is a join: two rebalances per pod. With static membership you give each consumer a stable group.instance.id. A static member doesn’t send LeaveGroup on shutdown, and if it comes back with the same ID within session.timeout.ms, the coordinator hands it its old partitions without a rebalance.

The ID must be stable and unique per running consumer. A Kubernetes StatefulSet gives you that for free with the pod name (orders-consumer-0, -1, …):

env:
  - name: GROUP_INSTANCE_ID
    valueFrom:
      fieldRef:
        fieldPath: metadata.name   # orders-consumer-0, orders-consumer-1, ...
consumer = Consumer({
    "bootstrap.servers": "kafka:9092",
    "group.id": "orders",
    "group.instance.id": os.environ["GROUP_INSTANCE_ID"],
    "session.timeout.ms": 60000,  # must cover a normal pod restart
})

The trade-off: when a static member really dies, its partitions sit unconsumed for the full session timeout before anyone takes them over. With a 60 s timeout that’s up to 60 s of lag on those partitions. Pick the timeout from how long your pods actually take to restart, not from a blog post.

Common mistakes

  • A random or per-start instance ID. group.instance.id=${HOSTNAME}-${RANDOM} is a new identity on every restart, so you get the rebalances back plus a stale member that holds partitions until its session expires. Deployment pod names change on every rollout too; use a StatefulSet.
  • Two consumers with the same group.instance.id. The coordinator fences the older one. If you scale a Deployment with a hard-coded ID, replicas keep kicking each other out.
  • Calling poll() in a liveness probe. It fetches records on a code path that doesn’t process them, and with auto-commit those offsets get committed: silent data loss. Have the poll loop record a timestamp and let the probe check that it is recent.
  • Running the work in a thread with a timeout and moving on. A Python thread can’t be killed; after the “timeout” it keeps running while you commit past its records. Use the pause/resume pattern above, or make the work itself time out (HTTP client timeouts, DB statement timeouts).
  • Fixing every eviction by raising max.poll.interval.ms to 30 minutes. A consumer that is truly stuck now holds its partitions for 30 minutes. Shrink the batch first.
  • Adding partitions to “spread load” during an incident. Partition count changes trigger a rebalance, and existing keys move to different partitions (see Kafka partitions explained).
  • Mixing assignors during a migration in one restart instead of the two-step roll-out described above.

Monitoring rebalances

Java consumers expose these under kafka.consumer:type=consumer-coordinator-metrics,client-id=...:

MetricAlert idea
rebalance-rate-per-hourMore than a few per hour outside deploys
rebalance-latency-maxSeconds, not minutes; minutes means a slow member is holding up the group
failed-rebalance-rate-per-hourAnything above zero is worth a look
last-rebalance-seconds-agoHandy on a dashboard next to deploy markers

librdkafka reports the same events through its statistics callback (rebalance_cnt, rebalance_age in the cgrp section). On the broker, the “Preparing to rebalance group … (reason: …)” log line tells you why: a new member, a member leaving, or a poll or session timeout. Rebalances that line up with lag spikes in lag monitoring are the ones to fix first.

A sane starting configuration (Java consumer)

On Kafka 4.x brokers and clients, let the broker assign incrementally:

group.protocol=consumer
group.instance.id=${POD_NAME}     # only with a StatefulSet (stable, unique per pod)
max.poll.interval.ms=300000
max.poll.records=200              # slowest realistic batch well under max.poll.interval.ms

With this protocol, session and heartbeat timing live on the broker (group.consumer.session.timeout.ms, default 45 s; group.consumer.heartbeat.interval.ms, default 5 s). Leave session.timeout.ms, heartbeat.interval.ms and partition.assignment.strategy out of the client config: the Java client rejects them when group.protocol=consumer.

On older brokers or clients, stay on the classic protocol with the cooperative assignor:

partition.assignment.strategy=org.apache.kafka.clients.consumer.CooperativeStickyAssignor
group.instance.id=${POD_NAME}
session.timeout.ms=45000
heartbeat.interval.ms=3000
max.poll.interval.ms=300000
max.poll.records=200

Hands-on exercise 1: watch the protocols side by side

  1. Create a 6-partition orders topic, pip install confluent-kafka, and copy rebalance_demo.py and run_scenario.sh from the course code.
  2. Run ./run_scenario.sh ex-eager range, then ./run_scenario.sh ex-coop cooperative-sticky, then (Kafka 4.x) ./run_scenario.sh ex-new consumer.
  3. Repeat the first two with SLOW_c2=10 in front.
  4. For each run, write down how many partition-seconds had no owner while c3 joined.
What you should see

Eager: all partitions are revoked on every membership change, and with a slow c2 the group stalls until c2 polls again. Cooperative: only one or two partitions move per change and the others keep flowing. New protocol: only moved partitions pause, for roughly one broker heartbeat interval (5 s by default). Exact partition numbers will differ from the lesson; the shape won’t.

Hands-on exercise 2: restart a consumer without a rebalance

  1. Using the events topic from Lesson 1 (3 partitions), start two console consumers with fixed instance IDs, each in its own terminal:
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic events --group static-demo \
  --consumer-property group.instance.id=worker-1
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic events --group static-demo \
  --consumer-property group.instance.id=worker-2
  1. Check who owns what:
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group static-demo --members --verbose
  1. Stop worker-1 with Ctrl+C, describe the group again, then start worker-1 again within 45 seconds (the default session.timeout.ms) and describe once more.
  2. Repeat steps 1–3 with a new group name and without group.instance.id, and compare.
What you should see

With static membership, the member list still shows worker-1 right after you stop it, and after the restart it owns exactly the same partitions as before; only its member ID suffix changes. The broker log records it as a replacement, not a rebalance:

Static member with groupInstanceId=worker-1 and unknown member id joins group static-demo in Stable state.
Replacing previously mapped member worker-1-ee04... with this groupInstanceId.

Without group.instance.id, stopping a consumer makes it leave the group, the other consumer takes all partitions, and the restart triggers a second rebalance.

Hands-on exercise 3: break and fix a slow consumer

Run python slow_worker.py naive and then python slow_worker.py pause against a topic with at least 300 records. Then change naive mode so it survives without touching max.poll.interval.ms.

Hint

Lower num_messages in consume() so that one batch takes less than 10 s (each record here costs 0.12 s, so 50 records is about 6 s). That’s the librdkafka equivalent of lowering max.poll.records.

Key takeaways

  • A rebalance under eager assignment stops every consumer, and its length is set by the slowest member’s next poll(), up to max.poll.interval.ms.
  • Cooperative-sticky moves only the partitions that must move, in two short rounds. The new group.protocol=consumer (Kafka 4.0+) goes further: no group-wide barrier, about one heartbeat of pause per moved partition.
  • Exceeding max.poll.interval.ms means the batch’s commit fails and the records are redelivered. Shrink batches or use pause/resume; raising the timeout is the last resort.
  • Static membership turns rolling restarts into no-ops, but only with IDs that are stable and unique per consumer, and at the cost of slower failover for a dead member.
  • Watch rebalance rate and latency next to lag; the broker’s “Preparing to rebalance” reason tells you which fix applies.

Quiz

  1. With an eager assignor, one consumer is 4 minutes into a slow batch when a new consumer joins. What happens to the other consumers’ partitions in the meantime?
  2. A consumer’s heartbeats are fine but it keeps getting removed from the group. Which setting is it tripping, and what’s the first fix to try?
  3. Why is group.instance.id=${HOSTNAME}-${RANDOM} worse than not setting it at all?
Show answers
  1. They have already revoked everything and sit idle until the slow consumer finishes its batch and calls poll() (or is evicted after max.poll.interval.ms). The whole group waits for the slowest member.
  2. max.poll.interval.ms: the gap between poll() calls is too long. Make batches smaller (max.poll.records, or num_messages in librdkafka) before raising the timeout.
  3. Every restart is a new static member, so you still get a rebalance, and the old static member isn’t removed on shutdown (static members don’t send LeaveGroup). Its partitions sit unconsumed until its session times out.

Done with this lesson?

Marking it complete updates the sidebar, the course page and the Continue button.