Partition Assignment and Rebalancing in Distributed Consumers
System DesignModel answerLast updated
Explain how a distributed message queue assigns partitions to consumers, handles ordering, and recovers from failures through rebalancing.
Distributed Consumer Architecture
You are building a real-time event processing pipeline using a distributed message queue. Your topic has 10 partitions and a consumer group with 4 active consumer instances reading from it.
Questions
1. Partition-to-Consumer Assignment
Explain how the system determines which consumer reads from which partition. What are the implications when the partition count (10) doesn't divide evenly by the consumer count (4)? How does this affect throughput and scaling?
2. Message Ordering
What ordering guarantees does the system provide? Describe scenarios where message order can be disrupted at the consumer level. If your application requires strict global ordering across all events, what approaches would you take?
3. Failure Recovery and Rebalancing
When a consumer instance fails unexpectedly, explain the complete lifecycle of recovering from the failure:
- How does the system detect the failure?
- What happens to progress tracking (offsets)?
- How are orphaned partitions reassigned?
- What ensures the failed consumer cannot interfere after recovery?
Concrete Example
Given partitions P0 through P9 and consumers C1 through C4, describe a reasonable assignment. Then walk through what happens when C4 crashes: detection, reassignment, and stabilization.
Hints
Hint 1
Each partition is assigned to exactly one consumer within a group, but a consumer can handle multiple partitions—think about the math when numbers don't divide evenly
Hint 2
Ordering is only guaranteed within a single partition; events in different partitions can be processed in any relative order
Hint 3
The system must track which consumer owns which partition using generation IDs or epochs to prevent stale consumers from corrupting state after a rebalance
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Distributed Consumer Groups
Core Principle
The fundamental design decision is partition-level assignment: each partition belongs to exactly one consumer in the group at any moment, but each consumer may own multiple partitions. This provides parallelism while maintaining per-partition ordering and avoiding concurrent writes.
1. Partition-to-Consumer Assignment
Assignment Logic
With 10 partitions and 4 consumers, the math is 10 ÷ 4 = 2 remainder 2. A fair assignment gives:
- Two consumers get 3 partitions each
- Two consumers get 2 partitions each
Range assignment (sorted by partition ID):
- C1: P0, P1, P2
- C2: P3, P4, P5
- C3: P6, P7
- C4: P8, P9
Round-robin assignment:
- C1: P0, P4, P8
- C2: P1, P5, P9
- C3: P2, P6
- C4: P3, P7
Implications of Uneven Distribution
Throughput bottleneck: If traffic is uniform across partitions, C1 and C2 handle 50% more load than C3 and C4. The slowest consumer determines group lag, so you lose effective parallelism.
Scaling ceiling: Adding a 5th consumer improves balance (each gets 2 partitions), but adding an 11th consumer leaves one idle—partition count is the hard limit on parallelism.
Design recommendation: Choose partition counts that factor cleanly into expected consumer counts. Powers of two (8, 16, 32) or highly composite numbers (12, 24, 60) work well. Overpartitioning (e.g., 60 partitions for 4–10 consumers) provides flexibility but increases metadata overhead.
2. Message Ordering Guarantees
What Is Guaranteed
Per-partition ordering is strict. Messages within a partition are stored with monotonically increasing offsets and delivered in that sequence to the assigned consumer. This is the foundation of the design.
Cross-partition ordering does not exist. Event at offset 100 in P3 may be processed before or after offset 5 in P7. The system makes no guarantees about relative timing across partitions.
How Order Breaks in Practice
Producer-side issues:
- Without idempotence, retries can reorder batches if multiple requests are in flight
- Changing partition count mid-stream alters the hash function, so a key's new messages route to a different partition than its history
Consumer-side issues:
- Dispatching records from one partition to a thread pool for parallel processing destroys order unless you re-shard by key
- After a crash, replaying from the last committed offset means downstream systems see duplicates, which can appear out of order if the consumer committed after partial processing
- If
max.poll.interval.msis exceeded, the consumer is evicted and another takes over, potentially replaying the same records
Enforcing Global Ordering
Option 1: Single partition. Simple but limits throughput to one consumer's capacity. Acceptable for low-volume control planes or configuration streams.
Option 2: Relax the requirement. Most "global" ordering needs are actually per-entity ordering (per user, per account, per device). Partition by entity ID and you keep parallelism while satisfying the real constraint.
Option 3: Application-level sequencing. Attach a global sequence number at the source. Consumers buffer out-of-order messages and deliver them sorted. This adds latency, memory pressure, and complexity but works when true global order is non-negotiable.
3. Failure Recovery: The Rebalance Protocol
Detection
The system uses a heartbeat mechanism. Each consumer sends periodic heartbeats to a coordinator (typically a designated broker). If heartbeats stop for longer than session.timeout.ms (commonly 45 seconds), the coordinator marks the consumer dead.
Graceful shutdown sends an explicit leave notification, triggering immediate rebalancing. Stalled processing (exceeding max.poll.interval.ms without polling) also triggers eviction, even if heartbeats continue.
Rebalancing Phases
Phase 1: Trigger. The coordinator increments a generation ID (or epoch) and notifies all surviving members that a rebalance is starting.
Phase 2: Revocation.
- Under eager rebalancing, every consumer immediately stops and releases all partitions. The entire group pauses.
- Under cooperative rebalancing, consumers keep partitions that aren't moving and only release those being reassigned.
Phase 3: Rejoin. Surviving consumers send a join request. One member (the first to join) is elected group leader.
Phase 4: Assignment. The group leader computes the new partition assignment using a configured strategy (range, round-robin, sticky, etc.) and sends it back to the coordinator, which distributes it to all members.
Phase 5: Resume. Each consumer fetches the last committed offset for its new partitions from the coordinator's offset store and begins consuming.
Offset Handling
Offsets are stored durably on the broker side, not in the consumer. When C2 takes over P8 from C4, it reads the last committed offset from the coordinator.
At-least-once semantics: Any records C4 processed but didn't commit before crashing will be reprocessed by C2. If exactly-once processing is required, the consumer must use idempotent writes or transactional APIs.
Zombie fencing: If C4 was merely paused (e.g., GC pause) and tries to commit later, the coordinator rejects the commit because it carries a stale generation ID.
Example: C4 Crashes
Before: C1 = P0–P2, C2 = P3–P5, C3 = P6–P7, C4 = P8–P9
After detection and rebalance: 10 ÷ 3 = 3 remainder 1, so the target is 4/3/3.
- Sticky assignment (minimizes movement): C1 keeps P0–P2, C2 keeps P3–P5 and takes P9, C3 keeps P6–P7 and takes P8. Only two partitions move.
- Range assignment (recomputes from scratch): C1 = P0–P3, C2 = P4–P6, C3 = P7–P9. Five partitions move even though only two were orphaned.
Sticky assignment reduces reprocessing and cache churn.
Common Mistakes
Assuming messages, not partitions, are assigned. The assignment is coarse-grained: whole partitions, not individual messages.
Ignoring rebalance pauses. Eager rebalancing stops all consumption for the detection window plus protocol round-trips. Cooperative rebalancing and static membership (pinning consumer IDs) reduce this pain.
Relying on auto-commit. Committing on a timer independent of processing can skip messages (committed but not processed before a crash) or duplicate them (processed but not committed). Manually commit after processing for control.
Overloading max.poll.interval.ms. Setting it too low causes false evictions during legitimate slow processing; too high delays detecting actual crashes.
Complexity and Tradeoffs
Time complexity: Assignment algorithms are O(P + C) to O(P log C). The real cost is operational: detection latency (tens of seconds) and reprocessing overhead.
Space complexity: O(P) metadata per consumer group.
Scalability: Partition count sets the parallelism ceiling. Rebalances become more expensive as C grows, but cooperative protocols and coordinator-side assignment (newer designs) mitigate this.
Reliability: Durable offset storage and generation-based fencing prevent data loss and zombie writes, but at-least-once semantics require idempotent downstream processing.
This architecture balances parallelism, fault tolerance, and ordering in a pragmatic way: strong guarantees within a partition, best-effort fairness across consumers, and fast recovery at the cost of occasional reprocessing.