00:00

Kafka Consumer Groups

Last updated:

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.

Definition: A consumer group is a named set of consumers that divide a topic's partitions between them and share one set of 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

Two consumer groups reading one topicThe orders topic has four partitions. In the billing group, consumer B1 reads partitions 0 and 1 and consumer B2 reads partitions 2 and 3. The analytics group has one consumer that reads all four partitions. Each group commits its own offsets to the __consumer_offsets topic through its group coordinator broker. topic: orders partition 0 partition 1 partition 2 partition 3 group: billing consumer B1P0, P1 consumer B2P2, P3 group: analytics consumer A1P0, P1, P2, P3 group coordinator brokermembership, assignment, __consumer_offsets
Inside a group, each partition has one reader. Each group gets the full topic and keeps its own offsets.

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 clientsYes (Kafka 4.4)Opt-in; GA since Kafka 4.0
Who computes the assignmentThe group leader (a consumer) using partition.assignment.strategyThe broker, using group.remote.assignor (uniform or range)
Rebalance styleGroup-wide sync; eager or cooperativeIncremental, per member, no global pause
Livenesssession.timeout.ms (45 s) and heartbeat.interval.ms set on the clientConfigured 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.

BillingGroupDemo.java
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):

Output
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

Terminal
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:

InvoiceListener.java
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 orders topic is read by billing, shipping and analytics groups without affecting one another.
  • Replaying data: a new group with auto.offset.reset=earliest reads 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.id across unrelated applications: they steal partitions from each other and each misses part of the data.
  • Slow processing inside poll() loops: exceeding max.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.sh or 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=consumer on 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