Sub topic 2
Consumer groups and partition assignment
This chapter assumes you know what a topic, a partition and an offset are, and that you can start a Spring Boot application with spring-kafka on the classpath. It covers how Kafka splits a topic's partitions among the consumers that read it. That split decides how much parallelism you get, what ordering you can rely on, and what happens when instances start or stop.
What a consumer group is
A consumer group is a set of consumers that share one group.id and cooperate to read a set of topics. Kafka gives each partition of a subscribed topic to exactly one consumer in the group at a time. Together, the members of a group read every record of the topic once.
Three rules follow from this:
- A partition is read by at most one consumer per group. Records in a partition are therefore processed in order within that group.
- A consumer can own several partitions.
- Different groups are independent. Each group tracks its own position in every partition, so two groups can read the same topic without affecting each other.
The first rule is why adding consumers does not break per-key ordering. Records with the same key go to the same partition, and that partition has one reader in the group.
The diagram shows one topic with three partitions read by two groups.
Groups in Spring Boot
In Spring, the group is set by spring.kafka.consumer.group-id or by the groupId attribute on @KafkaListener. The attribute overrides the property for that listener.
spring:
kafka:
bootstrap-servers: localhost:9092
consumer:
group-id: order-service
auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
properties:
spring.json.trusted.packages: com.example.orders
spring.json.value.default.type: com.example.orders.OrderEventTwo listeners on the same topic with different group IDs each receive every record. This is the publish/subscribe pattern. Two listeners with the same group ID share the records. This is the work-queue pattern.
package com.example.orders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
@Component
public class OrderGroupsDemo {
private static final Logger log = LoggerFactory.getLogger(OrderGroupsDemo.class);
@KafkaListener(topics = "orders", groupId = "order-service")
public void process(OrderEvent event,
@Header(KafkaHeaders.RECEIVED_PARTITION) int partition) {
log.info("order-service got {} from partition {}", event.orderId(), partition);
}
@KafkaListener(topics = "orders", groupId = "order-audit")
public void audit(OrderEvent event,
@Header(KafkaHeaders.RECEIVED_PARTITION) int partition) {
log.info("order-audit got {} from partition {}", event.orderId(), partition);
}
}Every order is logged twice, once per group. If you start two copies of the application, each order-service log line appears in only one copy, and order-audit is split the same way.
The @Header annotation gives you the partition of each record. Use it while learning to confirm which instance owns which partition.
How assignment happens
Assignment is negotiated at runtime. Each group has a group coordinator, which is one of the brokers. The flow is:
- A consumer starts and sends a join request to the coordinator.
- The coordinator collects the members, chooses one as group leader and sends it the member list.
- The leader runs the partition assignor, which computes who gets which partition, and returns the plan.
- The coordinator distributes the plan. Each consumer begins fetching from its partitions.
This repeats whenever the membership or the subscription changes. Each repetition is a rebalance.
Where a consumer resumes
When a consumer receives a partition, it needs a starting offset. It asks the coordinator for the group's committed offset for that partition. If the group has no committed offset yet, auto-offset-reset decides:
| Value | Behavior for a group with no committed offset |
|---|---|
| `earliest` | Start at the oldest retained record |
| `latest` | Start after the newest record (the Kafka default) |
| `none` | Fail with an exception |
This setting applies only when no offset exists. A new group ID has none, so changing group-id on a running service makes it start over from earliest or skip the backlog with latest. How offsets are committed is the subject of a later chapter.
Rebalances
Rebalances are the main operational cost of consumer groups. They are triggered by:
- a consumer joining, for example when you scale out or restart;
- a consumer leaving cleanly on shutdown;
- a consumer being declared dead;
- partitions being added to a subscribed topic;
- a change to a pattern subscription's matching topics.
How a consumer is declared dead
Two timers matter, and they are often confused.
- A background heartbeat thread contacts the coordinator every
heartbeat.interval.ms(default 3 seconds). If no heartbeat arrives withinsession.timeout.ms(default 45 seconds in recent clients), the coordinator removes the consumer. - The thread that runs your listener must call
poll()again withinmax.poll.interval.ms(default 5 minutes). Spring does this between batches of records. If your listener takes longer than that to process one batch, the consumer leaves the group even though heartbeats are fine.
A slow listener is the usual cause of unexpected rebalances. The symptoms are repeated logs about the consumer leaving the group and partitions being revoked, plus records processed twice.
You can tune these in YAML under properties:
spring:
kafka:
consumer:
max-poll-records: 100
properties:
max.poll.interval.ms: 300000
session.timeout.ms: 45000
heartbeat.interval.ms: 3000Assignment strategies
The assignor decides how partitions are spread. You set it with partition.assignment.strategy.
| Assignor | Behavior | Rebalance style |
|---|---|---|
| `RangeAssignor` | Splits each topic's partitions into contiguous ranges per consumer | Eager |
| `RoundRobinAssignor` | Deals partitions out one by one across all topics | Eager |
| `StickyAssignor` | Balanced like round robin, but keeps existing assignments where possible | Eager |
| `CooperativeStickyAssignor` | Same as sticky, but moves only the partitions that must move | Cooperative |
With an eager rebalance, every consumer gives up all its partitions, waits for the new plan, and then resumes. Processing pauses across the whole group. With a cooperative rebalance, consumers keep partitions that are not changing owner and release only the ones being moved. For a service with many partitions and frequent deploys, this removes most of the pause.
Recent Kafka clients default to a list containing RangeAssignor and CooperativeStickyAssignor, which still uses the eager protocol until you drop RangeAssignor from the list. To get cooperative behavior, set the list explicitly:
spring:
kafka:
consumer:
properties:
partition.assignment.strategy: org.apache.kafka.clients.consumer.CooperativeStickyAssignorChanging the strategy on a live group needs a rolling upgrade in two steps. First deploy with both the old and new assignors listed, then deploy again with only the new one. Switching in a single step makes the members disagree about a common protocol and fail to join.
Static membership
By default, a restarted instance joins as a new member and triggers a rebalance. If you set a unique group.instance.id per instance, the coordinator treats a restart within session.timeout.ms as the same member returning, and gives it back its partitions without a rebalance.
spring:
kafka:
consumer:
properties:
group.instance.id: ${HOSTNAME}The ID must be unique across live instances. Two members with the same instance ID cause the older one to be fenced and fail. Static membership works best with a longer session.timeout.ms, which also delays detection of a truly dead instance.
Parallelism limits and ordering
The partition count caps the useful number of consumers in a group. With three partitions, a fourth consumer in the same group sits idle until another member leaves. To process more in parallel, you need more partitions.
Adding partitions has a cost. The default partitioner maps a key to a partition by hashing it modulo the partition count, so changing the count changes where existing keys go. Records for one order written before and after the change can land on different partitions and be processed out of order. Choose the partition count with future growth in mind.
Inspecting a group
The kafka-consumer-groups tool shows assignments, committed offsets and lag.
kafka-consumer-groups.sh --bootstrap-server localhost:9092 \
--describe --group order-serviceThe output lists each partition with its current offset, log-end offset, lag and the owning consumer. Use it to confirm that all partitions are owned and that lag is not growing on one partition only. Uneven lag usually points to a hot key.
Common errors
- Reusing a group ID by accident. Copying a listener and forgetting to change
groupIdmakes the two listeners split records instead of each receiving all of them. - Expecting a second group to share work. A different group ID means a full second copy of the stream.
- More consumers than partitions. The extra consumers receive nothing.
- Rebalance loops. Slow processing plus a short
max.poll.interval.msevicts consumers repeatedly. - Surprise replays after renaming the group. A new group has no offsets, so
auto-offset-resetapplies.
Exercise
A topic has 4 partitions. The order-service group has 6 running instances, each with one listener thread. How many instances receive records, and what happens if one active instance crashes?
Show answer
Four instances each own one partition, and the other two are idle. When an active instance crashes, the coordinator removes it after the session timeout and triggers a rebalance. One of the idle instances takes over the orphaned partition, so processing continues and the group still has four active consumers.
Exercise
You deploy a new version of a service with 12 partitions and eager assignors. Each deploy pauses all processing for several seconds. Name two changes that reduce this, and say what one of them requires.
Show answer
Switch to the CooperativeStickyAssignor so only the moving partitions pause, and set a unique group.instance.id per instance so quick restarts do not trigger a rebalance. Changing the assignor on a live group requires a two-step rolling deploy, first listing both the old and new assignors and then only the new one.