Partition Strategy
Partition Strategy
Partition Assignment Methods
1. Key-Based Partitioning:
partition = hash(key) % num_partitions
Same key → Same partition
Guarantees ordering per key
2. Round-Robin:
partition = counter % num_partitions
Even distribution
No ordering guarantee
3. Custom Partitioner:
Business logic determines partition
Flexible but complex
Implementation
// Custom partitioner
public class OrderPartitioner implements Partitioner {
@Override
public int partition(String topic, Object key, byte[] keyBytes,
Object value, byte[] valueBytes, Cluster cluster) {
int numPartitions = cluster.partitionCountForTopic(topic);
// High-priority orders go to dedicated partition
Order order = (Order) value;
if (order.isHighPriority()) {
return 0; // Dedicated partition
}
// Regular orders distributed by customer
return Math.abs(key.hashCode()) % numPartitions;
}
}
// Configuration
props.put("partitioner.class", "com.example.OrderPartitioner");
Partitioning Strategies
| Strategy | Description | Use Case |
|---|---|---|
| Hash-based | hash(key) % partitions | General purpose |
| Range-based | Key ranges to partitions | Time-series data |
| Custom | Business logic | Priority routing |
| Sticky | Affinity to partition | Session data |
Ordering Guarantees
Ordering Guarantees
Within Partition
Partition 0:
[msg0] → [msg1] → [msg2] → [msg3]
↓ ↓ ↓ ↓
Offset 0 Offset 1 Offset 2 Offset 3
Ordering guaranteed within partition!
Across Partitions
Partition 0: [msg0] → [msg2] → [msg4]
Partition 1: [msg1] → [msg3] → [msg5]
NO ordering guarantee across partitions!
msg1 may arrive before msg0
Achieving Global Order
Option 1: Single partition (no parallelism)
Option 2: Use key for entity ordering
Option 3: Sequence numbers in messages
Ordering Examples
# Example 1: User events (ordered by user)
{
"user_id": "123", # Key - ensures ordering per user
"event": "profile_updated",
"timestamp": "2024-01-15T10:00:00Z"
}
# Example 2: Order events (ordered by order)
{
"order_id": "456", # Key - ensures ordering per order
"status": "shipped",
"timestamp": "2024-01-15T10:05:00Z"
}
# Example 3: Global events (no ordering guarantee)
{
"event_type": "system_alert",
"data": {...}
# No key - round-robin to partitions
}
Ordering Trade-offs
| Requirement | Solution | Trade-off |
|---|---|---|
| Entity ordering | Key by entity | Limited parallelism |
| Global ordering | Single partition | No parallelism |
| No ordering needed | Random partitioning | Maximum parallelism |
Rebalancing
Partition Rebalancing
What is Rebalancing?
Trigger: Consumer joins or leaves group
Before:
P0 → C1
P1 → C2
P2 → C3
C4 joins:
P0 → C1
P1 → C2
P2 → C3
P3 → C4 (new partition assigned)
Or:
P0 → C1
P1 → C2
P2 → C3
P3 → C4
Rebalance Strategies
1. Range Assignment:
- Consecutive partitions to consumers
- C0: P0, P1
- C1: P2, P3
2. Round-Robin:
- Distribute evenly
- C0: P0, P2
- C1: P1, P3
3. Sticky:
- Minimize partition movement
- Keep existing assignments
- Only move what's necessary
Rebalance Impact
During Rebalance:
- All consumers pause
- Partitions reassigned
- Offsets may be lost
- Latency spike
Duration: 100ms - few seconds
Reducing Rebalance Impact
// Incremental cooperative rebalancing (Kafka 2.4+)
props.put("partition.assignment.strategy",
"org.apache.kafka.clients.consumer.CooperativeStickyAssignor");
// Benefits:
// - Only affected partitions revoked
// - Non-stop processing continues
// - Faster rebalance
Rebalance Monitoring
def monitor_rebalance(consumer_group):
# Track rebalance events
rebalance_count = get_metric('consumer.rebalance.count')
rebalance_latency = get_metric('consumer.rebalance.latency')
# Alert on frequent rebalances
if rebalance_count > threshold:
alert('Frequent consumer rebalances')
# Alert on long rebalances
if rebalance_latency > 5000: # 5 seconds
alert('Long consumer rebalance')
Best Practices
- Use cooperative rebalancing (Kafka 2.4+)
- Keep heartbeat interval low for fast detection
- Set session timeout appropriately
- Monitor rebalance frequency
- Avoid unnecessary consumer restarts
Practice Problems
Design a scalable Partitions system. Cover high-level architecture, data model, and API design.
Solution
// Complete system design:
// - Functional + Non-functional requirements
// - Capacity estimation
// - Data model (SQL/NoSQL choice)
// - API endpoints
// - Component architecture
// - Scaling strategy
// - Monitoring & reliabilityHow would you scale Partitions to handle 10x the current load? Identify bottlenecks and solutions.
Solution
// Scaling approach:
// 1. Load balancing
// 2. Database sharding/replication
// 3. Cache layer (Redis)
// 4. CDN for static assets
// 5. Async processing (queues)
// 6. Microservices decompositionAnalyze potential failure modes for Partitions and design mitigation strategies.
Solution
// Failure mitigation:
// 1. Redundancy (multi-AZ)
// 2. Circuit breakers
// 3. Retry with backoff
// 4. Dead letter queues
// 5. Health checks
// 6. Graceful degradationQuiz
1. What is the main purpose of partitioning?
2. What ordering guarantee do partitions provide?
3. What triggers partition rebalancing?
4. What happens during rebalancing?
5. How does cooperative rebalancing improve over eager?
Flashcards
Question
What are partition strategies?
Click to reveal answer
Answer
1) Hash-based (by key), 2) Round-robin (even), 3) Custom (business logic), 4) Sticky (affinity)
Question
Ordering guarantee of partitions?
Click to reveal answer
Answer
Ordering guaranteed within partition only. Across partitions, no ordering guarantee.
Question
What is partition rebalancing?
Click to reveal answer
Answer
Reassigning partitions to consumers when consumers join or leave the consumer group
Question
Cooperative vs eager rebalancing?
Click to reveal answer
Answer
Cooperative: only affected partitions revoked, non-stop processing. Eager: all partitions revoked, full pause.
Question
How to achieve entity ordering?
Click to reveal answer
Answer
Use entity ID as partition key - ensures all events for same entity go to same partition
Revision Notes
Key Takeaways
- 1.Partitioning enables parallelism - key determines routing
- 2.Ordering guaranteed within partition only
- 3.Rebalancing occurs on consumer group changes
- 4.Cooperative rebalancing minimizes processing disruption
- 5.Use entity ID as key for entity-level ordering
Interview Tips
- •Explain partition as unit of parallelism
- •Discuss ordering guarantees clearly
- •Compare eager vs cooperative rebalancing
- •Know how to achieve entity-level ordering
Cheat Sheet
Cheat Sheet: Partitions
Partition Strategies
- Hash-based: hash(key) % n
- Round-robin: Even distribution
- Custom: Business logic
- Sticky: Minimize movement
Ordering
- Within partition: Guaranteed
- Across partitions: Not guaranteed
- Global: Single partition only
Rebalancing
- Trigger: Consumer join/leave
- Impact: Processing pause
- Solution: Cooperative rebalancing
Best Practices
- Use entity key for ordering
- Cooperative rebalancing (2.4+)
- Monitor rebalance frequency