- Create a Kafka topic with 4 partitions
- Produce keyed messages using a Python producer so messages map deterministically to partitions
- Run Python consumers that join the same consumer group and observe rebalancing when consumers join/leave
- Kafka is installed and running on the host used in this demo (
localhost:9092) - Python 3.8+ (or compatible) available
Useful references
1) Create the topic (4 partitions)
Create a topic namedconsumer-rebalancing-demo with 4 partitions and replication factor 1:
localhost:9092.
2) Prepare a Python virtual environment and install kafka-python
Update packages and enable the Python venv module (if needed). Then create and activate a virtual environment and installkafka-python:
A Python virtual environment keeps demo packages isolated from system Python packages. Activate the virtual environment (
source kafka-demo-env/bin/activate) in every terminal you use for this demo.3) Create the producer: producer.py
Createproducer.py and paste the following code. This producer sends 1000 messages and cycles keys through four values so they map across the 4 partitions. Serializers handle None safely.
key-0..key-3 and 4 partitions, the messages will spread across partitions 0–3.
4) Create the consumer: consumer.py
Createconsumer.py and paste the following script. It accepts an optional command-line argument for the consumer group id; if none is provided it uses default-group.
auto_offset_reset='earliest'ensures consumers without committed offsets will read from the beginning of the topic.- Kafka automatically creates consumer groups when a consumer first joins using the provided
group_id. You do not need to pre-create the group.
5) Run consumers and observe rebalancing
Start one consumer in groupconsumer-group-1:
Terminal 1
- Consumer 1 → partition 0
- Consumer 2 → partition 1
- Consumer 3 → partition 2
- Consumer 4 → partition 3
- If you stop one consumer (Ctrl+C), Kafka removes it from the group and immediately triggers another rebalance.
- The partitions previously owned by the stopped consumer will be reassigned to the remaining group members, who will begin receiving messages for those partitions.
Consumer groups enable horizontal scaling of message consumption. The maximum number of active consumers that can consume in parallel in a group is bounded by the number of partitions. With N partitions, up to N consumers in the same group can be actively assigned partitions; additional consumers will remain idle until partitions are freed.
Summary
- Created a topic with 4 partitions.
- Produced keyed messages so they map deterministically to partitions.
- Launched multiple consumers in the same group and observed Kafka rebalancing partition assignments as consumers joined or left.
- With K partitions, up to K consumers can be actively assigned partitions; Kafka automatically rebalances when group membership changes.