Kafka Consumer Groups
A Kafka consumer group is a set of consumers that work together to read a topic. Kafka gives each partition to exactly one member of the group, so the members split the work between them, and the group as a whole remembers how far it has read.
Consumer groups are how Kafka scales reading and how several applications read the same data independently. This tutorial explains how a group is formed, how partitions are assigned, what the group coordinator does, and what changed with the new consumer group protocol in Kafka 4.0.
1. What Is a Consumer Group?
Every consumer that sets the same group.id belongs to the same group. Inside a group, each partition of a subscribed topic is assigned to one consumer at a time. Different groups are completely independent: each group gets every record of the topic and keeps its own committed offsets.
2. Why Consumer Groups Matter
- Horizontal scaling: to read faster, start more instances with the same
group.id, up to one consumer per partition. - Fault tolerance: if an instance stops, its partitions are moved to the remaining members.
- Independent applications: a billing service and an analytics service use different groups and each read the full stream at their own pace.
- Ordering per key: because one partition has one reader in the group, records with the same key are processed in order.
3. How a Consumer Group Works
3.1 The group coordinator
One broker acts as the group coordinator for each group. It is the leader of the __consumer_offsets partition that the group's ID hashes to. Consumers send it heartbeats, join and leave through it, and commit offsets to it.
3.2 Partition assignment
When membership changes, partitions are reassigned. This is called a rebalance. Kafka 4.x supports two protocols:
Classic protocol (group.protocol=classic) | Consumer protocol (group.protocol=consumer, KIP-848) | |
|---|---|---|
| Default for clients | Yes (Kafka 4.4) | Opt-in; GA since Kafka 4.0 |
| Who computes the assignment | The group leader (a consumer) using partition.assignment.strategy | The broker, using group.remote.assignor (uniform or range) |
| Rebalance style | Group-wide sync; eager or cooperative | Incremental, per member, no global pause |
| Liveness | session.timeout.ms (45 s) and heartbeat.interval.ms set on the client | Configured on the broker (group.consumer.session.timeout.ms, group.consumer.heartbeat.interval.ms) |
The details of rebalancing are covered in Kafka Consumer Rebalancing.
3.3 More consumers than partitions
A group can have more members than partitions, but the extra members get no partitions and stay idle. They are useful only as hot spares.
4. Java Example: Two Consumers in One Group
This demo starts two consumers with the same group.id in one JVM and prints their assignments and records. In production each consumer usually runs in its own service instance.
package com.javabytechie.kafka;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
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.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
public class BillingGroupDemo {
public static void main(String[] args) {
new Thread(() -> runConsumer("B1")).start();
new Thread(() -> runConsumer("B2")).start();
}
static void runConsumer(String name) {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "billing");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
consumer.subscribe(List.of("orders"), new ConsumerRebalanceListener() {
@Override
public void onPartitionsAssigned(Collection<TopicPartition> parts) {
System.out.println(name + " assigned " + parts);
}
@Override
public void onPartitionsRevoked(Collection<TopicPartition> parts) {
if (!parts.isEmpty()) {
System.out.println(name + " revoked " + parts);
}
}
});
while (true) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(500))) {
System.out.printf("%s read %s from partition %d%n", name, r.key(), r.partition());
}
}
}
}
}
Output (Kafka 4.4, orders topic with 4 partitions; records were produced after both consumers joined):
B1 assigned [orders-0, orders-1]
B2 assigned [orders-2, orders-3]
B2 read ORD-101 from partition 2
B1 read ORD-102 from partition 0
B2 read ORD-103 from partition 2
B1 read ORD-104 from partition 1
B2 read ORD-105 from partition 3
B1 read ORD-106 from partition 1
The default classic assignor (RangeAssignor) gave each consumer two partitions. Each record went to the partition chosen by its key's hash, so it was read only by the member that owns that partition. The order of lines between B1 and B2 can differ from run to run because the two consumers run in parallel; within one partition the order is always kept. Stop the demo with Ctrl+C.
4.1 Inspecting a group from the command line
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing
The output lists each partition with its CURRENT-OFFSET, LOG-END-OFFSET, LAG and the member that owns it. Lag is the number of records the group has not yet read.
4.2 Spring Boot
In Spring for Apache Kafka, groupId and concurrency on @KafkaListener create several consumers in the same group inside one application:
package com.javabytechie.kafka;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class InvoiceListener {
@KafkaListener(topics = "orders", groupId = "billing", concurrency = "2")
public void onOrder(String order) {
System.out.println("Billing " + order);
}
}
5. Real-World Scenarios
- Scaling a slow consumer: a fraud-check service with 12 partitions runs 6 pods in one group; adding pods spreads partitions further.
- Fan-out to several teams: the
orderstopic is read bybilling,shippingandanalyticsgroups without affecting one another. - Replaying data: a new group with
auto.offset.reset=earliestreads a topic from the oldest retained record, for example to build a search index.
6. Common Mistakes
- Running more consumers than partitions and expecting more throughput; the extra consumers are idle.
- Reusing a
group.idacross unrelated applications: they steal partitions from each other and each misses part of the data. - Slow processing inside
poll()loops: exceedingmax.poll.interval.ms(5 minutes) makes the classic consumer leave the group and triggers a rebalance. - Too few partitions: the partition count is the upper limit for parallelism in a group, so plan it for future load.
7. Best Practices
- Name groups after the application, for example
billing-service, and keep one group per logical application. - Monitor consumer lag per partition with
kafka-consumer-groups.shor metrics, and alert on growth. - Use static membership (
group.instance.id) for classic consumers on Kubernetes to avoid rebalances on pod restarts. - Evaluate
group.protocol=consumeron Kafka 4.x clusters for faster, incremental rebalances in large groups.
8. Conclusion
A consumer group lets several consumers share the partitions of a topic, with one reader per partition and one set of offsets per group. Groups give Kafka horizontal scaling and fault tolerance, and different groups let many applications read the same data independently. Continue with Kafka Offset Management to learn how groups track their progress.
9. References
Kafka Consumer Groups Interview Questions and Answers
Common interview questions on Kafka Consumer Groups, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What happens if two applications use the same group.id by mistake?
Answer: Kafka treats them as one group and splits the partitions between them. Each application then receives only part of the data, and each commits offsets that the other relies on. Every independent application must have its own group.id.
Q. What is the maximum number of active consumers in a group for a topic with 8 partitions?
Answer: Eight. Each partition is assigned to at most one consumer in the group, so a ninth consumer receives no partitions and stays idle until another member leaves.
Intermediate questions
Q. What is the group coordinator and how is it chosen?
Answer: It is the broker that manages one consumer group: membership, heartbeats, rebalances and offset commits. Kafka hashes the group.id to a partition of the internal __consumer_offsets topic, and the leader of that partition is the coordinator. If that broker fails, the new partition leader becomes the coordinator.
Q. What is the difference between the classic and the KIP-848 consumer group protocol?
Answer: In the classic protocol, one consumer (the group leader) computes the assignment and every rebalance is a group-wide synchronisation. In the consumer protocol, enabled with group.protocol=consumer and generally available since Kafka 4.0, the broker computes the assignment and changes it incrementally per member, so other members keep consuming. Session timeouts move from client to broker configuration.
Tricky and scenario questions
Q. Can a single consumer read from several consumer groups at once?
Answer: No. A KafkaConsumer instance belongs to exactly one group, set by group.id. To read the same topic for two purposes, create two consumer instances with different group IDs, or process both concerns in one consumer.
Q. Consumer lag is growing on two partitions only. What would you check?
Answer: Uneven lag usually points to the data or to one member, not to the whole group. Check for hot keys that send most records to those partitions, slow processing for specific record types, and which member owns those partitions in kafka-consumer-groups.sh --describe. Adding consumers does not help a hot partition; repartitioning the key or processing faster does.