Consumer groups and offsets
One Spark job reads a topic, but most Kafka readers are ordinary applications, and several copies of the same application share the work through a consumer group. This lesson explains how a group splits partitions, what a rebalance is, how committed offsets and lag work, and why Spark does not use any of this to remember where it is.
Step 4 · Structured Streaming · Bronze · Kafka basics, lesson 2 of 2
On this page
Read first: Kafka in plain words (skip if you know it)
In plain words first
Picture a sorting office with 6 sacks of letters and a team of postal workers. The supervisor gives each sack to exactly one worker, so no letter is sorted twice. With 3 workers, each gets 2 sacks. With 6, one each. With 8, two workers stand around: there are only 6 sacks. When someone goes on a break, the supervisor hands their sacks to the others.
Each worker also writes on a board how far through their sack they are. If someone is replaced, the new worker reads the board and continues from there. In KafkaKafka: A system that stores streams of events in topics, in order within each partition, so many readers can read them, and read them again, at their own pace. Learn more → the sacks are partitionspartition: In Kafka, one ordered slice of a topic, read in order. In Spark, one chunk of a DataFrame's rows, processed as one task. Learn more →, the team is a consumer group, the supervisor is the group coordinator, and the board holds the committed offsetsoffset: The position of a message inside a Kafka partition: 0, 1, 2, ... A stream stores the offsets it has read in its checkpoint. Learn more →.
A group splits the partitions
Consumers that share a group.id form a group. Kafka gives each partition of the topictopic: A named stream of events in Kafka or Pub/Sub, such as "orders". Producers write to it; consumers read from it. Learn more → to exactly one consumer in the group, so together they read every message once. Different groups are independent: the billing group and the analytics group each read all the messages.
| Topic partitions | Consumers in the group | What happens |
|---|---|---|
| 6 | 1 | One consumer reads all 6 partitions |
| 6 | 3 | Each reads 2 partitions: three times the throughput |
| 6 | 6 | One partition each: the most parallel this group can be |
| 6 | 8 | 2 consumers get nothing and sit idle |
So the number of partitions caps how many consumers in a group can do useful work. That is why partition counts are chosen with growth in mind; you can add partitions later, but it moves keys to other partitions (see Kafka in production).
Rebalances
When a consumer joins, leaves or stops responding, the group redistributes the partitions. That is a rebalance. A consumer counts as gone if it stops sending heartbeats for session.timeout.ms (45 seconds by default), or if it does not ask for more messages within max.poll.interval.ms (5 minutes by default), for example because processing one batch took too long.
With the classic protocol, a rebalance can pause the whole group while partitions move. Kafka 4 added a new protocol in which the brokerbroker: One server in a Kafka cluster. Each stores some partitions and serves reads and writes for them. Learn more → plans the assignment and moves partitions a few at a time, so the rest keep working (Kafka 4).
max.poll.interval.ms, which triggerstrigger: The setting that decides when the next micro-batch starts: straight away, on a fixed interval, or once over everything waiting. Learn more → a rebalance, which makes everyone slower. Fetch fewer records per poll (max.poll.records, 500 by default) or speed up the processing.Committed offsets
A consumer saves its position by committing an offset to Kafka (into an internal topic, __consumer_offsets). The committed offset is the next message to read. After a restart or a rebalance, whoever owns the partition continues from there.
- Auto commit is on by default (
enable.auto.commit=true, every 5 seconds). It is easy, but it commits on a timer, not when your work is done. A crash can lose messages that were committed but not yet processed, or repeat ones processed but not yet committed. - Commit after processing (auto commit off, commit yourself once the results are saved) gives at-least-onceat-least-once: No event is lost, but after a failure some can be processed or written twice. Learn more →: nothing is lost, but a crash can repeat a few messages. Delivery guarantees covers how to make those repeats harmless.
- With no committed offset yet,
auto.offset.resetdecides where to start:latest(the default, only new messages) orearliest(everything still kept).
Consumer lag
Laglag: How far a stream is behind: data that has arrived but has not been processed yet. Learn more → is how far a group is behind, per partition: the latest offset in the partition minus the group's committed offset. Kafka ships a tool that shows it:
$ kafka-consumer-groups.sh --bootstrap-server broker:9092 \ --describe --group billing TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG orders 0 1203 1210 7 orders 1 842 9842 9000 orders 2 977 981 4
Partition 1 is 9,000 messages behind while the others are nearly current. That usually means one hot key, or one stuck consumer, not a group that is too small. Lag that keeps growing everywhere means the group cannot keep up: Backpressure shows the arithmetic.
Spark does it differently
A Spark query does not rely on consumer-group commits. The driverdriver: The process that runs your program, plans the work and sends tasks to executors. Learn more → decides which offset range every partition contributes to a micro-batchmicro-batch: One small round of a stream: Spark takes the data that arrived since the last round, processes it like a little batch job, and saves its progress. Learn more → and writes those ranges to the checkpointcheckpoint: In streaming, the folder where Spark records which input it has processed and its state, so a restarted query continues where it stopped. Learn more → before reading. After a crash, the checkpoint, not Kafka, says where to continue. That is what lets Spark re-run a batch on exactly the same messages.
| Plain Kafka consumer group | Spark Structured Streaming | |
|---|---|---|
| Where the position lives | Committed offsets in Kafka | The query's checkpoint |
| Who assigns partitions | The group coordinator, through rebalances | Spark's driver, every micro-batch |
| Group id | You choose it | A new unique id per query by default |
| Where to start the first time | auto.offset.reset | startingOffsets |
| Seeing lag in Kafka tools | Yes | No: read it from the query's progress instead |
Spark's documentation is explicit: the Kafka sourcesource: Where a stream reads from: a Kafka topic, a folder of files, a Delta table. Learn more → does not commit offsets, and you cannot set enable.auto.commit or auto.offset.reset on it. You can force a group id with kafka.group.id (sometimes needed for access control), but two queries sharing one id interfere with each other, so use it with care. To watch a Spark job's lag, use the progress report (Monitoring streams).
Common mistakes
- Adding consumers beyond the partition count — The extra ones sit idle. Add partitions, or make each consumer faster.
- Relying on auto commit for important data — It commits on a timer. Commit after the results are saved.
- Long processing inside the poll loop — Missing max.poll.interval.ms throws the consumer out and causes a rebalance.
- Looking for a Spark job's lag in kafka-consumer-groups — Spark does not commit offsets there. Use the query's progress report.
Key takeaways
- A consumer group gives each partition to exactly one member, so partitions cap a group's parallelism.
- A rebalance redistributes partitions when members join, leave or stall.
- Committed offsets are the group's position; commit after processing for at-least-once.
- Spark keeps offsets in its checkpoint, not in Kafka, which is how it re-runs a batch exactly.
Interview prep
THE QUESTION
"You have a topic with 12 partitions and a consumer group of 20 instances. What happens, and how would you scale further?"
Avoid: "add more consumers to go faster" without noting that a group cannot use more consumers than the topic has partitions.
Follow-ups · answer out loud, then open
Follow-up"What causes a rebalance, and why do frequent rebalances hurt?"
Scenario"Lag is near zero on 11 partitions and 2 million on one. What do you look at?"
Trap"Spark commits its offsets to the consumer group, so kafka-consumer-groups shows its lag."
Check yourself
3 questionsA topic has 4 partitions. A consumer group has 6 members. How many are reading?
Show the answer
4. One partition goes to one member; with 4 partitions only 4 members get work.
With auto commit on, a consumer crashes after the commit but before processing finished. What happens to those messages?
Show the answer
They are skipped: the commit said they were done. Auto commit runs on a timer, so it can commit messages that were never fully processed.
Where does a Spark Structured Streaming query keep its Kafka position?
Show the answer
In its checkpoint. The driver records each batch's offset ranges in the checkpoint before reading them.
Practise this
Interview problems on streaming, graded on hidden tests
Keep going
Up next · new module: Stateful streams · 8 min readWatermarks and late data
Event time vs processing time, how watermarks bound state, and what happens to late rows.
Related lessons
Kafka in plain wordsStructured Streaming · 8 min read
Backpressure and rate limitsStructured Streaming · 9 min read
Delivery guarantees end to end
Previous: Kafka in plain words
Primary sources: Kafka design: the consumer · Consumer configs · Checking consumer position (kafka-consumer-groups) · Spark Kafka integration: Kafka specific configurations