Practical 0 · Your cluster and a group you can watch
Goal: a three-broker Kafka cluster, a
Watcheryou write yourself that prints every partition it gains or loses, and one group watched through every kind of rebalance: eager, cooperative, the new protocol, a static member’s restart. Then a group that refuses a member, and you find out why.Time: ~60 minutes. Where: your files in
~/kafka-groups/on this computer; Kafka and your Java programs run in Docker containers on a network of their own. You’ll want five terminals, all in~/kafka-groups: one for the producer, three for members, one for commands. Read lesson 1 and lesson 2 first.
Task 1 · Get the lab, a topic and a steady stream of orders
mkdir -p ~/kafka-groups
cd ~/kafka-groups
curl -fo lab http://localhost:8800/kafka-consumer-groups-deep/tools/lab
chmod +x lab
./lab setup p0
starting 3 Kafka 4.4.0 brokers (about 30 s; longer the first time, while Docker downloads apache/kafka:4.4.0)…
✓ 3 brokers (Kafka 4.4.0, KRaft) in containers kcg-1, kcg-2, kcg-3, on the network kcg-net (27 s)
✓ lib/: kafka-clients 4.4.0 and its logger, SHA-256 checked
✓ ./run (your Java programs, in a JDK 25 container) and ./kafka (Kafka's tools, in a broker)
ready for p0. Try: ./kafka kafka-topics --list
(every command is in lab.log; ./lab setup p0 -v shows them as they run)
You now have two small scripts. ./kafka <tool> ... runs one of Kafka’s command-line tools inside broker
kcg-1, already pointed at the cluster. ./run File.java ... runs a Java program of yours in a JDK 25 container
on the same network; NAME=w1 ./run ... names that container kcg-run-w1.
What setup did
- The cluster: three containers from
apache/kafka:4.4.0,kcg-1tokcg-3, each both a broker and a KRaft controller (no ZooKeeper), on the Docker networkkcg-net, each with its data in a volumekcg-N-data. Brokers delete a partition’s oldest 4 MB segments once it holds more than 8 MB (log.segment.bytes,log.retention.bytes), so a partition stays under about 12 MB and the course small on disk; compacted topics such as__consumer_offsetsaren’t affected. - No published ports: nothing listens on this computer’s network. Clients reach the brokers as
kcg-1:9092insidekcg-net, which is why your programs run in a container too. - The jars:
kafka-clients-4.4.0.jarand SLF4J 1.7.36 (the logging API it uses, and a simple logger) from Maven Central intolib/, each checked against a SHA-256 in the lab script. ./runisdocker run --rm --network kcg-net -v ~/kafka-groups:/work eclipse-temurin:25.0.5.1_2-jdk java -cp 'lib/*' ...plus your user id (so files it writes are yours) and the client’s log level:LOG=info ./run ...shows the client’s own log, hidden below warnings by default.- Everything carries the label
fromzero.course=kafka-consumer-groups-deep;./lab reset p0removes only labelled things, and running setup again keeps what you have.
Create the topic: 6 partitions, each with a copy on all 3 brokers.
./kafka kafka-topics --create --topic orders --partitions 6 --replication-factor 3
Created topic orders.
In terminal 1, start a producer that sends 100 orders a second for an hour, and leave it running:
./kafka kafka-producer-perf-test --topic orders --num-records 360000 --throughput 100 --record-size 100 \
--producer-props partitioner.class=org.apache.kafka.clients.producer.RoundRobinPartitioner
It starts with one line, Option --producer-props has been deprecated ...: the option still works in 4.4. Then
it prints a line every 5 seconds.
Why the partitioner: without a key, a producer fills one partition’s batch before moving on (lesson 1), so a member might own only empty partitions. Round-robin spreads the orders evenly, so every member has something to read.
Task 2 · Write the Watcher, find its coordinator
Create ~/kafka-groups/Watcher.java yourself, one file, the public class Watcher:
- run as
./run Watcher.java <group> <name> [setting=value ...]: joins<group>withclient.id<name>, bootstrapkcg-1:9092,kcg-2:9092,kcg-3:9092, String deserializers; each extra argument is a consumer setting - subscribes to
orderswith aConsumerRebalanceListenerthat prints, for each callback,HH:mm:ss.SSS <name> assigned|revoked|lost [partition numbers] now [what it owns now] - once a second prints
HH:mm:ss.SSS <name> read <N> from [partitions those records came from], even when N is 0 - Ctrl-C leaves the group cleanly: a shutdown hook calls
consumer.wakeup(), the loop catchesWakeupException, thenclose(); any other exception is printed as<name> stopped: <exception>
Hint
new KafkaConsumer<String, String>(props), then consumer.subscribe(List.of("orders"), new ConsumerRebalanceListener() {...})
with onPartitionsRevoked, onPartitionsAssigned and onPartitionsLost, keeping a Set<TopicPartition> of what
it owns. In the loop: poll(Duration.ofMillis(100)), count, and print when System.currentTimeMillis() / 1000
changes. LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")) gives the time.
Solution
// ~/kafka-groups/Watcher.java: a group member that says which partitions it owns, and how much it reads each second
// ./run Watcher.java <group> <name> [config=value ...]
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.WakeupException;
public class Watcher {
static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
static void say(String name, String what) {
System.out.println(LocalTime.now().format(TIME) + " " + name + " " + what);
}
static List<Integer> numbers(Collection<TopicPartition> parts) { // [orders-4, orders-1] -> [1, 4]
return parts.stream().map(TopicPartition::partition).sorted().toList();
}
public static void main(String[] args) {
String group = args[0], name = args[1];
Properties props = new Properties();
props.put("bootstrap.servers", "kcg-1:9092,kcg-2:9092,kcg-3:9092");
props.put("group.id", group);
props.put("client.id", name);
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
for (String arg : Arrays.copyOfRange(args, 2, args.length)) { // extra settings: name=value
String[] kv = arg.split("=", 2);
props.put(kv[0], kv[1]);
}
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
Set<TopicPartition> mine = new HashSet<>();
consumer.subscribe(List.of("orders"), new ConsumerRebalanceListener() {
public void onPartitionsRevoked(Collection<TopicPartition> parts) {
mine.removeAll(parts);
say(name, "revoked " + numbers(parts) + " now " + numbers(mine));
}
public void onPartitionsAssigned(Collection<TopicPartition> parts) {
mine.addAll(parts);
say(name, "assigned " + numbers(parts) + " now " + numbers(mine));
}
public void onPartitionsLost(Collection<TopicPartition> parts) {
mine.removeAll(parts);
say(name, "lost " + numbers(parts) + " now " + numbers(mine));
}
});
Thread main = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread(() -> { // Ctrl-C: leave the group cleanly
consumer.wakeup();
try { main.join(); } catch (InterruptedException e) { }
}));
long second = System.currentTimeMillis() / 1000;
int count = 0;
Set<Integer> from = new TreeSet<>();
try {
while (true) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(100))) {
count++;
from.add(r.partition());
}
long now = System.currentTimeMillis() / 1000;
if (now != second) { // one line per second, even when it read 0
say(name, "read " + count + " from " + from);
second = now;
count = 0;
from.clear();
}
}
} catch (WakeupException e) {
say(name, "leaving the group");
} catch (Exception e) { // e.g. a group that won't take this member
say(name, "stopped: " + e);
} finally {
consumer.close();
}
}
}
Predict first: w1 is the group’s only member. Which partitions does it get, and about how many orders a second does it read?
In terminal 2:
NAME=w1 ./run Watcher.java watchers w1
What you see
06:49:53.295 w1 assigned [0, 1, 2, 3, 4, 5] now [0, 1, 2, 3, 4, 5]
All six, and then about 100 a second from all six. Before that come a few seconds of read 0 from []: part of it
is the coordinator of a new group waiting group.initial.rebalance.delay.ms (3,000 ms by default) for more members
before its first share-out.
Now find the coordinator, two ways. Lesson 2 computed that watchers keeps its bookmarks in partition 17 of
__consumer_offsets:
./kafka kafka-consumer-groups --describe --group watchers --state
./kafka kafka-topics --describe --topic __consumer_offsets | grep 'Partition: 17\s'
The COORDINATOR (ID) of the first is the Leader of the second (on your cluster, maybe another broker than the
lesson’s).
Task 3 · Eager, then cooperative
Predict first: w2 joins
watchers. Does w1 give up only the partitions w2 will get, or all six?
In terminal 3, NAME=w2 ./run Watcher.java watchers w2; once it reads, in terminal 4,
NAME=w3 ./run Watcher.java watchers w3. Watch w1’s terminal:
06:50:20.298 w1 revoked [0, 1, 2] now []
06:50:20.323 w1 assigned [0, 1] now [0, 1]
All of them, every time (w1’s lines when w3 joined; when w2 joined it gave up all six), and back some 10 to 25 ms later: all members poll every 100 ms, so nobody holds up the barrier. Stop all three Watchers with Ctrl-C (leave the producer running).
Now cooperative, in a new group watchers-coop; terminals 2, 3, 4, a few seconds apart:
NAME=c1 ./run Watcher.java watchers-coop c1 partition.assignment.strategy=org.apache.kafka.clients.consumer.CooperativeStickyAssignor
NAME=c2 ./run Watcher.java watchers-coop c2 partition.assignment.strategy=org.apache.kafka.clients.consumer.CooperativeStickyAssignor
NAME=c3 ./run Watcher.java watchers-coop c3 partition.assignment.strategy=org.apache.kafka.clients.consumer.CooperativeStickyAssignor
Predict first: when c3 joins, what does c1 revoke, and how long until c3 reads anything?
What you see
c1 and c2 each give up one partition and keep reading the other two without a gap. c1:
06:51:25.060 c1 revoked [2] now [0, 1]
06:51:25.060 c1 assigned [] now [0, 1]
c3 prints assigned [], then, about 3 seconds later, its two partitions: the second rebalance, one heartbeat
interval later.
06:51:25.065 c3 assigned [] now []
06:51:28.068 c3 assigned [2, 5] now [2, 5]
Stop c1, c2 and c3 (task 5 starts c1 and c2 again).
Task 4 · Moving less: the new protocol and static members
The new protocol. In a new group, with
group.protocol=consumer, in terminals 2, 3 and 4:
NAME=n1 ./run Watcher.java watchers-new n1 group.protocol=consumer
NAME=n2 ./run Watcher.java watchers-new n2 group.protocol=consumer
NAME=n3 ./run Watcher.java watchers-new n3 group.protocol=consumer
Each existing member gives up only what moves, and keeps reading the rest. n3 gets assigned [] at once and its
partitions about 5 seconds later, one heartbeat interval of the new protocol.
06:51:59.582 n3 assigned [] now []
06:52:04.597 n3 assigned [2, 5] now [2, 5]
Look at the broker’s side, while all three run:
./kafka kafka-consumer-groups --describe --group watchers-new --members --verbose
CURRENT-EPOCH equals TARGET-EPOCH for every member: each has reached the assignment the coordinator computed.
Stop the three.
A static member. Three members with fixed names: in terminals 2, 3, 4,
NAME=s1 ./run Watcher.java watchers-static s1 group.instance.id=s1
NAME=s2 ./run Watcher.java watchers-static s2 group.instance.id=s2
NAME=s3 ./run Watcher.java watchers-static s3 group.instance.id=s3
Predict first: you kill s2 hard, as a crash would, and start it again 10 seconds later. What do s1 and s3 print?
In terminal 5, docker kill kcg-run-s2. Count to ten, then start s2 again in its terminal, with the same
command.
What you see
s2 gets back exactly the partitions it had, and s1 and s3 print nothing but their read lines. Then s2’s first
read lines hold the orders that piled up while it was away.
06:53:04.202 s2 assigned [2, 3] now [2, 3]
06:53:05.005 s2 read 515 from [2, 3]
Stop the three with Ctrl-C. Static members don’t leave the group: their partitions wait for session.timeout.ms
(45 s by default), which lesson 4 comes back to.
Task 5 · Break it: a member the group refuses
Start c1 and c2 again in terminals 2 and 3 (task 3’s commands): they rejoin watchers-coop. A colleague starts a third member
with the assignor they always use:
NAME=c9 ./run Watcher.java watchers-coop c9 partition.assignment.strategy=org.apache.kafka.clients.consumer.RoundRobinAssignor
With the client’s own ERROR ... JoinGroup failed line, your Watcher says:
06:53:22.155 c9 stopped: org.apache.kafka.common.errors.InconsistentGroupProtocolException: The group member's supported protocols are incompatible with those of existing members or first group member tried to join with empty protocol type or empty protocol list.
Find why, in this order:
- The error: c9’s “protocols” (for a consumer, its assignors) don’t match the existing members’.
- What the group uses:
./kafka kafka-consumer-groups --describe --group watchers-coop --stateshowsASSIGNMENT-STRATEGYcooperative-sticky. - What c9 offered: only
roundrobin. Nothing in common, so the coordinator refused it; c1 and c2 carried on.
The fix is to offer what the group uses, or both while a group migrates (lesson 2): start c9 with
partition.assignment.strategy=org.apache.kafka.clients.consumer.RoundRobinAssignor,org.apache.kafka.clients.consumer.CooperativeStickyAssignor
and it joins as a third cooperative member. Then stop c1, c2 and c9, and the producer.
Check your work
./lab check p0
It checks the cluster and topic, runs your Watcher.java for 25 seconds in a group of its own, and looks for your
four groups:
22/22 passed
Go deeper: the rebalance from the client's own log
LOG=info shows what the client itself logs. Its startup lists every consumer setting with its value
(group.protocol = classic, session.timeout.ms = 45000, heartbeat.interval.ms = 3000,
max.poll.interval.ms = 300000), and during a rebalance its ConsumerCoordinator explains each step: why it is
rejoining, the generation it joined, the partitions it was given. Run a fourth member of watchers with
LOG=info NAME=w4 ./run Watcher.java watchers w4 and read it alongside your Watcher lines.