python
import json
import time
import random
import threading
from collections import defaultdict, Counter
from typing import Dict, List, Tuple, Optional
from kafka import KafkaAdminClient, KafkaProducer, KafkaConsumer
from kafka.admin.new_topic import NewTopic
from kafka.errors import KafkaError, TopicAlreadyExistsError
from kafka.partitioner.default import RoundRobinPartitioner
# Optional: For metrics scraping if Prometheus is enabled on brokers
# pip install kafka-python
class PartitionRebalanceHarness:
"""
A rehearsal harness for Kafka partition rebalancing.
Features:
- Synthetic load generation: Producers create uneven load on partitions/brokers.
- Hotspot detection: Monitors leader distribution, consumer lag, and throughput skew.
- Auto-mitigation: Reassigns partitions to balance load across brokers.
Assumptions:
- Kafka cluster with 3+ brokers (e.g., Dockerized via Strimzi or Confluent).
- Topic with 10+ partitions for meaningful rebalancing.
- Run on a machine with network access to Kafka brokers.
Usage:
harness = PartitionRebalanceHarness(bootstrap_servers='localhost:9092', topic='rebalance-test')
harness.create_topic(partitions=20, replication_factor=3)
harness.rehearse_rebalancing(duration_minutes=10, load_threads=10, hotspot_threshold=0.3)
"""
def __init__(self, bootstrap_servers: str, topic: str, client_id: str = 'rebalance-harness'):
self.bootstrap_servers = bootstrap_servers
self.topic = topic
self.admin_client = KafkaAdminClient(
bootstrap_servers=bootstrap_servers,
client_id=client_id + '-admin'
)
self.producer_config = {
'bootstrap.servers': bootstrap_servers,
'client.id': client_id + '-producer',
'acks': 'all',
'enable.idempotence': True,
}
self.consumer_config = {
'bootstrap.servers': bootstrap_servers,
'group.id': 'harness-consumer-group',
'auto.offset.reset': 'earliest',
'enable.auto.commit': False,
}
self.brokers = self._get_broker_ids()
self.num_brokers = len(self.brokers)
print(f"Detected {self.num_brokers} brokers: {self.brokers}")
def _get_broker_ids(self) -> List[int]:
"""Fetch active broker IDs."""
metadata = self.admin_client.describe_cluster()
return [broker.id for broker in metadata.brokers]
def create_topic(self, partitions: int = 20, replication_factor: int = 3, retention_ms: int = 3600000):
"""Create or verify topic with specified partitions."""
topic = NewTopic(
name=self.topic,
num_partitions=partitions,
replication_factor=replication_factor,
topic_configs={'retention.ms': retention_ms}
)
try:
self.admin_client.create_topics([topic])
print(f"Created topic '{self.topic}' with {partitions} partitions.")
except TopicAlreadyExistsError:
print(f"Topic '{self.topic}' already exists.")
time.sleep(2) # Wait for metadata propagation
def generate_synthetic_load(self, duration_sec: int, num_threads: int = 5, skew_factor: float = 0.7) -> None:
"""
Generate synthetic load with skew to create hotspots.
- skew_factor: Fraction of traffic to 20-30% of partitions (hotspots).
"""
def producer_thread(partitioner):
producer = KafkaProducer(**self.producer_config, partitioner=partitioner)
end_time = time.time() + duration_sec
msg_count = 0
while time.time() < end_time:
key = f"key-{random.randint(1, 10000)}"
value = f"payload-{msg_count}-{random.randint(1, 100000)}".encode('utf-8')
producer.send(self.topic, key=key.encode('utf-8'), value=value)
msg_count += 1
time.sleep(0.001) # ~1k msgs/sec per thread
producer.flush()
print(f"Producer thread sent {msg_count} messages.")
# Get partitions
partitions = self._get_topic_partitions()
hot_partitions = random.sample(partitions, max(1, int(len(partitions) * skew_factor)))
print(f"Skewed load to {len(hot_partitions)} hotspot partitions: {hot_partitions}")
threads = []
for i in range(num_threads):
if i < num_threads * skew_factor:
# Skewed partitioner: Prefer hot partitions
class SkewPartitioner:
def __init__(self, hot_pids):
self.hot_pids = hot_pids
def partition(self, key, all_partitions, available):
if random.random() < 0.8:
return random.choice(self.hot_pids)
return RoundRobinPartitioner().partition(key, all_partitions, available)
partitioner = SkewPartitioner(hot_partitions)
else:
partitioner = RoundRobinPartitioner()
t = threading.Thread(target=producer_thread, args=(partitioner,))
t.start()
threads.append(t)
for t in threads:
t.join()
def _get_topic_partitions(self) -> List[int]:
"""Get partition IDs for the topic."""
tp_desc = self.admin_client.describe_topics([self.topic])[0]
return [p.partition for p in tp_desc.partitions]
def detect_hotspots(self, lag_threshold: int = 10000, leader_imbalance_threshold: float = 0.3) -> Dict:
"""
Detect hotspots via:
- Leader imbalance: Broker with > (1 + threshold) * avg leaders.
- Consumer lag skew: Partitions with high lag.
Returns hotspot metrics.
"""
# Leader distribution
leader_count = Counter()
lag_by_partition = {}
partition_leaders = {}
tp_desc = self.admin_client.describe_topics([self.topic])[0]
for p in tp_desc.partitions:
leader_id = p.leader.id
leader_count[leader_id] += 1
partition_leaders[p.partition] = leader_id
avg_leaders = sum(leader_count.values()) / len(leader_count)
hotspots = {
'leader_imbalance': {},
'high_lag_partitions': [],
'broker_leader_count': dict(leader_count),
'avg_leaders_per_broker': avg_leaders
}
# Check imbalance
for broker, count in leader_count.items():
if count > avg_leaders * (1 + leader_imbalance_threshold):
hotspots['leader_imbalance'][broker] = {
'count': count,
'imbalance_ratio': count / avg_leaders
}
# Consumer lag (quick snapshot)
consumer = KafkaConsumer(**self.consumer_config)
consumer.assign([f"{self.topic}-{pid}" for pid in partition_leaders])
time.sleep(1) # Stabilize
for tp in consumer.assignment():
try:
lag = consumer.end_offsets([tp])[0].offset - consumer.position(tp)
lag_by_partition[tp.partition] = lag
if lag > lag_threshold:
hotspots['high_lag_partitions'].append({
'partition': tp.partition,
'leader': partition_leaders[tp.partition],
'lag': lag
})
except KafkaError:
pass
consumer.close()
print(f"Hotspot detection: {json.dumps(hotspots, indent=2)}")
return hotspots
def auto_mitigate(self, dry_run: bool = False) -> Optional[Dict]:
"""
Auto-rebalance partitions to even out leaders.
- Moves leaders from hot brokers to cold ones.
"""
hotspots = self.detect_hotspots()
if not hotspots['leader_imbalance']:
print("No leader imbalance detected. Skipping mitigation.")
return None
partitions = self._get_topic_partitions()
current_assignments = self._get_current_replicas()
# Simple strategy: Evenly distribute leaders
target_leaders_per_broker = len(partitions) // self.num_brokers
hot_brokers = list(hotspots['leader_imbalance'].keys())
cold_brokers = [b for b in self.brokers if b not in hot_brokers]
new_replicas = {}
for partition in partitions:
# Prefer cold brokers for leaders
if cold_brokers:
new_leader = random.choice(cold_brokers)
else:
new_leader = random.choice(self.brokers)
new_replicas[partition] = [
new_leader,
*[random.choice(self.brokers) for _ in range(2)] # RF=3 example
]
if dry_run:
print("DRY RUN: Proposed reassignments:", json.dumps(new_replicas, indent=2))
return new_replicas
# Execute reassignment
reassign_spec = {self.topic: new_replicas}
print("Executing partition reassignment...")
self.admin_client.alter_partition_reassignments(reassign_spec)
wait_time = 0
while wait_time < 60: # Poll for 1 min
status = self.admin_client.describe_reassignment_status({self.topic: list(partitions)})
if not status:
print("Reassignment completed.")
break
time.sleep(5)
wait_time += 5
else:
print("Reassignment ongoing or failed.")
return new_replicas
def _get_current_replicas(self) -> Dict[int, List[int]]:
"""Helper: Current replica assignments."""
tp_desc = self.admin_client.describe_topics([self.topic])[0]
return {p.partition: [r.id for r in p.replicas] for p in tp_desc.partitions}
def rehearse_rebalancing(self, duration_minutes: int = 5, load_threads: int = 10,
iterations: int = 3, dry_run_mitigate: bool = False):
"""
Full rehearsal loop:
1. Generate skewed load.
2. Detect hotspots.
3. Auto-mitigate.
Repeat for iterations.
"""
cycle_duration = (duration_minutes * 60) // iterations
for i in range(iterations):
print(f"\n--- Iteration {i+1}/{iterations} ---")
self.generate_synthetic_load(cycle_duration, load_threads)
hotspots = self.detect_hotspots()
if hotspots['leader_imbalance'] or hotspots['high_lag_partitions']:
self.auto_mitigate(dry_run=dry_run_mitigate)
else:
print("Balanced - no action needed.")
time.sleep(10) # Stabilize
def cleanup(self):
"""Delete topic for clean slate."""
self.admin_client.delete_topics([self.topic])
print(f"Cleaned up topic '{self.topic}'.")
# Example usage
if __name__ == "__main__":
BOOTSTRAP_SERVERS = 'localhost:9092' # Update to your cluster
TOPIC = 'rebalance-rehearsal'
harness = PartitionRebalanceHarness(BOOTSTRAP_SERVERS, TOPIC)
harness.create_topic(partitions=30, replication_factor=3)
# Run rehearsal (set dry_run_mitigate=True to preview reassignments)
harness.rehearse_rebalancing(duration_minutes=3, load_threads=8, iterations=2)
# Manual detect/mitigate
# hotspots = harness.detect_hotspots()
# harness.auto_mitigate(dry_run=True)
# harness.cleanup()
This harness provides end-to-end rehearsal for production-like partition rebalancing! 🚀