Practical 1 · Capstone: a consumer you can trust
Goal:
OrderSink, a group member you write from an empty folder, that processes 12,000 numbered orders into a file. You kill it hard mid-batch with each way of committing and count the orders it repeats and loses, make it too slow formax.poll.interval.msand tune it while you read its lag, then break it so an order disappears.Time: ~60 minutes. Where: your files in
~/kafka-groups/sink/, on the cluster from Practical 0; four terminals in~/kafka-groups. Read lesson 3 and lesson 4 first.
Task 1 · An empty folder, 12,000 orders, and OrderSink
cd ~/kafka-groups
./lab update
./lab setup p1
mkdir sink
✓ kept your 3 brokers kcg-1, kcg-2, kcg-3 (running)
✓ lib/: kafka-clients 4.4.0 and its logger, SHA-256 checked (kept the ones you had)
✓ ./run (your Java programs, in a JDK 25 container) and ./kafka (Kafka's tools, in a broker)
loading 12,000 numbered orders (about 10 s)…
✓ topic shop-orders: 6 partitions, orders 1 to 12,000 (2000, 2000, 2000, 2000, 2000, 2000 per partition) (5 s)
ready for p1. Try: ./kafka kafka-get-offsets --topic shop-orders
(every command is in lab.log; ./lab setup p1 -v shows them as they run)
Setup adds the topic shop-orders: 6 partitions, one record per order, its value the order’s number. Every
group reads the same 12,000, so a file with each number once is a perfect run. Skipped Practical 0, or your cluster is in a state you don’t trust? ./lab reset p1 starts
you here.
Create ~/kafka-groups/sink/OrderSink.java yourself, the public class OrderSink:
- run as
./run sink/OrderSink.java <group> <name> <file> [setting=value ...]: joins<group>withclient.id<name>, subscribes toshop-orders, and a new group starts at the first order (auto.offset.reset=earliest) - for each record, “processes” the order: sleeps
ms.per.orderms (default 5), then appends a line<order number> <partition> <offset>to<file>and flushes it commit=after(the default) commits withcommitSync()once the whole batch is processed;commit=beforecommits right afterpoll(), before processing;commit=autoturns onenable.auto.commitand never commits itself. Any othersetting=valueis a consumer setting.- prints
HH:mm:ss.SSS <name> assigned [partitions] bookmarks {partition=committed offset or none}on each assignment,revoked [partitions]on each revocation, and after each poll, at most once a second,processed N (total T) - Ctrl-C (or
docker stop) finishes the batch, commits it (not inauto:close()does that), and leaves; any other exception is printed as<name> stopped: <exception>
Hint
Start from your Watcher.java. The bookmarks come from consumer.committed(new HashSet<>(parts)) inside
onPartitionsAssigned (a partition with none maps to null). commitSync() with no arguments commits the
position after the last poll(): everything that poll returned. Open the file once with
new PrintWriter(new FileWriter(file, true)); the true appends.
Solution
// ~/kafka-groups/sink/OrderSink.java: a group member that processes each order into a file, and commits its
// bookmark the way you tell it to.
// ./run sink/OrderSink.java <group> <name> <file> [commit=auto|after|before] [ms.per.order=5] [setting=value ...]
import java.io.*;
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 OrderSink {
static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
static String name;
static void say(String what) {
System.out.println(LocalTime.now().format(TIME) + " " + name + " " + what);
}
static List<Integer> numbers(Collection<TopicPartition> parts) {
return parts.stream().map(TopicPartition::partition).sorted().toList();
}
public static void main(String[] args) throws Exception {
String group = args[0], file = args[2];
name = args[1];
String commit = "after";
long msPerOrder = 5;
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");
props.put("auto.offset.reset", "earliest"); // a new group starts at the first order
for (String arg : Arrays.copyOfRange(args, 3, args.length)) {
String[] kv = arg.split("=", 2);
if (kv[0].equals("commit")) commit = kv[1];
else if (kv[0].equals("ms.per.order")) msPerOrder = Long.parseLong(kv[1]);
else props.put(kv[0], kv[1]); // any other consumer setting
}
props.put("enable.auto.commit", String.valueOf(commit.equals("auto")));
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(List.of("shop-orders"), new ConsumerRebalanceListener() {
public void onPartitionsRevoked(Collection<TopicPartition> parts) {
say("revoked " + numbers(parts));
}
public void onPartitionsAssigned(Collection<TopicPartition> parts) {
Map<TopicPartition, OffsetAndMetadata> saved = consumer.committed(new HashSet<>(parts));
Map<Integer, Object> from = new TreeMap<>();
for (TopicPartition tp : parts) {
OffsetAndMetadata om = saved.get(tp);
from.put(tp.partition(), om == null ? "none" : om.offset());
}
say("assigned " + numbers(parts) + " bookmarks " + from);
}
});
Thread main = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread(() -> { // Ctrl-C: finish the batch, commit, leave
consumer.wakeup();
try { main.join(); } catch (InterruptedException e) { }
}));
long second = System.currentTimeMillis() / 1000;
int count = 0;
long total = 0;
try (PrintWriter out = new PrintWriter(new FileWriter(file, true))) {
while (true) {
ConsumerRecords<String, String> batch = consumer.poll(Duration.ofMillis(100));
if (commit.equals("before") && !batch.isEmpty()) {
consumer.commitSync(); // the bookmark moves first: at-most-once
}
for (ConsumerRecord<String, String> r : batch) {
Thread.sleep(msPerOrder); // "processing" the order
out.println(r.value() + " " + r.partition() + " " + r.offset());
out.flush();
count++;
total++;
}
if (commit.equals("after") && !batch.isEmpty()) {
consumer.commitSync(); // the whole batch is done: at-least-once
}
long now = System.currentTimeMillis() / 1000;
if (now != second) {
say("processed " + count + " (total " + total + ")");
second = now;
count = 0;
}
}
} catch (WakeupException e) {
if (!commit.equals("auto")) consumer.commitSync(); // auto: close() commits
say("leaving the group");
} catch (Exception e) {
say("stopped: " + e);
} finally {
consumer.close();
}
}
}
Task 2 · Kill it mid-batch: auto-commit, then commit after
Predict first: you kill the member with
docker kill(no Ctrl-C, noclose(): a crash) and start it again. Withcommit=autoand withcommit=after, does it repeat orders, lose some, or both?
In terminal 1:
NAME=a1 ./run sink/OrderSink.java sink-auto a1 sink/auto-1.txt commit=auto session.timeout.ms=10000
When its total passes about 4,000, in terminal 2:
docker kill kcg-run-a1
Start it again in terminal 1, writing to a second file:
NAME=a1 ./run sink/OrderSink.java sink-auto a1 sink/auto-2.txt commit=auto session.timeout.ms=10000
Why session.timeout.ms=10000: the killed member is still in the group until its session times out (lesson 4),
and the new one waits for it: 10 s instead of 45.
A few processed 0 (total 0) lines while it waits, then:
08:08:49.456 a1 assigned [0, 1, 2, 3, 4, 5] bookmarks {0=2000, 1=0, 2=0, 3=0, 4=0, 5=2000}
08:08:52.069 a1 processed 500 (total 500)
The bookmarks are where the dead member last committed (here 4,000 orders, on partitions 0 and 5; yours will
differ). Totals move a batch
(max.poll.records, 500) at a time. Once it prints processed 0 after its orders, it has caught up:
Ctrl-C. Count all lines, then the distinct orders:
cat sink/auto-*.txt | wc -l
cut -d' ' -f1 sink/auto-*.txt | sort -u | wc -l
12019
12000
All 12,000 orders, 19 of them twice: the kill came 19 orders into a batch, after the commit of the 4,000 before it, so the restart did those 19 again. Your count of repeats depends on where in the batch your kill lands; what must match is 12,000 distinct orders, none missing.
Now the same three steps with commit=after: group sink-after, name f1, files sink/after-1.txt and
sink/after-2.txt, and docker kill kcg-run-f1.
What you see
Here the restart began at bookmarks {0=0, 1=2000, 2=0, 3=0, 4=2000, 5=0}, and the counts were 12018 and 12000:
the same story, 18 repeats, nothing lost (yours will differ, but not the 12000): both are at-least-once. Auto-commit’s repeats can be larger, since it
commits at most every auto.commit.interval.ms (5 s, lesson 3).
Task 3 · Too slow, then tuned, while you read its lag
Each order now takes 30 ms, and the group allows 10 s between polls:
NAME=s1 ./run sink/OrderSink.java sink-slow s1 sink/slow-1.txt ms.per.order=30 max.poll.interval.ms=10000
08:16:52.736 s1 assigned [0, 1, 2, 3, 4, 5] bookmarks {0=none, 1=none, 2=none, 3=none, 4=none, 5=none}
[kafka-coordinator-heartbeat-thread | sink-slow] WARN org.apache.kafka.clients.consumer.internals.ConsumerCoordinator - [Consumer clientId=s1, groupId=sink-slow] consumer poll timeout has expired. This means the time between subse...
08:17:07.887 s1 stopped: org.apache.kafka.clients.consumer.CommitFailedException: Offset commit cannot be completed since the consumer is not part of an active group for auto partition assignment; it is likely that the consumer wa...
Lesson 4’s failure: 15 s after its poll, the batch done, its commit is refused. Its 500 orders are in
slow-1.txt, and no bookmark says so.
Predict first: which setting do you change, and to what, so that a batch fits in 10 s?
Solution
A batch is up to max.poll.records × 30 ms: 500 × 30 ms = 15 s. max.poll.records=100 makes it 3 s, well inside
10 s. (Raising max.poll.interval.ms past 15 s works too, but every eager rebalance, the default here, then waits for a 15 s batch.)
Start s1 again with max.poll.records=100 added and sink/slow-2.txt: processed 100 every 3 s. In terminal 2,
read the group’s lag twice, about 10 seconds apart:
./kafka kafka-consumer-groups --describe --group sink-slow
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID ...
sink-slow shop-orders 0 0 2000 2000 s1-e008b07e-5f37-4149-ae63-77...
sink-slow shop-orders 1 700 2000 1300 s1-e008b07e-5f37-4149-ae63-77...
sink-slow shop-orders 2 0 2000 2000 s1-e008b07e-5f37-4149-ae63-77...
...
That is the second look. Here the total lag went from 11,700 to 11,300 in 12.4 s, about 32 orders a second, and only one partition moved (yours may be another): one member works through its partitions one batch at a time, each batch from one partition.
Predict first: at this rate, how long until the lag is 0? And with two more members?
Start them in terminals 2 and 3 (the --describe from a fourth):
NAME=s2 ./run sink/OrderSink.java sink-slow s2 sink/slow-3.txt ms.per.order=30 max.poll.interval.ms=10000 max.poll.records=100
NAME=s3 ./run sink/OrderSink.java sink-slow s3 sink/slow-4.txt ms.per.order=30 max.poll.interval.ms=10000 max.poll.records=100
What you see
At 32 a second, 11,300 orders is about 6 minutes. Once the three share the partitions, two each:
sink-slow shop-orders 2 800 2000 1200 s2-88007939-8e14-4c01-81ab-e7...
sink-slow shop-orders 3 100 2000 1900 s2-88007939-8e14-4c01-81ab-e7...
sink-slow shop-orders 4 800 2000 1200 s3-d2dd3322-1910-4bd3-9bb1-20...
sink-slow shop-orders 5 0 2000 2000 s3-d2dd3322-1910-4bd3-9bb1-20...
sink-slow shop-orders 0 100 2000 1900 s1-e008b07e-5f37-4149-ae63-77...
sink-slow shop-orders 1 1800 2000 200 s1-e008b07e-5f37-4149-ae63-77...
Each member does 100 orders every 3 s, about 33 a second, so the three do about 100: 8,400 is about 85 s at that rate. Here the last member finished 96 s after this look: a group is done only when its busiest member is, and s3 still had 1,200 + 2,000 = 3,200.
When all three print processed 0 after their orders, stop them with Ctrl-C and count sink/slow-*.txt as in
task 2: 12500 lines, 12000 distinct. The 500 repeats are the first s1’s batch, processed and never committed.
Task 4 · Break it: an order disappears
A colleague “speeds up” the commit: right after poll(), so a slow batch can’t hold it up. Task 2’s three steps
with commit=before: group sink-before, name b1, files sink/before-1.txt and sink/before-2.txt,
docker kill kcg-run-b1 past 4,000.
Predict first: what do the two counts say this time?
What you see
11507
11507
No order twice, and 493 missing. Your counts and partitions below will differ; what holds is none twice, some missing, all from one partition.
Find out which orders, in this order:
-
The count: fewer than 12,000 distinct, and no error anywhere.
-
Where each partition got to before the kill, the next offset after the last one processed (a partition the first run never reached has no line):
awk '{last[$2] = $3} END {for (p in last) print p, last[p] + 1}' sink/before-1.txt | sort -n0 7 2 2000 3 2000 -
Where the restart began: its
bookmarksline in terminal 1, here{0=500, 1=0, 2=2000, 3=2000, 4=0, 5=0}. Here partition 0 got to offset 7, but its bookmark says 500: the batch was committed before it was processed, and orders at offsets 7 to 499, the 493, were never processed by anyone.
commit=after is the default: leave your OrderSink.java as it is, and run it without commit=before from now on.
Check your work
./lab check p1
It checks the topic and your program, counts your files (a kill and a restart for auto, after and before; no order missing in the after, auto
and slow runs; the before runs are only reported), and then kills your OrderSink itself, 2 s after its
first order in a run of its own, and starts it again: not one order may be missing.
PASS sink/slow-*.txt: every order processed (12,500 lines, 12,000 distinct orders: 500 repeated, 0 missing)
PASS sink/before-*.txt: your before runs
PASS sink/before-1.txt was cut short by a kill, and a restart wrote before-2.txt
info sink/before-*.txt: 11,507 lines, 11,507 distinct orders: 0 repeated, 493 missing
...
PASS the first run was killed partway (1,017 orders processed)
PASS commit=after, killed and restarted: no order missing (12,017 lines, 17 repeated, 0 missing)
27/27 passed
Your counts of repeats and missing orders will differ; the PASS lines must not.
Your files are exactly what an idempotent sink would have to absorb: lesson 3’s Go deeper on making a repeat harmless shows three ways.
Next: that’s the course. The front page lists the lessons, to look anything up again.