Consumer groups and rebalancing

Mid-level Always asked 7 min

On this page

The question

How do consumer groups let you scale consumption in Kafka?

30-second answer

Consumers that share a group ID split the partitions of the topics they subscribe to: each partition is assigned to exactly one consumer of the group, and a consumer can hold several. To read faster, you add consumers, up to the number of partitions. Different groups are independent: each gets every record and keeps its own offsets. So partitions scale one service, and groups let many services read the same data.

Understand it

Partitions and consumers in one group

Explore

2 consumers share 4 partitions, 2 at a time. Add consumers, up to 4, and the group reads faster.

4
2
View as text

Partitions of the topic orders on the left, consumers of the group billing on the right, with a line from each partition to the consumer that reads it. Consumers with no partition are drawn dashed and marked idle.

1 consumer reads 4 partitions, 1 at a time. Add consumers, up to 4, and the group reads faster.

2 consumers share 4 partitions, 2 at a time. Add consumers, up to 4, and the group reads faster.

4 consumers for 4 partitions: one each, the most parallelism this topic allows the group. More consumers would sit idle.

6 consumers, 4 partitions: a partition goes to one consumer of the group, so 2 get nothing. Idle consumers wait as standbys for the next rebalance.

2 consumers share 5 partitions, 2 at a time. Add consumers, up to 5, and the group reads faster. The first consumer reads three partitions and the second two.

Partitions of the topic orders on the left, consumers of the group billing on the right, with a line from each partition to the consumer that reads it. Consumers with no partition are drawn dashed and marked idle.

1 consumer reads 4 partitions, 1 at a time. Add consumers, up to 4, and the group reads faster.

2 consumers share 4 partitions, 2 at a time. Add consumers, up to 4, and the group reads faster.

4 consumers for 4 partitions: one each, the most parallelism this topic allows the group. More consumers would sit idle.

6 consumers, 4 partitions: a partition goes to one consumer of the group, so 2 get nothing. Idle consumers wait as standbys for the next rebalance.

2 consumers share 5 partitions, 2 at a time. Add consumers, up to 5, and the group reads faster. The first consumer reads three partitions and the second two.

Takeaway: A consumer group splits the partitions of a topic, and each partition goes to exactly one of its consumers. So the partition count caps the parallelism of a group: consumers beyond it sit idle.

A consumer joins, then another one fails

Step by step

Two consumers of the group billing split four partitions. Each sends heartbeats to the group coordinator, a broker, and commits its offsets as it goes.

Step 1 of 6
View as text

The group coordinator on top. Four partitions on the left, each with its lag, and up to three consumers on the right, with a line from each partition to the consumer reading it.

Two consumers of the group billing split four partitions. Each sends heartbeats to the group coordinator, a broker, and commits its offsets as it goes.

A third instance starts with the same group ID and asks to join. The coordinator tells every member to rejoin: a rebalance.

With the classic eager protocol, every consumer commits and gives up all its partitions first. Until the new assignment arrives, nobody reads, and lag grows everywhere.

One member, the group leader, computes the new assignment, and the coordinator hands it out. Each consumer resumes from the last committed offset of its partitions.

C2 hangs and stops sending heartbeats. The coordinator waits session.timeout.ms, 45 seconds by default, before declaring it dead. Meanwhile nobody reads P2.

Another rebalance gives P2 to C3, which starts at the last offset C2 committed. Whatever C2 processed after that commit is processed again: at-least-once.

The group coordinator on top. Four partitions on the left, each with its lag, and up to three consumers on the right, with a line from each partition to the consumer reading it.

Two consumers of the group billing split four partitions. Each sends heartbeats to the group coordinator, a broker, and commits its offsets as it goes.

A third instance starts with the same group ID and asks to join. The coordinator tells every member to rejoin: a rebalance.

With the classic eager protocol, every consumer commits and gives up all its partitions first. Until the new assignment arrives, nobody reads, and lag grows everywhere.

One member, the group leader, computes the new assignment, and the coordinator hands it out. Each consumer resumes from the last committed offset of its partitions.

C2 hangs and stops sending heartbeats. The coordinator waits session.timeout.ms, 45 seconds by default, before declaring it dead. Meanwhile nobody reads P2.

Another rebalance gives P2 to C3, which starts at the last offset C2 committed. Whatever C2 processed after that commit is processed again: at-least-once.

Takeaway: Any change in membership makes the group rebalance: partitions are taken back and handed out again. Each new owner resumes at the last committed offset, so a rebalance pauses reading and can repeat some records.

Eager and cooperative rebalancingIn an eager rebalance, every consumer gives up every partition, nobody reads, and then all partitions are assigned again. In a cooperative rebalance, consumers give up only the partitions that move to another consumer, keep reading the rest, and a second round assigns the moved partitions.CooperativeEager: the classic defaultEvery consumerrevokes allNobody readsAll partitionsassigned againRevoke onlymoving partitionsThe rest keepbeing readSecond roundassigns them
Eager and cooperative rebalancingIn an eager rebalance, every consumer gives up every partition, nobody reads, and then all partitions are assigned again. In a cooperative rebalance, consumers give up only the partitions that move to another consumer, keep reading the rest, and a second round assigns the moved partitions.CooperativeEager: the classic defaultEvery consumerrevokes allNobody readsAll partitionsassigned againRevoke onlymoving partitionsThe rest keepbeing readSecond roundassigns them
Eager and cooperative rebalancing

In code

@KafkaListener(topics = "orders", groupId = "billing", concurrency = "3")
void on(ConsumerRecord<String, OrderEvent> r) {
    // Each of the 3 consumers gets some partitions; with 3 instances
    // of the service, the group has 9 consumers, so orders needs 9+ partitions
    billing.handle(r.value());
}
Three consumers in one instance, all in the group billing
Map<TopicPartition, OffsetAndMetadata> processed = new HashMap<>();

consumer.subscribe(List.of("orders"), new ConsumerRebalanceListener() {
    @Override
    public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
        consumer.commitSync(processed);                  // the next owner starts right after our work
        processed.clear();
    }

    @Override
    public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
        log.info("now reading {}", partitions);
    }
});
Commit what was processed before giving a partition away
spring.kafka.consumer.properties.partition.assignment.strategy=\
  org.apache.kafka.clients.consumer.CooperativeStickyAssignor
# A restart with the same instance ID within session.timeout.ms causes no rebalance
spring.kafka.consumer.properties.group.instance.id=${HOSTNAME}
spring.kafka.consumer.properties.session.timeout.ms=45000
# Kafka 4.0+: the new protocol assigns on the broker, incrementally; it replaces the assignment strategy
# spring.kafka.consumer.properties.group.protocol=consumer
Fewer, cheaper rebalances: cooperative assignment and static membership
// 500 records at about 1 s each: 500 s between polls, past the 300 s limit. Kicked out, rebalance, repeat
 Wrong props.put("max.poll.records", 500);

// 100 records: about 100 s per loop, well under the limit
 Right props.put("max.poll.records", 100);
A poll that takes longer than max.poll.interval.ms gets the consumer thrown out
The steps of a classic rebalanceA new consumer, C3, sends JoinGroup to the coordinator. The coordinator answers the heartbeats of C1 and C2 with rebalance in progress, and they rejoin. The coordinator picks C1 as group leader and sends it the member list. C1 computes the assignment and sends it in SyncGroup, and the coordinator gives each member its partitions.C2C1, leaderCoordinatorC3, newJoinGroupheartbeat: rebalance in progressheartbeat: rebalance in progressJoinGroupJoinGroupyou lead: members C1, C2, C3SyncGroup with the assignmentyour partitionsyour partitions
The steps of a classic rebalanceA new consumer, C3, sends JoinGroup to the coordinator. The coordinator answers the heartbeats of C1 and C2 with rebalance in progress, and they rejoin. The coordinator picks C1 as group leader and sends it the member list. C1 computes the assignment and sends it in SyncGroup, and the coordinator gives each member its partitions.C2C1, leaderCoordinatorC3, newJoinGroupheartbeat: rebalance in progressheartbeat: rebalance in progressJoinGroupJoinGroupyou lead: members C1, C2, C3SyncGroup with the assignmentyour partitionsyour partitions
The steps of a classic rebalance

Solve it

The group rebalances every few minutes, and lag only grows

The invoices service consumes orders with 3 instances in one group. For each record it calls a tax API that takes about a second. The logs show “commit cannot be completed since the group has already rebalanced”, followed by a rebalance, again and again, and lag keeps rising. Explain the loop and stop it.

  1. Measure one poll loop. poll returns up to max.poll.records, 500 by default. At a second per record, the consumer calls poll again only after about 500 seconds.
  2. Find the limit it breaks. If poll is not called within max.poll.interval.ms, 300 seconds by default, the consumer leaves the group, even though its heartbeats continue. Its partitions move, its commit fails, and the new owner redoes the batch.
  3. Fit the loop under the limit. Lower max.poll.records to 100, so a loop takes about 100 seconds. Raising the interval instead also works, but it delays detecting a consumer that is really stuck.
  4. Make each record cheaper. Call the tax API with a timeout, cache its answers, or process records of different keys in parallel and commit only what is done. The fix for lag is throughput, not settings.
  5. Check. The rebalance rate drops to zero, the consumer metric for time between polls stays well under 300 s, and lag falls.
spring.kafka.consumer.max-poll-records=100
# Default, kept on purpose: a consumer that does not poll for 5 minutes is stuck
spring.kafka.consumer.properties.max.poll.interval.ms=300000
# The tax client gives up after 2 s, so one slow answer cannot stall the loop
tax.client.read-timeout=2s
Smaller batches per poll, and a timeout on the slow call

How to answer

  • The partition count is the ceiling on parallelism inside one group.
  • Each partition is read by one consumer, which keeps per-partition order.
  • A rebalance redistributes partitions whenever members or partitions change.
  • One group per service; one consumer per thread.

Common mistakes

  • Saying that adding consumers always speeds things up. Past the partition count, the extra ones sit idle.
  • Sharing one KafkaConsumer instance between threads. It is not thread-safe.

Follow-up questions

What happens when a group has more consumers than the topic has partitions?

The extra consumers get no partition and sit idle. Kafka never gives one partition to two consumers of the same group, because that would break ordering and offset tracking. Idle consumers are not useless: if a consumer fails, the rebalance can hand its partitions to one of them at once. To use more consumers, add partitions, accepting that keys move to new partitions.

  • Parallelism is the smaller of consumers and partitions.
  • Plan partitions for the peak consumer count you expect.
  • Kafka 4 share groups allow several consumers per partition, without per-partition order.

See it in the infographic: Partitions and consumers in one group

What is a rebalance, and what triggers it?

A rebalance reassigns the partitions of a group among its current members. It is triggered when a consumer joins, leaves, misses heartbeats for session.timeout.ms, or does not poll within max.poll.interval.ms, and when the subscribed topics gain partitions. With the classic eager protocol, everyone stops reading until it ends. Each new owner resumes from the committed offset, so uncommitted work is redone.

  • Cooperative rebalancing moves only the partitions that change owner.
  • Static membership, with group.instance.id, avoids rebalances on a quick restart.
  • Kafka 4.0 made a new protocol, where the broker assigns incrementally, generally available.

See it in the infographic: A consumer joins, then another one fails

What is consumer lag, and what do you do when it keeps growing?

Lag is, per partition, the log end offset minus the committed offset of the group: records produced but not yet processed. Growing lag means the group processes slower than producers write. First find out where: one hot partition, or all of them. Then speed up processing, add consumers up to the partition count, add partitions, or batch the expensive work. Alert on lag, or on its growth, per group.

  • Lag on one partition only points at a hot key or a stuck consumer.
  • Frequent rebalances show up as lag spikes.
  • Retention keeps running, so very high lag can turn into lost records.

See it in the infographic: A consumer joins, then another one fails See it in the infographic: Partitions and consumers in one group

Why does a consumer get thrown out of its group when processing is slow?

Two timers watch a consumer. Heartbeats, sent from a background thread, prove the process is alive within session.timeout.ms, 45 seconds by default. Separately, the application must call poll again within max.poll.interval.ms, 5 minutes by default, to prove it is making progress. If one batch takes longer, the consumer leaves the group, its partitions move, and its commit fails. Lower max.poll.records or speed up the work.

  • The defaults are 500 records per poll and 5 minutes between polls.
  • Raising the interval delays detecting a stuck consumer.
  • A CommitFailedException after a slow batch is the typical sign.

See it in the infographic: A consumer joins, then another one fails

What partition assignment strategies does the Java consumer offer?

Range gives each consumer a contiguous range of each topic's partitions, and is the first default. RoundRobin deals partitions one by one across consumers. Sticky balances while keeping as many assignments as possible. CooperativeSticky does the same, but rebalances incrementally: consumers keep the partitions that do not move and keep reading them. In Kafka 4 the new consumer protocol moves assignment to the broker.

  • The default list is Range, then CooperativeSticky, so a group can upgrade with rolling restarts.
  • Sticky assignment reduces rework, since partitions rarely change owner.
  • All members must agree on a common strategy.

See it in the infographic: Partitions and consumers in one group

Two services must both receive every order. How do you set that up?

Give them different group IDs, such as billing and shipping. Each group gets all records of the topic and tracks its own offsets, so neither slows or affects the other. Instances of the same service share their group ID, so they split the work instead of duplicating it.

What does concurrency do on a Spring @KafkaListener?

It starts that many consumers, each on its own thread, in the same group. With concurrency 3 and two instances of the service, the group has 6 consumers, so the topic needs at least 6 partitions to keep them all busy.

Check yourself

1. A topic has 4 partitions, and its consumer group has 6 consumers. How many consumers are idle?
Show answers
  • 2: Correct. Each partition goes to one consumer, so 2 of the 6 get none.
  • 0: Incorrect. Kafka does not split a partition between consumers of one group.
  • 4: Incorrect. Only the consumers beyond the partition count are idle.
2. Which of these trigger a rebalance of a consumer group?Choose 2
Show answers
  • A new consumer joins the group: Correct. A change in membership means partitions must be redistributed.
  • A consumer misses heartbeats for longer than session.timeout.ms: Correct. The coordinator declares it dead and redistributes its partitions.
  • A new producer starts writing to the topic: Incorrect. Producers are not members of consumer groups.
3. Partition 2 has a log end offset of 1,500, and the group's committed offset for it is 1,200. What is the lag?
Show answers
  • 300: Correct. Lag is the log end offset minus the committed offset.
  • 1,200: Incorrect. That is how far the group got, not what remains.
  • 1,500: Incorrect. That counts records already processed too.