Kafka Consumer Groups: Partition Ownership and Rebalancing
System DesignModel answerLast updated
Explain how a Kafka consumer group splits partitions, handles offsets and crashes, scales with consumer count, and behaves during a rebalance.
Context
A payments platform publishes financial events to a Kafka topic that has 3 partitions. A single consumer group reads from this topic and processes each event. You need to explain how the group behaves and how to make it scale and stay correct.
Questions
- Assignment. The group has 5 active consumers subscribed to the 3-partition topic. How are partitions distributed among them, and what state are the two consumers without a partition in?
- Offsets and crashes. Explain what a consumer offset is. If a consumer crashes after it has processed a message but before it commits the offset, what happens to that message once the group rebalances? What configuration and coding practices give you at-least-once processing?
- Scaling. To raise throughput, the team proposes adding more consumers than there are partitions. Would this help? Justify your answer using Kafka's partition ownership model, and mention what you would do instead.
- Rebalancing. Walk through the sequence of events in a partition rebalance. What happens to latency and availability while it runs, and how can the impact be reduced?
Answer in a structured way, with concrete settings and trade-offs. Short code is welcome for the commit logic in question 2.
Hints
Hint 1
Start from one rule: within a group, each partition is read by exactly one consumer at a time, while one consumer may hold several partitions.
Hint 2
An offset marks the next record to read. Ask yourself in which order 'do the work' and 'commit the offset' must happen so that a crash can only cause a repeat, never a loss, and how a handler can tolerate repeats.
Hint 3
For the rebalance, list the triggers first (join, leave, missed heartbeat, poll timeout, metadata change), then the steps (join, leader assigns, sync). Then contrast eager with cooperative and static membership.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core principle
Within a consumer group, the partition is the unit of parallelism. Each partition is owned by exactly one member at a time, while one member can own several partitions. Progress is tracked per partition through committed offsets. All four answers follow from these two facts.
1. Five consumers, three partitions
The group coordinator triggers a rebalance, and the configured assignor (Range, RoundRobin, Sticky, CooperativeSticky) gives each of the 3 partitions to a different consumer. For example:
| Consumer | Partition |
|---|---|
| C1 | P0 |
| C2 | P1 |
| C3 | P2 |
| C4 | none |
| C5 | none |
C4 and C5 are idle but healthy. They remain full group members, send heartbeats, and their poll() returns no records. They act as hot standbys: if C1 dies, the next rebalance can give P0 to C4 without waiting for a new process to start. This is not an error state, but it costs resources and adds rebalance overhead.
2. Offsets and at-least-once
An offset is a record's position within a partition. The committed offset for a (group, partition) pair is the position of the next record to read, stored in the internal __consumer_offsets topic. Committing N+1 means everything up to N is finished.
Crash after processing but before commit:
- The coordinator detects the failure (missed heartbeats or poll timeout) and rebalances.
- The new owner starts from the last committed offset, which is before the message.
- The message is processed a second time.
Nothing is lost, but duplicates are possible, which is the definition of at-least-once.
How to get at-least-once:
- Set
enable.auto.commit=false. - Commit only after the work is durably complete (for instance after the database write).
- Commit pending offsets in the revoke callback so planned handoffs create fewer duplicates.
- Make the handler idempotent. For financial events, dedupe on a unique transaction ID using a unique constraint or an upsert.
Auto-commit pitfall: auto-commit runs on a timer inside poll(). If work is handed to other threads, the offset can be committed before the work finishes. A crash then loses the message (at-most-once), which is unacceptable for payments.
from confluent_kafka import Consumer, KafkaException
def process(msg):
"""Idempotent: INSERT ... ON CONFLICT (txn_id) DO NOTHING."""
def run(bootstrap, group_id, topic):
c = Consumer({
"bootstrap.servers": bootstrap,
"group.id": group_id,
"enable.auto.commit": False,
"auto.offset.reset": "earliest",
"partition.assignment.strategy": "cooperative-sticky",
})
c.subscribe([topic])
try:
while True:
msg = c.poll(1.0)
if msg is None:
continue
if msg.error():
raise KafkaException(msg.error())
process(msg) # 1. work first
c.commit(message=msg, asynchronous=False) # 2. then commit
finally:
c.close() # LeaveGroup triggers a fast rebalance
Committing per message is safest but slowest. In production, commit per processed batch; the guarantee holds as long as the commit always follows the work.
3. Does adding consumers beyond partitions help?
No. Maximum parallelism equals the partition count. With 3 partitions and 10 consumers, 3 work and 7 idle. Throughput does not change, while heartbeat load, rebalance duration and cost grow.
The restriction exists to preserve per-partition ordering: two readers on one partition would race, and a single offset could no longer describe progress.
What to do instead:
- Add partitions to raise the ceiling. Caveat: on keyed topics this changes the key-to-partition mapping, so per-key ordering can break across the change. Over-provision up front where possible.
- Parallelize inside a consumer, for example a worker pool keyed by message key to retain per-key order. Commit only the highest offset below which all work is complete.
- Find the real bottleneck: slow downstream writes, no batching, or fetch settings (
max.poll.records,fetch.min.bytes).
4. Rebalance sequence and impact
Triggers: a member joins, leaves gracefully, misses heartbeats beyond session.timeout.ms, exceeds max.poll.interval.ms, or the subscription/partition count changes.
Eager (classic) protocol:
- The coordinator moves the group into a preparing-rebalance state; members learn of it through heartbeat responses.
- Each member runs its revoke callback, commits, and releases all partitions.
- All members send
JoinGroup; the coordinator picks a leader and sends it the member list. - The leader computes the assignment and returns it via
SyncGroup; the coordinator distributes it. - Members run their assign callback, fetch committed offsets and resume.
Impact:
- Stop-the-world under eager: the whole group pauses, so lag and end-to-end latency spike.
- Detection delay: for a crash, partitions sit idle up to
session.timeout.ms(45 s by default in recent clients) before the rebalance starts. - Duplicates: anything processed after the last commit is replayed.
- Availability: brokers remain up and no data is lost; only consumption stalls. Producers keep writing.
Mitigations:
- Cooperative incremental rebalancing (
CooperativeStickyAssignor): only partitions that must move are revoked. - Static membership (
group.instance.id): restarts within the session timeout cause no rebalance. - Tuned timeouts and processing small enough to stay under
max.poll.interval.ms. - The newer broker-driven protocol (KIP-848, Kafka 4.0), which rebalances incrementally.
Common mistakes
- Claiming extra consumers are "load balanced" onto the same partition.
- Committing before processing, or relying on auto-commit with asynchronous work.
- Assuming at-least-once means no duplicates, and skipping idempotency.
- Forgetting that slow processing can exceed
max.poll.interval.ms, causing the consumer to be kicked out and a needless rebalance. - Saying a rebalance makes data unavailable; it only pauses consumption.