This guide demonstrates Kafka consumer rebalancing through creating a topic, producing messages with Python, and observing automatic partition redistribution.
This guide walks you through a hands-on demonstration of Kafka consumer rebalancing. You’ll create a topic, produce messages with Python, and observe how consumer groups automatically redistribute partitions when members join or leave.
from kafka import KafkaProducerimport time, randomproducer = KafkaProducer( bootstrap_servers=['localhost:9092'], key_serializer=lambda k: k.encode('utf-8'), value_serializer=lambda v: v.encode('utf-8'))topic = 'consumer-rebalancing-demo'for i in range(1000): # Random key in {0,1,2,3} ensures messages are spread across all partitions key = str(random.randint(0, 3)) value = f'Message-{i}' producer.send(topic, key=key, value=value) print(f'Produced: {value} (key={key})') time.sleep(0.5) # throttle for demonstrationproducer.close()
(kafka-demo-env) root@kafka-host ~# python3 consumer.py group-1Consumer group-1 starting...[group-1] Received Message-0 from partition 1, key=1[group-1] Received Message-1 from partition 3, key=3...
With only one member, it reads from all four partitions (0–3).
You’ve now seen how Kafka consumer groups distribute topic partitions among consumers and automatically rebalance when members join or leave. This ensures high throughput and fault tolerance for your streaming applications.