Kafka: Consumer Groups in Depth
Tested 2026-11-30 on Ubuntu 22.04.4 LTS host (Linux 6.8), 4-core Arm Neoverse-N1 (aarch64), 23 GB RAM; Docker Engine 29.1.3 · with Apache Kafka 4.4.0 (apache/kafka:4.4.0, 3 KRaft nodes), kafka-clients 4.4.0, Eclipse Temurin JDK 25.0.5 (eclipse-temurin:25.0.5.1_2-jdk), Docker Engine 29.1.3 · by Vivek Sahu (@viv1) · CC BY 4.0
Your shop sends 200 orders a second to Kafka, and your billing service takes 10 ms to charge each one.
One copy can’t keep up: it was 9,313 orders behind after 80 seconds, and falling further.
Three copies in one consumer group share the work: under 900 behind at each of four checks.
Until a member joins, leaves or restarts. Then the group rebalances, and by default every member stops, all waiting for one busy member: up to one of its batches, 5 s here (in 26 runs, from almost nothing to 4.4 s without an order read).
There are ways to move only what must move, and the bookmark each group keeps has rules of its own: when it is written decides whether a crash bills a customer twice or not at all.
This course is for someone who has produced and consumed messages (the console tools, a simple client) but never looked inside a consumer group. Lesson 1 recaps only what groups rest on: partitions, offsets and the poll loop. Every number here comes from runs on a real three-broker cluster; in the practicals you run the same mechanisms on your own.
By the end you’ll be able to:
- explain, from runs you watched, how a group shares out partitions: the coordinator, the assignors, static membership;
- say what committing an offset guarantees, and where duplicates and lost messages come from, auto-commit included;
- explain why a rebalance pauses consumers, and how eager, cooperative and the new protocol (KIP-848) differ;
- read a group’s lag and tune it in production:
max.poll.interval.ms, session timeouts, and what lag does and doesn’t tell you.
How it works
Each lesson starts with the problem, then an animated picture you step through (press Play, or use the
arrow keys), then the mechanism with real output, and Go deeper sections for the details. Each practical has
you write the Java yourself, as single-file programs run with java File.java: requirements, a hint, a hidden
solution, “predict first” questions, and a part where you break it. One script, ./lab, does the rest:
./lab setup p0starts three Kafka 4.4.0 brokers in Docker containers, on a network of their own, and downloads the Kafka client jars from Maven Central, checking each one’s SHA-256../lab check pNtells you whether your work is right. It only reads your files (and runs your program in a group of its own: once for p0, killed and restarted for p1)../lab reset pNremoves this course’s containers and volumes (only those) and starts them again; your files stay.
All you need is Docker. Java runs in a container too (Eclipse Temurin JDK 25), and nothing is published on a port of your computer. The two images are a 400 MB download, once, and take about 1.4 GB of disk.
Path
| Lesson | Practical | You’ll be able to |
|---|---|---|
| 1 · One topic, many readers | say what a group shares out, what it doesn’t, and what its bookmarks are | |
| 2 · Who gets which partition | 0 · Your cluster and a group you can watch | find a group’s coordinator, and watch eager, cooperative, new-protocol and static rebalances |
| 3 · What a commit really guarantees | say what a crash repeats or skips for each way of committing, and where a group with no bookmark starts | |
| 4 · Consumer groups in production | 1 · Capstone: a consumer you can trust | tell a dead member from a stuck one, read lag, and pick the setting to change; then count what each way of committing repeats and loses when you kill your own consumer |
What your folder will look like
~/kafka-groups/
├── lab the lab script: ./lab setup|check|reset pN (Practical 0)
├── lab.log every command ./lab ran, with its output
├── run ./run File.java: your Java programs, in a JDK container on the course network
├── kafka ./kafka <tool>: Kafka's command-line tools, inside broker kcg-1
├── lib/ kafka-clients 4.4.0 and its logger (./lab setup p0)
├── Watcher.java a member that prints what it owns and reads (Practical 0)
└── sink/ the capstone (Practical 1): empty at first
├── OrderSink.java processes each order into a file, committing as you tell it
└── auto-1.txt ... one file per run: <order number> <partition> <offset> a line
1 · One topic, many readers: why consumer groups exist
In one sentence: a consumer group is a set of consumers that share out a topic’s partitions, so that each partition is read by exactly one member, and that keeps a bookmark per partition so the group carries on where it stopped.
The problem it solves
Your shop writes every order to a Kafka topic called orders, 200 a second. A billing service reads them and
charges each customer. Charging takes 10 ms an order, so one copy of the service can do at most about 100 a
second.
In this course’s run, a consumer that spends 10 ms on each record was 2,259 orders behind after 20 seconds and 9,313 behind after 80: about 118 more every second.
A second copy, as just another consumer, reads every order too: each customer is charged twice. What you need:
- copies that split the orders, each order handled once;
- a copy that restarts carries on where it was;
- a second team (shipping) reading the same orders without taking any from billing.
The idea: share out partitions, keep a bookmark
A topic is already split. orders was created with 6 partitions: six separate, ordered logs. Each record
the producer sends goes into one of them and gets the next number in that partition, its offset (0, 1, 2 …).
A group shares out the partitions, not the records. Consumers that start with the same group.id form a
consumer group. Kafka gives each of the 6 partitions to exactly one member of the group. With two members, each
gets three; with three, two each. A member reads only its own partitions, so no order is read twice inside the group.
topic orders group billing (3 members) group shipping (1 member)
partition 0 ───────▶ b1 s1 reads all 6
partition 1 ───────▶ b1
partition 2 ───────▶ b2
partition 3 ───────▶ b2
partition 4 ───────▶ b3
partition 5 ───────▶ b3
The slow consumer from above, run as three members of one group, was under 900 orders behind at each of four checks, 20 seconds apart (899, 393, 716 and 888): each member had on average a third of the orders, about 67 a second, under its limit of 100.
Groups don’t see each other. shipping gets its own share-out of the same 6 partitions: Kafka doesn’t delete
a record when it’s read, so every group reads everything.
A bookmark per partition. Each group remembers, for each partition, the offset of the next record it should read: the committed offset. A member that restarts asks for it and continues from there. Lesson 3 is all about when that bookmark is written and what that guarantees.
What it rests on
Three pieces you use without seeing them:
| Piece | What it is |
|---|---|
| The poll loop | A consumer calls poll() over and over; each call returns the next records from its partitions. Joining, leaving and committing happen inside those calls. |
| The group coordinator | One broker per group keeps its member list and hands out partitions (lesson 2). |
__consumer_offsets | The internal topic where coordinators write every group’s bookmarks. |
What it looks like
Six hundred orders, then two members of billing and one of shipping, each printing which partitions it was given
and how much it read (this is the Watcher program you write in Practical 0):
05:12:17.507 b1 assigned [0, 1, 2] now [0, 1, 2]
05:12:18.014 b1 read 296 from [1]
05:12:17.505 b2 assigned [3, 4, 5] now [3, 4, 5]
05:12:18.100 b2 read 304 from [4, 5]
05:12:14.476 s1 assigned [0, 1, 2, 3, 4, 5] now [0, 1, 2, 3, 4, 5]
05:12:15.069 s1 read 600 from [1, 4, 5]
billing split the 600 (296 + 304), and shipping read all 600. The even split was luck: a producer sending
records with no key sticks to one partition until it has sent batch.size bytes there, so this quick burst
landed in only three partitions.
KIP-480 introduced the idea;
since Kafka 3.3 the built-in partitioner works as
KIP-794
describes, also sending less to slower brokers (partitioner.adaptive.partitioning.enable):
orders:0:0
orders:1:296
orders:2:0
orders:3:0
orders:4:296
orders:5:8
b1 owned three partitions but only one had records. A group balances partitions, not work.
After the members stopped, the group still exists, with its bookmarks:
./kafka kafka-consumer-groups --describe --group billing
Consumer group 'billing' has no active members.
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID HOST CLIENT-ID
billing orders 1 296 296 0 - - -
billing orders 4 296 296 0 - - -
billing orders 5 8 8 0 - - -
...
CURRENT-OFFSET is the bookmark, LOG-END-OFFSET the offset the next new record will get, and LAG the
difference: how many records the group has still to read. A new member of billing started next read 0
records: the bookmarks were at the end. A member of a new group, audit, read all 600.
Try it on your computer
Practical 0, after lesson 2, has you start a three-broker cluster with ./lab setup p0, write that Watcher
yourself, and watch a group share out its partitions as members join and leave.
Go deeper: the bookmarks' own topic
__consumer_offsets is an ordinary topic with special settings. On this course’s cluster:
Topic: __consumer_offsets TopicId: VIp08GAvRyiKzMTuVthjwQ PartitionCount: 50 ReplicationFactor: 3 Configs: compression.type=producer,min.insync.replicas=1,cleanup.policy=compact,segment.bytes=104857600,retention.bytes=8388608
(retention.bytes is the lab’s size cap, set on every broker; it applies only to topics that delete old data, not
to a compacted one like this.)
- 50 partitions (
offsets.topic.num.partitions): each group’s bookmarks all go to one of them, picked from the group’s name. Lesson 2 uses that to find the coordinator. - 3 replicas: a copy on each broker, so losing one broker loses no bookmarks.
cleanup.policy=compact: each commit is a record whose key is (group, topic, partition). Compaction keeps only the newest record per key, so the topic stays small however often groups commit.
The topic isn’t there from the start: on the fresh cluster, before orders was even created,
./kafka kafka-topics --list printed nothing at all; after this lesson’s runs it listed __consumer_offsets and
orders. Reference:
Kafka 4.4 broker configs (offsets.topic.*).
Common misunderstandings
- “More consumers always read faster.” Only up to the number of partitions. A partition belongs to one member
of a group: when seven members joined one group on
orders, the seventh was given no partition at all. - “The consumer group is the running processes.” The group outlives them: it lives on the coordinator, with its bookmarks, even with no members, as the describe above shows.
Check yourself
1. Billing runs 4 members on orders (6 partitions). How many partitions does each get?
Two members get 2 and two get 1: every partition has exactly one owner, and 6 doesn't divide by 4. The members
with 2 partitions do twice the work if the orders are spread evenly. Lesson 2 shows which members get which.
2. You stop all of billing for an hour, then start it again. Where does it start reading?
At its bookmarks, the committed offsets: the records produced during that hour are its lag, and it reads them first. Nothing is skipped and nothing done before the stop is read again (as long as the bookmarks were up to date when it stopped: lesson 3).3. Billing and a new fraud-check service both need every order. Same group or different groups?
Different groups. In the same group they would split the partitions, and each would see only part of the orders. In different groups, each gets its own share-out and its own bookmarks.Next: 2 · Who gets which partition: assignment and rebalancing.
2 · Who gets which partition: assignment and rebalancing
In one sentence: one broker, the group’s coordinator, keeps the list of members; whenever it changes, the group rebalances: partitions are taken back and handed out again, either all at once (eager), only the ones that move (cooperative), or member by member, driven by the broker (the new protocol, KIP-848).
The problem it solves
Billing’s members change all the time: deploys restart them, a sale adds some, a machine dies at 3 a.m. Each change moves partitions between members, under two rules: never two owners (an order billed twice) and never unowned for long (its orders wait).
Somebody must decide the new share-out, take partitions from their old owners, and only then give them to the new ones, while the rest of the group keeps working.
The coordinator
The somebody is a broker. Every group has a coordinator: the broker that leads the partition of
__consumer_offsets where the group’s bookmarks go. The partition is picked from the group’s name: the Java hash
of group.id, made positive, modulo the topic’s 50 partitions. On this course’s cluster:
| Group | abs(hash) % 50 | Leader of that partition | Coordinator (--describe --state) |
|---|---|---|---|
| watchers | 17 | broker 3 | kcg-3:9092 (3) |
| billing | 9 | broker 2 | kcg-2:9092 (2) |
| audit | 5 | broker 1 | kcg-1:9092 (1) |
Each member finds its coordinator, then sends it heartbeats, “I’m still here” messages, every
heartbeat.interval.ms (3 s by default).
The classic protocol: join, then sync
The classic protocol is still the Java client’s default in 4.4 (group.protocol = classic in its startup
log). When the member list changes, the coordinator answers each member’s next heartbeat with “rebalance in
progress”, and then:
- Join. Each member sends a JoinGroup request. The coordinator waits until every known member has (re)joined.
- The leader assigns. The coordinator picks one member as the group’s leader and sends it the member list. The leader runs an assignor, a function in the client that maps partitions to members.
- Sync. The leader sends the result back; the coordinator gives each member its partitions.
A member only does steps 1 and 3 from inside poll(). Which assignor runs is the consumer setting
partition.assignment.strategy; the default is [RangeAssignor, CooperativeStickyAssignor], and the group uses
the first one every member lists: range.
Four members, then one leaves
Four members joined, then w2 left:
| Assignor | 4 members | After w2 left | Partitions that changed owner besides w2’s |
|---|---|---|---|
| range | w1 0,1 · w2 2,3 · w3 4 · w4 5 | w1 0,1 · w3 2,3 · w4 4,5 | 1 (partition 4) |
| round-robin | w1 0,4 · w2 1,5 · w3 2 · w4 3 | w1 0,3 · w3 1,4 · w4 2,5 | 3 (0 kept, 2, 3, 4 moved) |
| cooperative-sticky | w1 0,1 · w2 3,4 · w3 2 · w4 5 | w1 0,1 · w3 2,3 · w4 4,5 | 0 |
Range and round-robin start afresh; sticky keeps what each member has where it can.
Eager: everybody stops
Range and round-robin are eager: in the join step every member gives up all its partitions. When w3 joined two members:
05:25:20.005 w1 read 50 from [0, 1, 2]
05:25:20.090 w1 revoked [0, 1, 2] now []
05:25:20.101 w1 assigned [0, 1] now [0, 1]
9 to 14 ms in three runs: short, as both members poll every 100 ms. But the barrier waits for
the slowest member. Make the second member slow (10 ms a record, with a backlog: 500 records
and 5 s per poll()) and w1 sits empty until it rejoins:
03:51:06.566 w1 revoked [3, 4, 5] now []
03:51:07.047 w1 read 55 from [3, 4, 5]
03:51:08.052 w1 read 0 from []
03:51:09.055 w1 read 0 from []
03:51:10.004 w1 assigned [2, 3] now [2, 3]
(A read line counts the second before it.) In 26 runs w1 read nothing for 10 to 4,420 ms: the
“everything pauses” of a rebalance, up to one of the slow member’s 5 s batches (lesson 4).
Cooperative: only what moves
With CooperativeStickyAssignor a member gives up only the partitions that move, and keeps reading the others:
06:34:05.161 w1 revoked [5] now [1, 3]
06:34:05.161 w1 assigned [] now [1, 3]
06:34:06.005 w1 read 36 from [1, 3, 5]
06:34:07.016 w1 read 34 from [1, 3]
The price is a second rebalance: a revoked partition goes to w3 only in a follow-up round, once w1 has let go
(KIP-429).
It came one full heartbeat interval after the revoke: 2,989 to 3,027 ms at the default 3 s (16 runs),
1,001 to 1,012 ms with heartbeat.interval.ms=1000 (three runs). With the slow member’s 5 s batches, the moved
partition waited 10.1 to 15.2 s.
The new protocol: the broker assigns
group.protocol=consumer (KIP-848, on in brokers since Kafka 4.0) removes the barrier. The coordinator
computes the assignment itself (uniform by default, or range) and tells each member, in its own heartbeat
responses, what to give up and what to take.
w3 got its partitions 5,010 to 5,060 ms after joining (14 runs), about one of this protocol’s 5 s heartbeat intervals. A moved partition reached it 0.6 to 4.0 s after its revoke, different in each run; the partitions that stayed were read without a gap.
Static membership: a restart that isn’t a change
In a rolling deploy each restart is a leave and a join: two rebalances per member. Give each member a fixed name,
group.instance.id, and the coordinator keeps its partitions for it until session.timeout.ms runs out
(KIP-345).
w2, killed with docker kill and started again with the same id:
06:19:19.569 w2 assigned [2, 3] now [2, 3]
06:19:20.038 w2 read 439 from [2, 3]
The same two partitions, and no revoked or assigned line on w1 or w3; partitions 2 and 3 were unread until w2
was back. The other side: a static member doesn’t leave even when it stops cleanly. w3, stopped normally, kept
its partitions 30.1 to 31.1 s longer (three runs, session.timeout.ms=30000).
Try it on your computer
Practical 0 · Your cluster and a group you can watch:
write the Watcher behind these outputs, and watch each kind of rebalance on your own cluster.
Go deeper: what the broker knows in the new protocol
In a consumer group the coordinator holds each member’s assignment and an epoch, a counter that goes up
with every new target assignment. --describe --members --verbose shows both, and here they agree:
GROUP CONSUMER-ID HOST CLIENT-ID #PARTITIONS CURRENT-EPOCH CURRENT-ASSIGNMENT TARGET-EPOCH TARGET-ASSIGNMENT
asg-new 9QpM4yOjS42XK5VcWyiUhw /172.19.0.8 w4 2 6 orders:1,3 6 orders:1,3
asg-new zrK2UsJVQLyVL9X74XV2gw /172.19.0.7 w3 2 6 orders:2,5 6 orders:2,5
asg-new DybJvTKkQUucjujUJKCXzA /172.19.0.5 w1 2 6 orders:0,4 6 orders:0,4
During a rebalance a member’s current epoch lags the target until it has revoked and taken what it should. For a
classic group the epoch and target columns are -: only the current assignment is listed, the one the leader member
computed and the coordinator passed on.
The timings belong to the broker too (kafka-configs --describe --all): group.consumer.heartbeat.interval.ms=5000
and group.consumer.session.timeout.ms=45000. uniform spreads partitions evenly and sticks to current owners;
when w2 left asg-new, only w2’s two partitions moved. Docs:
the consumer rebalance protocol in Kafka 4.4,
KIP-848.
Go deeper: moving a running group to another assignor or protocol
The new protocol’s settings live on the broker, and a 4.4 client refuses the old ones:
Exception in thread "main" org.apache.kafka.common.config.ConfigException: partition.assignment.strategy cannot be set when group.protocol=CONSUMER
In a classic group every member must agree. A member whose only assignor is one the group doesn’t use can’t join:
06:37:52.577 w3 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.
That is why the default lists two assignors: a member that lists both can join a range group or a cooperative one,
so you move from eager to cooperative in two rolling restarts (first add CooperativeStickyAssignor to the list,
then remove range).
Classic to consumer needs no second step: the brokers convert a group between the two protocols, an empty one
directly and a running one during a rolling restart where members switch one by one
(group.consumer.migration.policy=bidirectional by default).
Common misunderstandings
- “Static membership makes restarts free.” It avoids the rebalance, not the wait: the restarted member’s partitions are unread until it is back, and a member that really died keeps its partitions until the session timeout.
Check yourself
1. An eager group of 10 members; one of them processes a batch for 40 s between polls. A new member joins. How long can the other nine read nothing?
Up to about 40 s: each gives up all its partitions in the join step, and the coordinator waits for every member to rejoin, which the busy one only does at its nextpoll(). With cooperative rebalancing the nine keep
reading what they keep.
2. You switch a running group from range to CooperativeStickyAssignor by restarting members one at a time with only the new setting. What does the first restarted member see?
An InconsistentGroupProtocolException: the others use range only, so it can't join. List both
assignors in the first rolling restart, then drop range in a second.
3. Two groups, billing and billing-v2. Same coordinator?
Only by chance. The coordinator is the leader of partition abs(hash(group.id)) % 50 of
__consumer_offsets, so different names usually land on different partitions, and often on different
brokers.
Next: Practical 0 · Your cluster and a group you can watch, then lesson 3, on what a commit really guarantees.
3 · What a commit really guarantees
In one sentence: a commit is a record saying “for this partition, read offset N next”; written after the work, a crash repeats work (at-least-once), written before it, a crash skips work (at-most-once), and what is repeated or skipped is whatever lies between the bookmark and the work.
The problem it solves
Billing’s member has fetched 41 orders and billed 23 of them when its machine dies. A new process carries on from the group’s bookmark. If the bookmark was moved past the 41 before billing them, 18 customers are never billed. If it is still before them, 23 customers are billed twice.
Kafka can’t know which of the 41 were billed: only your code knows. What a crash costs is decided by when your code moves the bookmark.
The idea: move the bookmark after the work
Moving the bookmark is a commit. Commit after processing, and a crash repeats at most what was processed since the last commit: at-least-once, nothing lost, some things twice. Commit before processing, and a crash skips what was fetched but not yet done: at-most-once. Most systems choose at-least-once and make a repeat harmless (the second Go deeper).
A commit is a record
Six partitions, 100 records each (offsets 0 to 99), all read by group c-one, which committed after processing:
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID HOST CLIENT-ID
c-one orders 0 100 100 0 - - -
...
c-one orders 5 100 100 0 - - -
The last record processed was 99; the bookmark says 100, the next one to read. It is a record that the group’s
coordinator writes to __consumer_offsets, keyed by group, topic and partition:
{"key":{"type":1,"data":{"group":"c-one","topic":"orders","partition":3}},"value":{"version":4,"data":{"offset":100,"leaderEpoch":0,"metadata":"","commitTimestamp":1796009993539,"topicId":"AyIxLlCeQciYRLorVUm78A"}}}
A newer commit for the same key replaces it. A restarted member, or a new owner after a rebalance, asks for it and starts there.
Auto-commit: every 5 seconds, inside poll()
By default a member commits by itself: enable.auto.commit=true, auto.commit.interval.ms=5000. In three runs of
group c-auto, commits came 4,987 to 5,001 ms apart (plus one as each run closed).
There is no timer behind it. A member that spends 20 s on each batch (500 records, 40 ms each) committed 20,105 to
20,150 ms apart (three runs): auto-commit happens inside poll(), and commits what earlier polls returned. So
it is at-least-once only if your loop processes everything a poll() returned before calling it again (the
KafkaConsumer javadoc
says so); hand records to another thread and a crash can lose them.
Three ways to commit, killed mid-stream
A producer sends 100 orders a second; a member processes them at 10 ms each, writing each order’s partition and
offset to a file. It is killed with docker kill and started again with the same group, three times per way:
| How it commits | Processed twice | Never processed |
|---|---|---|
| auto-commit (the default) | 304, 380, 7 | 0, 0, 0 |
commitSync() after each batch | 23, 20, 8 | 0, 0, 0 |
commitSync() before processing | 0, 0, 0 | 2, 30, 9 |
The kills came at random points, 5 to 14 s in, so compare the columns, not the numbers. Three more auto-commit runs, killed 1.1 to 3.1 s in, before the first commit, each lost about 1,780 orders: there was no bookmark to return to (the next section).
Committing after each batch repeats at most the batch in progress. The first killed run had just fetched 41:
04:10:03.064 m1 processed 71
04:10:03.065 m1 polled 33
04:10:03.404 m1 committed {0=29524, 1=29524, 2=29523, 3=29523, 4=29522, 5=29522} in 3 ms
04:10:03.405 m1 polled 41
Started again, it resumed at that commit and processed 23 of the 41 a second time:
04:10:21.361 m1 assigned [0, 1, 2, 3, 4, 5] committed {0=29524, 1=29524, 2=29523, 3=29523, 4=29522, 5=29522}
...
total: 3232 lines, 23 duplicates, 0 missing
No bookmark yet: auto.offset.reset
When a group has no commit for a partition, auto.offset.reset decides where it starts. On 289,729 records
already in the topic, with nothing being produced:
auto.offset.reset | New group read |
|---|---|
latest (the default) | 0: it waits for new records |
earliest | all 289,729 |
none | nothing: the consumer throws |
04:29:26.118 m1 stopped: org.apache.kafka.clients.consumer.NoOffsetForPartitionException: Undefined offset with no reset policy for partitions: [orders-0, orders-1, orders-2, orders-3, orders-4, orders-5]
It only applies when there is no commit. c-one, started again with earliest, resumed at its bookmark, 100.
commitSync or commitAsync
commitSync() waits for the coordinator’s answer and throws if the commit fails. commitAsync() returns at once
and reports the result to a callback; a failure reaches only that callback. On this machine, committing after
every poll, a commit’s round trip took 1 to 22 ms either way (median 2 ms, three runs each, about
1,450 commits a run); measure on yours. The difference that holds everywhere: only commitSync() stops your loop when a commit
fails.
Commits around a rebalance
In an eager rebalance every member gives up all its partitions, and each new owner, even the old owner getting
one back, starts from the bookmark. Two members, m2 joining m1, then m2 stopping:
| How m1 and m2 commit | Processed twice |
|---|---|
| every 1,000 records | 138, 573, 1,208 |
every 1,000 records, and in onPartitionsRevoked | 0, 0, 0 |
| auto-commit | 0, 0, 0 |
With commits every 1,000 records, each rebalance sent every partition back to its last commit, even m1 getting
its own partitions back: in one run from its commit of 1.6 s before the revoke. In another, the rebalance came
before any commit, so both started at the end of their partitions (latest): 55 orders were never processed.
Committing in onPartitionsRevoked, which the
ConsumerRebalanceListener javadoc
recommends, hands over exactly:
04:24:06.560 m1 committed on revoke {0=43579, 1=43579, 2=43578, 3=43578, 4=43577, 5=43577}
04:24:06.581 m1 assigned [0, 1, 2] committed {0=43579, 1=43579, 2=43578}
04:24:06.599 m2 assigned [3, 4, 5] committed {3=43578, 4=43577, 5=43577}
Auto-commit repeated nothing in its three runs either.
Try it on your computer
The capstone, after lesson 4, has you write a consumer that survives exactly these kills, and count the orders it repeats and loses.
Go deeper: what else a commit holds, and when it expires
The value has more than the offset: leaderEpoch (the partition leader’s epoch of the last record read; 0
in the record above), metadata (a string you may attach to a commit) and commitTimestamp.
Bookmarks don’t last forever. The broker setting offsets.retention.minutes=10080 (7 days) expires a group’s
committed offsets once the group has been empty that long
(broker configs). A member that comes back after
that has no bookmark, and auto.offset.reset decides again: with latest, everything produced while it was away
is skipped.
Go deeper: making a repeat harmless
At-least-once plus an effect that can be repeated safely gives the result of exactly-once:
- Idempotent writes: key the result by partition and offset (or by an order id), so writing it again overwrites instead of adding. The file in the runs above could be deduplicated that way.
- Bookmark and result together: store the offset in the same database transaction as the result, and on
onPartitionsAssignedseek()to it instead of using Kafka’s commit. - Kafka to Kafka: a transactional producer can commit the consumer’s offsets in the same transaction as the
records it writes (
sendOffsetsToTransaction, KIP-98).
None of the three is measured in this course.
Common misunderstandings
- “commitSync() gives exactly-once.” It is still after the work: a crash repeats the batch in progress.
- “Auto-commit loses messages.” Not when every record is processed inside the poll loop (0 missing in the
three runs killed after a commit). It loses them when work leaves the loop, or when there is no commit yet and
latestapplies. - “
earliestmakes my group re-read the topic.” Only a group, or partition, with no commit.
Check yourself
1. A member auto-commits every 5 s and processes 100 orders a second. It is killed. About how many orders can be processed twice?
Up to about 500, the work of one 5 s interval: the commit can be up to 5 s behind. The runs above repeated 7 to 380.2. Sending a payment twice is far worse than missing one, which a nightly job catches. When should the payment consumer commit?
Before sending: at-most-once. A crash then skips the payments in progress (2 to 30 in the runs above) and never repeats one.3. A new group is deployed with the defaults, crashes 2 s after it starts, and comes back a minute later. What did it miss?
Probably everything produced in that minute: with no commit yet,auto.offset.reset=latest starts it
at the end of each partition. The runs above lost about 1,780 orders each that way. Set earliest for a group that
must see everything from its first day.
Next: 4 · Consumer groups in production: how the group decides a member is gone, and how to read lag.
4 · Consumer groups in production
In one sentence: a group judges each member by two clocks, heartbeats (is the process alive?,
session.timeout.ms) and polls (is it making progress?,max.poll.interval.ms), and you judge the group by one number, lag: how far its bookmarks are behind the end of each partition.
The problem it solves
At 3 a.m. billing’s lag alert fires. The members are “running”, but is one of them dead, stuck in a slow batch, or just too slow for the traffic? Each has a different fix.
The idea: alive, and making progress
A member is one process doing two things, and the group checks each:
member process
├── heartbeat thread ── "still here", every heartbeat.interval.ms ──► coordinator
│ silent for session.timeout.ms = dead
└── your poll loop ── poll(), process the batch, poll() ...
no poll() for max.poll.interval.ms = stuck
In the classic protocol the heartbeats come from a background thread (kafka-coordinator-heartbeat-thread in the
client’s log), so a member busy in a long batch still heartbeats. Defaults: heartbeats every 3 s,
session.timeout.ms=45000, max.poll.interval.ms=300000 (5 minutes), max.poll.records=500.
Dead: session.timeout.ms
Three members, a producer running, then one is killed with docker kill (three or four runs each):
| The killed member | Its partitions went to the others after |
|---|---|
classic, session.timeout.ms=10000 | 9.8 to 12.2 s |
| classic, the default 45 s | 43.3 to 43.8 s |
classic, static (group.instance.id), session.timeout.ms=30000 | 29.8 to 30.8 s |
new protocol (group.protocol=consumer) | 40.7 to 44.4 s for one partition, 44.4 to 46.9 s for the other |
Each is the session timeout, give or take a few seconds. The static member stays on the member list until its
timeout runs out: 12 s after the kill, --describe --members still listed it with its 2 partitions, unread: the
price of lesson 2’s rebalance-free restart.
The new protocol’s session timeout belongs to the broker, and the client refuses its own:
Exception in thread "main" org.apache.kafka.common.config.ConfigException: session.timeout.ms cannot be set when group.protocol=CONSUMER
A lower timeout moves a dead member’s partitions sooner, but a healthy member silent for longer than it (a long garbage-collection pause, a network blip) is thrown out too.
Stuck: max.poll.interval.ms
Member m1 processes each record in 30 ms, so a batch of 500 takes 15 s, with max.poll.interval.ms=10000. A
second member, m2, joins:
03:46:07.028 m1 polled 500
...
03:46:17.062 [kafka-coordinator-heartbeat-thread | pi-2] WARN org.apache.kafka.clients.consumer.internals.ConsumerCoordinator - [Consumer clientId=m1, groupId=pi-2] consumer poll timeout has expired. ...
...
03:46:22.203 m1 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 was kicked out of the group.
About 10 s after its poll (9.99 to 10.05 s, three runs), the client itself sent LeaveGroup; m2 got all six partitions 27 to 55 ms later:
03:46:17.102 m2 assigned [0, 1, 2, 3, 4, 5] now [0, 1, 2, 3, 4, 5]
When m1 finished its batch, its commit failed: CommitFailedException means “you were thrown out for not
polling”. Its 500 records were processed and never committed, so they will be processed again. A version that
catches the exception and polls again rejoins within a second, and the group rebalances again. (A static member over
max.poll.interval.ms keeps its partitions until the session timeout instead,
consumer configs.)
The fix: smaller batches
The time between two polls is about max.poll.records × the time per record: 500 × 30 ms = 15 s above. Raise
max.poll.interval.ms to more than the slowest batch, or lower max.poll.records.
Smaller batches also shorten eager rebalances, which wait for the slow member (lesson 2). At 10 ms per record a batch is 5 s at 500 and 0.5 s at 50; another member sat empty for:
Slow member’s max.poll.records | Empty time, 11 runs |
|---|---|
| 500 | 10 to 4,282 ms |
| 50 | 233 to 419 ms |
It varies from run to run, and stays under one batch.
Reading lag
kafka-consumer-groups --describe shows, per partition, the bookmark (CURRENT-OFFSET), the end of the partition
(LOG-END-OFFSET), their difference (LAG), and who owns it. A member that processes at most 100 records a second,
with 200 a second produced:
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID HOST CLIENT-ID
lag-3 orders 0 20313 20429 116 c1-59b927c6-70d9-41d0-93e4-74b31f805207 /172.21.0.5 c1
...
lag-3 orders 5 20310 20426 116 c1-59b927c6-70d9-41d0-93e4-74b31f805207 /172.21.0.5 c1
| Members | Total LAG, one run | Change, three runs |
|---|---|---|
| 1 | 699, then 7,181 60 s later | +96 to +108 a second |
| 3 | 8,207, then 5,173 33 s later | −80 to −118 a second |
| 3, producer stopped | 2,895, then 0 within 15 s | the same in each run |
Lag counts records, not time. That run’s highest, 8,849, is 44 s of production at 200 a second, and about 88 s to zero at 100 a second. Steady lag is a group keeping up; lag growing everywhere, a group too slow for its input.
With no members, --describe says the group “has no active members”, shows - as the owner, and still lists
the bookmarks and the lag.
Group states
--describe --state shows the group’s state. These runs saw:
| Protocol | States seen | Meaning |
|---|---|---|
| classic | Stable, PreparingRebalance, Stable | PreparingRebalance: waiting for all members to rejoin; then CompletingRebalance (too short to catch): waiting for the assignment |
| consumer | Stable, Reconciling, Stable, Assigning | Assigning: a new target assignment is being computed; Reconciling: members are moving to it (about 5 s when w3 joined) |
| both | Empty | no members; the bookmarks are kept |
Meanings: KIP-345 and KIP-848; the full list: GroupState.
A debugging checklist
| What you see | Look at | Usually |
|---|---|---|
| Lag growing on every partition, group Stable | the members’ processing rate | too slow for the input: speed up processing, or add members (up to the partition count) |
“consumer poll timeout has expired”, CommitFailedException | time per batch | a batch slower than max.poll.interval.ms: lower max.poll.records |
| State keeps going to PreparingRebalance | members joining and leaving | the poll timeout above, or members restarting: static membership (lesson 2) |
| Partitions unread for about 45 s after a crash | session.timeout.ms | its default, 45 s |
| Records processed twice after a deploy | where you commit | commits missing in onPartitionsRevoked (lesson 3) |
Try it on your computer
The capstone, next, has you tune a consumer that falls past max.poll.interval.ms, and read its lag while it
catches up.
Go deeper: the new protocol's timeouts live on the broker
In a consumer group the broker sets the heartbeat interval and the session timeout for every member:
group.consumer.heartbeat.interval.ms=5000 and group.consumer.session.timeout.ms=45000, within the bounds
group.consumer.min.session.timeout.ms=45000 and group.consumer.max.session.timeout.ms=60000. So out of the
box, a dead member’s partitions wait about 45 s (40.7 to 46.9 s above).
The slow member above, in a consumer group, got the poll timeout warning 14.7 to 14.9 s after each poll (three
runs), its commit failed with “unknown member ID”, and it rejoined 0.1 s later, with partitions 0-2 in 7 of its 8
rejoins. It never committed: batch after batch, about 15 s apart.
One group can have its own values, set as group configs (consumer.session.timeout.ms,
consumer.heartbeat.interval.ms, group configs) with
kafka-configs --entity-type groups; this course doesn’t run that. max.poll.interval.ms and
max.poll.records stay client settings in both protocols.
Common misunderstandings
- “Zero lag means nothing is lost.” Lag compares the bookmark with the end of the partition. A member that commits before processing (lesson 3) shows zero lag over orders it never processed.
Check yourself
1. Each record takes 50 ms and max.poll.records is 500, with the other defaults. Safe? And when the database behind it slows to 1 s per record?
At 50 ms a batch takes 25 s, well under the 5 minutes of max.poll.interval.ms. At 1 s per record it
takes 500 s: the member is thrown out mid-batch, its commit fails, and the batch is processed again. Lower
max.poll.records, or raise max.poll.interval.ms past the slowest batch you expect.
2. A group's lag is 6,000 and falls by about 100 a second. Is it healthy?
It is catching up: about 60 s to zero if the rate holds. The worrying case is the opposite trend, lag that grows on every partition.3. A static member's machine dies, with session.timeout.ms=30000. What happens to its partitions?
Nothing for about 30 s: the member is still listed and its partitions are unread (29.8 to 30.8 s in the runs
above). Then
they go to the others.
Next: Practical 1 · Capstone: a consumer you can trust.
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.
Next: 3 · What a commit really guarantees.
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.