- The first four lessons. A single-node Kafka cluster with KRaft, Topics, partitions and the log underneath, Producing: keys, partitions and ordering and Consuming: offsets, groups and where to start explain the words this lesson builds on: broker, listener, topic, partition, offset, key, consumer group and committed offset.
- Docker with Compose v2.20 or later. The lesson was tested with Docker 29 and Compose v5.
- A bash-style shell. The commands use bash; on Windows, run them in WSL.
- Java or Python. JDK 21 with Maven 3.9 or later, or Python 3.12 to 3.14 with
pip; one of the two is enough. The consumer and its commands are on the page in both languages: pick yours on any code tab, and the page keeps the choice. The first run downloads the Kafka client, so it needs an internet connection. - On Ubuntu, also under WSL. Ubuntu 24.04 ships Maven 3.8, which fails on this project with "Source option 5 is no longer supported"; install Maven 3.9 from maven.apache.org instead. For Python, install the
python3-venvpackage first. - If you have Python 3.15. Check with
python3 --version. The lab's Kafka client for Python,confluent-kafka2.16.1, has no prebuilt package for Python 3.15, sopiptries to build it from source and usually stops with Failed building wheel for confluent-kafka. Install Python 3.14 as well, for example withbrew install python@3.14on a Mac. Then, in One member, below, create the virtual environment withpython3.14 -m venv --clear .venvinstead ofpython3 -m venv .venv;--clearempties a.venvthat an earlier attempt left behind. - Four terminals. Each member of the group runs in a terminal of its own, up to three at a time, and a fourth terminal runs the commands. Tabs in one terminal window are fine.
- TCP ports 19234 and 19134 free on your machine. The labs of the earlier lessons use 19130, 19131, 19232, 19132, 19233 and 19133, so all five can run side by side. You can change the ports; the lesson tells you where.
- Room for one broker. The broker uses about 500 MB of memory. The image is the one from the earlier lessons.
What you are about to run
The lab is one Docker Compose project with one container, started from apache/kafka:4.3.2, the image of the earlier lessons: a single node that is broker and controller at once. You create one topic, rides.completed, with six partitions, and write six bike rides to it from one file, rides.txt, with the console producer. Then you run up to three copies of a small consumer on your machine, in Java or in Python, as members of one consumer group, ride-billing, and watch the group share the six partitions among them.
Each line of rides.txt is a key, a | and a value: the key is the bike, and the value is the ride, in the same shape as the rides of the earlier lessons.
bike-1003|{"bike":"bike-1003","from":"station-12","to":"station-05","minutes":9}
bike-1009|{"bike":"bike-1009","from":"station-04","to":"station-09","minutes":16}
bike-1002|{"bike":"bike-1002","from":"station-07","to":"station-02","minutes":18}
bike-1010|{"bike":"bike-1010","from":"station-10","to":"station-01","minutes":23}
bike-1001|{"bike":"bike-1001","from":"station-03","to":"station-11","minutes":12}
bike-1004|{"bike":"bike-1004","from":"station-08","to":"station-06","minutes":7}The keys are picked so that each ride lands on a partition of its own, in the order of the file: bike-1003 on partition 0, bike-1009 on 1, bike-1002 on 2, bike-1010 on 3, bike-1001 on 4 and bike-1004 on 5. With one ride on each partition, the rides a member prints show which partitions it holds.
The broker has the three listeners of the last two labs, on ports of its own:
KAFKA_LISTENERS: INTERNAL://:29092,HOST://:19234,EXTERNAL://:19134,CONTROLLER://:9093
KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:29092,HOST://localhost:${KAFKA_HOST_PORT:-19234},EXTERNAL://${KAFKA_ADVERTISED_HOST:-host.docker.internal}:${KAFKA_PORT:-19134}| Listener | Port | Advertised address | For |
|---|---|---|---|
| INTERNAL | 29092, inside the container only | kafka:29092 |
Kafka's tools, run with docker compose exec |
| HOST | 19234 | localhost:19234 |
your consumers, and other programs on your machine |
| EXTERNAL | 19134 | host.docker.internal:19134 |
BROKA and other clients in containers |
CONTROLLER, on port 9093, is the quorum's, as before. As the third lesson explained, programs on your machine need HOST: EXTERNAL advertises host.docker.internal, a name your machine may not know.
Get the lab
git clone https://github.com/orchesta/broka.git
cd broka/learn/kafka/05-consumer-groups
ls -AIf you kept the clone from an earlier lesson, run git pull in it instead of cloning again, then change into the new folder.
.env.example
README.md
compose.yml
java
python
rides.txtcompose.yml is the project. java and python hold the same consumer, one folder per language: java is a small Maven project whose one real dependency is the Kafka client, kafka-clients 4.3.2; python has the script and a requirements.txt that names confluent-kafka 2.16.1. rides.txt holds the six rides. .env.example holds the three settings you may want to change, and README.md has the run commands and the connection values.
The settings file is optional. Copy it when you need to change something:
cp .env.example .env# Host port of the HOST listener, for the programs you run on this machine. If you change it, change
# localhost:19234 in the Java and Python code too.
KAFKA_HOST_PORT=19234
# Host port of the EXTERNAL listener, for clients in other containers, such as BROKA.
KAFKA_PORT=19134
# Address the broker hands back to clients on the EXTERNAL listener. Keep host.docker.internal on Docker
# Desktop; on Linux set it to the host's IP address.
KAFKA_ADVERTISED_HOST=host.docker.internalKAFKA_HOST_PORT: change it when 19234 is taken. The consumer haslocalhost:19234in its code, so change the port there too.KAFKA_PORT: change it when 19134 is taken.KAFKA_ADVERTISED_HOST: the address the broker hands to clients in other containers. On Linux with Docker Engine, put the IP address of your machine here; the first lesson explains why.
Start it and write the rides
docker compose up -d --wait--wait returns when the broker is healthy. The last lines look like this:
Network broka-lab-kafka-consumer-groups_default Created
Volume broka-lab-kafka-consumer-groups_kafka-data Created
Container broka-lab-kafka-consumer-groups-kafka-1 HealthyAs in the earlier labs, the broker does not create a topic when a client first uses it: KAFKA_AUTO_CREATE_TOPICS_ENABLE is false. Create the topic, with six partitions:
docker compose exec kafka /opt/kafka/bin/kafka-topics.sh --bootstrap-server localhost:29092 --create --topic rides.completed --partitions 6 --replication-factor 1WARNING: Due to limitations in metric names, topics with a period ('.') or underscore ('_') could collide. To avoid issues it is best to use either, but not both.
Created topic rides.completed.The warning is the one from the second lesson: every topic name with a dot draws it.
Write the six rides with the console producer:
docker compose exec -T kafka /opt/kafka/bin/kafka-console-producer.sh --bootstrap-server localhost:29092 --topic rides.completed --reader-property parse.key=true --reader-property key.separator='|' < rides.txtAs in the earlier lessons, parse.key=true and key.separator='|' make everything before the | the key, and -T leaves the terminal out, so the lines of the file reach the producer as they are. The producer prints nothing when it succeeds.
Read the rides back with the console consumer, in a group of its own, ride-audit, and print the partition and the key of each:
docker compose exec kafka /opt/kafka/bin/kafka-console-consumer.sh --bootstrap-server localhost:29092 --topic rides.completed --group ride-audit --from-beginning --max-messages 6 --formatter-property print.partition=true --formatter-property print.key=trueThe consumer rebalance protocol (KIP-848) is production-ready! Set group.protocol=consumer to try it out. See https://kafka.apache.org/documentation/#consumer_rebalance_protocol
Partition:4 bike-1001 {"bike":"bike-1001","from":"station-03","to":"station-11","minutes":12}
Partition:5 bike-1004 {"bike":"bike-1004","from":"station-08","to":"station-06","minutes":7}
Partition:2 bike-1002 {"bike":"bike-1002","from":"station-07","to":"station-02","minutes":18}
Partition:3 bike-1010 {"bike":"bike-1010","from":"station-10","to":"station-01","minutes":23}
Partition:0 bike-1003 {"bike":"bike-1003","from":"station-12","to":"station-05","minutes":9}
Partition:1 bike-1009 {"bike":"bike-1009","from":"station-04","to":"station-09","minutes":16}
Processed a total of 6 messagesOne ride on each partition, as the keys promised. Which partition comes first can differ. The first line is the notice about the newer group protocol that the earlier lessons showed; The older protocol, below, explains what it is about.
A consumer that reports its partitions
The consumer is the same program in both languages. Pick yours:
package learn;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.WakeupException;
import org.apache.kafka.common.serialization.StringDeserializer;
public class GroupConsumer {
public static void main(String[] args) {
// The member's name, such as billing-1. Every line the program prints starts with it.
String name = args[0];
var props = new Properties();
props.put("bootstrap.servers", "localhost:19234");
props.put("group.id", "ride-billing");
// The name is also the client id, which the group tools show for each member.
props.put("client.id", name);
props.put("group.protocol", "consumer");
// An optional second argument asks the broker for an assignor: uniform or range.
if (args.length > 1) {
props.put("group.remote.assignor", args[1]);
}
props.put("key.deserializer", StringDeserializer.class.getName());
props.put("value.deserializer", StringDeserializer.class.getName());
props.put("auto.offset.reset", "earliest");
var consumer = new KafkaConsumer<String, String>(props);
var main = Thread.currentThread();
// Ctrl+C runs this hook: it wakes poll() up and waits until the loop below has closed the consumer.
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
consumer.wakeup();
try {
main.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
try {
// The listener prints each change to this member's partitions.
consumer.subscribe(List.of("rides.completed"), new ConsumerRebalanceListener() {
@Override
public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
System.out.println(name + ": assigned " + numbers(partitions));
}
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
System.out.println(name + ": revoked " + numbers(partitions));
}
});
while (true) {
for (var record : consumer.poll(Duration.ofSeconds(1))) {
System.out.println(name + ": " + record.key() + ", partition " + record.partition()
+ ", offset " + record.offset());
}
}
} catch (WakeupException e) {
// Ctrl+C: leave the loop.
} finally {
// Commits the position, gives the partitions back and leaves the group.
consumer.close();
}
}
private static List<Integer> numbers(Collection<TopicPartition> partitions) {
return partitions.stream().map(TopicPartition::partition).sorted().toList();
}
}import sys
from confluent_kafka import Consumer
# The member's name, such as billing-1. Every line the program prints starts with it.
name = sys.argv[1]
config = {
"bootstrap.servers": "localhost:19234",
"group.id": "ride-billing",
# The name is also the client id, which the group tools show for each member.
"client.id": name,
"group.protocol": "consumer",
"auto.offset.reset": "earliest",
}
# An optional second argument asks the broker for an assignor: uniform or range.
if len(sys.argv) > 2:
config["group.remote.assignor"] = sys.argv[2]
consumer = Consumer(config)
def numbers(partitions):
return sorted(p.partition for p in partitions)
# The callbacks print each change to this member's partitions.
consumer.subscribe(
["rides.completed"],
on_assign=lambda c, partitions: print(f"{name}: assigned {numbers(partitions)}"),
on_revoke=lambda c, partitions: print(f"{name}: revoked {numbers(partitions)}"),
)
try:
while True:
msg = consumer.poll(1.0)
if msg is None:
continue
if msg.error():
print(f"{name}: error: {msg.error()}")
continue
print(f"{name}: {msg.key().decode()}, partition {msg.partition()}, offset {msg.offset()}")
except KeyboardInterrupt:
pass # Ctrl+C: leave the loop.
finally:
# Commits the position, gives the partitions back and leaves the group.
consumer.close()Most of it is the consumer of the fourth lesson: it connects to localhost:19234, uses the newer group protocol, starts a new group at the first record with auto.offset.reset=earliest, and commits by itself every five seconds. When you press Ctrl+C, it closes, which commits once more and leaves the group. Four things are new:
- A name. The program takes the member's name as its first argument, such as
billing-1, and starts every line it prints with the name. The name is also the client id,client.id, which the group tools show for each member. - One group for all copies. Every copy has the same
group.id,ride-billing, so every copy you start joins the same group. The group shares the partitions ofrides.completedamong its members, and each partition goes to one member at a time. - A listener.
subscribe()gets a listener: aConsumerRebalanceListenerin Java, theon_assignandon_revokecallbacks in Python. The client calls it whenever the member's partitions change, and the program prints the change: assigned with the partitions the member has just been given, revoked with the ones just taken away. A list can be empty. - An assignor, if you ask for one. An optional second argument,
uniformorrange, goes intogroup.remote.assignor. It asks the broker for one of its two assignors, its two ways of sharing partitions among members. Without it, the broker uses its default. Uniform and range, below, compares the two.
One member
Each member keeps running until you stop it, so each needs a terminal of its own. Keep the terminal you have used so far for the docker compose commands; this lesson calls it the command terminal. Open a second terminal, change into the lab's folder in it, learn/kafka/05-consumer-groups in your clone, and start the first member, billing-1:
cd java
mvn -q compile exec:java -Dexec.args=billing-1cd python
python3 -m venv .venv
. .venv/bin/activate
pip install -r requirements.txt
python group_consumer.py billing-1The first Maven run downloads the Kafka client and Maven's plugins; -q keeps Maven quiet, so only the program's lines appear. pip installs one package, confluent-kafka, and prints its own lines first (if it stops with Failed building wheel for confluent-kafka, see the Python 3.15 item under Before you start). Then the member prints its partitions and the six rides, and keeps polling:
billing-1: assigned [0, 1, 2, 3, 4, 5]
billing-1: bike-1001, partition 4, offset 0
billing-1: bike-1004, partition 5, offset 0
billing-1: bike-1002, partition 2, offset 0
billing-1: bike-1010, partition 3, offset 0
billing-1: bike-1003, partition 0, offset 0
billing-1: bike-1009, partition 1, offset 0billing-1: assigned [0, 1, 2, 3, 4, 5]
billing-1: bike-1004, partition 5, offset 0
billing-1: bike-1001, partition 4, offset 0
billing-1: bike-1010, partition 3, offset 0
billing-1: bike-1002, partition 2, offset 0
billing-1: bike-1009, partition 1, offset 0
billing-1: bike-1003, partition 0, offset 0The only member gets all six partitions. The group is new, so earliest starts each partition at offset 0. Which partition comes first can differ.
A second member
Open a third terminal, change into the lab's folder, and start a second member, billing-2. In Python, the virtual environment is there already; the new terminal only has to activate it:
cd java
mvn -q compile exec:java -Dexec.args=billing-2cd python
. .venv/bin/activate
python group_consumer.py billing-2Within a few seconds, both members print. Here are the lines of both terminals together, in the order they came; the name at the start of each line tells you which terminal printed it:
billing-2: assigned []
billing-1: revoked [3, 4, 5]
billing-1: assigned []
billing-2: assigned [3, 4, 5]billing-1: revoked [3, 4, 5]
billing-1: assigned []
billing-2: assigned [3, 4, 5]The broker gave half of the partitions to the new member, in two steps. First billing-1 gave up partitions 3, 4 and 5; only then did billing-2 get them. A partition never has two owners at once, and billing-1 kept reading partitions 0, 1 and 2 all along. Each line lists only what changed, and an empty list means nothing changed on that side: billing-1: assigned [] says that billing-1 got nothing new. The Java client also reports a member's first assignment when it is still empty, which is why billing-2: assigned [] comes first there.
The members hear about a change through the broker's answers to their heartbeats, the requests each member sends every five seconds by default, so a change takes a few seconds.
Write the rides again from the command terminal:
docker compose exec -T kafka /opt/kafka/bin/kafka-console-producer.sh --bootstrap-server localhost:29092 --topic rides.completed --reader-property parse.key=true --reader-property key.separator='|' < rides.txtEach member prints the rides of its own partitions, now at offset 1. Here they are by member, the same in both languages; in your terminals, the order can differ:
billing-1: bike-1003, partition 0, offset 1
billing-1: bike-1009, partition 1, offset 1
billing-1: bike-1002, partition 2, offset 1
billing-2: bike-1010, partition 3, offset 1
billing-2: bike-1001, partition 4, offset 1
billing-2: bike-1004, partition 5, offset 1What the broker sees
From the command terminal, describe the group's members; --verbose adds what the broker knows about each member's assignment:
docker compose exec kafka /opt/kafka/bin/kafka-consumer-groups.sh --bootstrap-server localhost:29092 --describe --group ride-billing --members --verboseGROUP CONSUMER-ID HOST CLIENT-ID #PARTITIONS CURRENT-EPOCH CURRENT-ASSIGNMENT TARGET-EPOCH TARGET-ASSIGNMENT
ride-billing 5w5n9LFsSwiziXXXR-JG-Q /192.168.65.1 billing-2 3 3 rides.completed:3,4,5 3 rides.completed:3,4,5
ride-billing 6KIsUn6DSgij65zRcKR8lQ /192.168.65.1 billing-1 3 3 rides.completed:0,1,2 3 rides.completed:0,1,2GROUP CONSUMER-ID HOST CLIENT-ID #PARTITIONS CURRENT-EPOCH CURRENT-ASSIGNMENT TARGET-EPOCH TARGET-ASSIGNMENT
ride-billing QvpfkceYSBCOQr3f7l5+ww /192.168.65.1 billing-1 3 3 rides.completed:0,1,2 3 rides.completed:0,1,2
ride-billing BL0JYq+pTiasTgNVdqYscA /192.168.65.1 billing-2 3 3 rides.completed:3,4,5 3 rides.completed:3,4,5One row per member, named by its client id. CONSUMER-ID is random, so yours differs; HOST is the address the broker saw the consumer come from, so it may differ too.
CURRENT-ASSIGNMENT is what the member holds now, and TARGET-ASSIGNMENT is what the broker wants it to hold. The broker computes a new target as soon as the group changes, and the members then catch up with it by giving up and taking over partitions, as in the lines above. Once the change is over, as here, the two are the same.
Each change to the group gets a number, called an epoch. The group's epoch goes up each time the group needs a new assignment, as when a member joins. TARGET-EPOCH is the group epoch the target was computed for, and CURRENT-EPOCH the one the member has caught up with. The numbers themselves can differ on your machine; what matters is whether they match, and whether each current assignment matches its target.
Use --state in place of --members to see the group as a whole:
docker compose exec kafka /opt/kafka/bin/kafka-consumer-groups.sh --bootstrap-server localhost:29092 --describe --group ride-billing --state --verboseGROUP COORDINATOR (ID) ASSIGNMENT-STRATEGY STATE GROUP-EPOCH TARGET-ASSIGNMENT-EPOCH #MEMBERS
ride-billing kafka:29092 (1) uniform Stable 3 3 2ASSIGNMENT-STRATEGY is uniform, the broker's default assignor, because neither member asked for another. STATE is Stable: every member holds its target assignment. While members are still handing partitions over, the state is Reconciling instead. GROUP-EPOCH is the group's epoch, and TARGET-ASSIGNMENT-EPOCH the epoch of its latest target assignment.
A third member
Open a fourth terminal, change into the lab's folder, and start billing-3 the same way:
cd java
mvn -q compile exec:java -Dexec.args=billing-3cd python
. .venv/bin/activate
python group_consumer.py billing-3The three members print, together:
billing-3: assigned []
billing-2: revoked [5]
billing-2: assigned []
billing-1: revoked [2]
billing-1: assigned []
billing-3: assigned [2, 5]billing-1: revoked [2]
billing-1: assigned []
billing-2: revoked [5]
billing-2: assigned []
billing-3: assigned [2, 5]Now each member holds two partitions, and only two partitions moved: partition 2 from billing-1, and partition 5 from billing-2. The other four stayed where they were. That is what uniform, the default assignor, aims for: partitions spread as evenly as the members allow, with as few moves as possible. billing-3 can get its two partitions in one step or in two, as each is freed.
Describe the members again:
docker compose exec kafka /opt/kafka/bin/kafka-consumer-groups.sh --bootstrap-server localhost:29092 --describe --group ride-billing --members --verboseGROUP CONSUMER-ID HOST CLIENT-ID #PARTITIONS CURRENT-EPOCH CURRENT-ASSIGNMENT TARGET-EPOCH TARGET-ASSIGNMENT
ride-billing 5w5n9LFsSwiziXXXR-JG-Q /192.168.65.1 billing-2 2 4 rides.completed:3,4 4 rides.completed:3,4
ride-billing 6KIsUn6DSgij65zRcKR8lQ /192.168.65.1 billing-1 2 4 rides.completed:0,1 4 rides.completed:0,1
ride-billing F1Zj9im9RDupwWJNI7ZiYQ /192.168.65.1 billing-3 2 4 rides.completed:2,5 4 rides.completed:2,5GROUP CONSUMER-ID HOST CLIENT-ID #PARTITIONS CURRENT-EPOCH CURRENT-ASSIGNMENT TARGET-EPOCH TARGET-ASSIGNMENT
ride-billing QvpfkceYSBCOQr3f7l5+ww /192.168.65.1 billing-1 2 4 rides.completed:0,1 4 rides.completed:0,1
ride-billing IIGhlp+9TkyA4G/ilSpjaA /192.168.65.1 billing-3 2 4 rides.completed:2,5 4 rides.completed:2,5
ride-billing BL0JYq+pTiasTgNVdqYscA /192.168.65.1 billing-2 2 4 rides.completed:3,4 4 rides.completed:3,4Each member holds two partitions, the target and the current assignment are the same again, and all the epochs have caught up.
A member leaves
In billing-2's terminal, press Ctrl+C. The terminals print:
billing-2: revoked [3, 4]
billing-1: assigned [3]
billing-3: assigned [4]billing-2: revoked [3, 4]
billing-3: assigned [3]
billing-1: assigned [4]close() gives the member's partitions back at once, and the other two members take them over within a few seconds, one each, so each holds three. Which of them gets which can differ from run to run: in the runs shown on this page, partition 3 went to billing-1 in Java and to billing-3 in Python. A member that crashes gives nothing back: as the fourth lesson showed, its partitions wait until its session times out, 45 seconds by default.
Write the rides again from the command terminal:
docker compose exec -T kafka /opt/kafka/bin/kafka-console-producer.sh --bootstrap-server localhost:29092 --topic rides.completed --reader-property parse.key=true --reader-property key.separator='|' < rides.txtEach member prints the rides of its own partitions. Here they are by member; in your terminals, the order can differ:
billing-1: bike-1003, partition 0, offset 2
billing-1: bike-1009, partition 1, offset 2
billing-1: bike-1010, partition 3, offset 2
billing-3: bike-1002, partition 2, offset 2
billing-3: bike-1001, partition 4, offset 2
billing-3: bike-1004, partition 5, offset 2billing-1: bike-1003, partition 0, offset 2
billing-1: bike-1009, partition 1, offset 2
billing-1: bike-1001, partition 4, offset 2
billing-3: bike-1002, partition 2, offset 2
billing-3: bike-1010, partition 3, offset 2
billing-3: bike-1004, partition 5, offset 2Every ride comes once, at offset 2. The members that took over partitions 3 and 4 started at the offsets billing-2 committed when it closed, so they skipped nothing and read nothing twice. Describe the members once more:
docker compose exec kafka /opt/kafka/bin/kafka-consumer-groups.sh --bootstrap-server localhost:29092 --describe --group ride-billing --members --verboseGROUP CONSUMER-ID HOST CLIENT-ID #PARTITIONS CURRENT-EPOCH CURRENT-ASSIGNMENT TARGET-EPOCH TARGET-ASSIGNMENT
ride-billing 6KIsUn6DSgij65zRcKR8lQ /192.168.65.1 billing-1 3 5 rides.completed:0,1,3 5 rides.completed:0,1,3
ride-billing F1Zj9im9RDupwWJNI7ZiYQ /192.168.65.1 billing-3 3 5 rides.completed:2,4,5 5 rides.completed:2,4,5GROUP CONSUMER-ID HOST CLIENT-ID #PARTITIONS CURRENT-EPOCH CURRENT-ASSIGNMENT TARGET-EPOCH TARGET-ASSIGNMENT
ride-billing QvpfkceYSBCOQr3f7l5+ww /192.168.65.1 billing-1 3 5 rides.completed:0,1,4 5 rides.completed:0,1,4
ride-billing IIGhlp+9TkyA4G/ilSpjaA /192.168.65.1 billing-3 3 5 rides.completed:2,3,5 5 rides.completed:2,3,5Uniform and range
So far, the broker has used uniform. Its other assignor, range, shares partitions differently. A group uses one assignor at a time, so you will start all three members with range. First stop billing-1 and billing-3 with Ctrl+C. The group is empty now, and keeps its committed offsets. Then start the three members again, one after the other, with range as a second argument. Start each one in the terminal it ran in before: that terminal is still in java or python, and for Python the virtual environment is still active. If you have closed one of those terminals, open a new one, change into java or python in the lab's folder, and for Python activate the virtual environment again with . .venv/bin/activate. For billing-1:
mvn -q compile exec:java -Dexec.args="billing-1 range"python group_consumer.py billing-1 rangeThen start billing-2 and billing-3 the same way, and wait until each new member prints assigned with partition numbers before you start the next; in Java, its first assigned [] does not count. No rides come this time: the group resumes at its committed offsets, and nothing new has been written. When billing-3 joins, the three members print, together:
billing-3: assigned []
billing-2: revoked [3]
billing-2: assigned []
billing-1: revoked [0, 1]
billing-1: assigned []
billing-1: assigned [3]
billing-3: assigned [0, 1]billing-1: revoked [3]
billing-1: assigned []
billing-2: revoked [2]
billing-2: assigned []
billing-3: assigned [2, 3]From the command terminal, describe the members:
docker compose exec kafka /opt/kafka/bin/kafka-consumer-groups.sh --bootstrap-server localhost:29092 --describe --group ride-billing --members --verboseGROUP CONSUMER-ID HOST CLIENT-ID #PARTITIONS CURRENT-EPOCH CURRENT-ASSIGNMENT TARGET-EPOCH TARGET-ASSIGNMENT
ride-billing OE56iQicQCeryx0-u9OSNg /192.168.65.1 billing-3 2 10 rides.completed:0,1 10 rides.completed:0,1
ride-billing znadFtJzS3e-WH9VfgB9lQ /192.168.65.1 billing-2 2 10 rides.completed:4,5 10 rides.completed:4,5
ride-billing UcGJBUoQSriiDJs2pkfwdA /192.168.65.1 billing-1 2 10 rides.completed:2,3 10 rides.completed:2,3GROUP CONSUMER-ID HOST CLIENT-ID #PARTITIONS CURRENT-EPOCH CURRENT-ASSIGNMENT TARGET-EPOCH TARGET-ASSIGNMENT
ride-billing x0ZwS6mMQ4SNY1aoxoOuJw /192.168.65.1 billing-1 2 10 rides.completed:4,5 10 rides.completed:4,5
ride-billing UWsOxIuYTyOtWaHnUOxvEw /192.168.65.1 billing-2 2 10 rides.completed:0,1 10 rides.completed:0,1
ride-billing uZ1xxe6jR76MrCjA+SUkJw /192.168.65.1 billing-3 2 10 rides.completed:2,3 10 rides.completed:2,3And the group:
docker compose exec kafka /opt/kafka/bin/kafka-consumer-groups.sh --bootstrap-server localhost:29092 --describe --group ride-billing --state --verboseGROUP COORDINATOR (ID) ASSIGNMENT-STRATEGY STATE GROUP-EPOCH TARGET-ASSIGNMENT-EPOCH #MEMBERS
ride-billing kafka:29092 (1) range Stable 10 10 3With range, each member holds a block of neighbouring partitions: 0 and 1, 2 and 3, or 4 and 5. Which member gets which block can differ from run to run, so your lines may differ from these. range can also move more partitions than uniform: when billing-3 joined, uniform moved two partitions in both runs shown on this page, and range moved three in the Java run and two in the Python run. When the blocks shift, range can even move a partition between two members that both stay, as partition 3 did in the Java run.
Why blocks? range lines up the topics the group reads: when they have the same number of partitions, a member that gets partitions 0 and 1 of one topic gets partitions 0 and 1 of the others too. If two of them also use the same keys, say rides and payments both keyed by bike, the records of one bike in both topics go to the same member. Their producers have to agree on the partitioner for that, as the third lesson showed. uniform does not line topics up: it spreads all the partitions as evenly as it can, and moves as few as possible.
Give every member the same assignor: if members ask for different ones, the group still uses only one of them. --state shows which one the group uses.
The older protocol
Your members use the newer group protocol, because the program sets group.protocol=consumer. The console consumer's group, ride-audit, uses the older one. From the command terminal, list the groups with their type:
docker compose exec kafka /opt/kafka/bin/kafka-consumer-groups.sh --bootstrap-server localhost:29092 --list --typeGROUP TYPE
ride-billing Consumer
ride-audit ClassicConsumer is the newer protocol, and Classic the older one. Both share partitions among the members of a group, but they do it differently:
- Classic. The broker coordinates, but does not assign. It picks one member as the leader, and the leader computes the assignment in the client and sends it back through the broker. Every change, such as a member joining or leaving, makes the whole group rebalance: every member rejoins, and the group waits until all of them have. With the default settings, each member also gives up all its partitions first, so the whole group stops reading until the new assignment arrives.
- Consumer. The broker computes the assignment, and a member takes part in a change only when its own partitions change; the others keep reading, as you saw.
Kafka 4.0 turned the newer protocol on in the broker, but the clients of this lab, kafka-clients 4.3.2 in Java and confluent-kafka 2.16.1 in Python, still use the classic protocol unless you set group.protocol=consumer. That is what the console consumer's notice is about. How an existing group moves from one protocol to the other is for a later lesson.
Stop the three members with Ctrl+C.
Try it yourself
Each of these starts with no members running: stop them all with Ctrl+C before you begin the next one.
- Start more members than there are partitions, without a second argument, each in a terminal or tab of its own, opened as in A second member. With seven, one member has nothing to read: its row in
--members --verboseshows 0 under#PARTITIONSand-underCURRENT-ASSIGNMENT. When another member stops, the idle member takes over the freed partition within a few seconds. - Mix the languages: run some members in Java and the others in Python. They form one group, because they share the group id, and the broker shares the partitions among them as before.
- Try the classic protocol. In the program, set
group.protocoltoclassicandgroup.idto a new name, such asride-billing-classic, and start two members without a second argument. When the second one joins, the first printsrevoked [0, 1, 2, 3, 4, 5]and thenassigned [0, 1, 2]: it gave up everything before it got half back. Describe the new group, with--group ride-billing-classicinstead ofride-billing: in--members --verbose, the epoch columns show-. Then setgroup.protocolback toconsumerandgroup.idback toride-billing. - See what
rangeis for. Create a second topic,rides.paid, with six partitions, and change the program to subscribe to both topics. The program prints only partition numbers, without the topic, so the same number can now appear twice, as inassigned [0, 0, 1, 1, 2, 2]. Start two members withrange:--members --verboseshows the same partition numbers of both topics on each member, as inrides.completed:0,1,2;rides.paid:0,1,2. Stop them, and start two without a second argument:uniformgives each member six partitions too, but does not line the topics up. In the runs for this lesson, each member got all six partitions of one topic. Then change the program back, so that it subscribes torides.completedalone. - Catch the group in the middle of a change, which lasts only a few seconds. With two members running, put this line in the command terminal, but do not press Enter yet. It joins the two describe commands with
;, so that they run one after the other:Start a third member, then press Enter in the command terminal at once. If you are quick enough, a member's row shows aterminaldocker compose exec kafka /opt/kafka/bin/kafka-consumer-groups.sh --bootstrap-server localhost:29092 --describe --group ride-billing --members --verbose; docker compose exec kafka /opt/kafka/bin/kafka-consumer-groups.sh --bootstrap-server localhost:29092 --describe --group ride-billing --state --verboseCURRENT-EPOCHbehind itsTARGET-EPOCH, or a current assignment that differs from its target. The tool also printsWarning: Consumer group 'ride-billing' is rebalancing., andSTATEshowsReconciling. A few seconds later, the group isStableagain. If you miss it, stop the third member with Ctrl+C and wait until each of the other two printsassignedonce more. Then bring the line back with the Up arrow, and try again.
What to remember
- A consumer group shares the partitions of its topics among its members: each partition goes to one member at a time, and a member can hold several. With more members than partitions, the extra members have nothing to read.
- With the newer protocol, the broker computes the assignment and moves a partition in two steps: the old owner gives it up, and only then does the new owner get it. Only the partitions that change owner move; the others stay put, and their members keep reading. Members learn of a change through their heartbeats.
- The group's epoch goes up each time the group needs a new assignment. When every member holds its target assignment, the group is
Stable; while members are still handing partitions over, it isReconciling. - A member that closes gives its partitions back at once, and the members that take them over resume at its committed offsets. A member that crashes keeps its partitions until its session times out, 45 seconds by default.
- The broker has two assignors:
uniform, the default, spreads partitions evenly and moves as few as it can;rangegives each member neighbouring partitions and lines up the same partition numbers across topics. A member asks for one withgroup.remote.assignor, and a group uses one at a time. - In the older, classic protocol, a leader member computes the assignment, and every change rebalances the whole group; with the default settings, every member first gives up all its partitions. Both of the lab's clients, in Java and in Python, still use the classic protocol unless you set
group.protocol=consumer.
Clean up, or carry on
To remove the lab and its data, run this in the lab's folder:
docker compose down -vYour runs left java/target or python/.venv in the lab's folder; delete it too if you want the folder as you cloned it. Or keep everything: nothing in this lab writes on its own, so it stays as you left it, on ports 19234 and 19134, next to the earlier labs if they run too. The lab's README has the short form of these commands and the connection values.

