How Consumer Groups work in aiokafka
masterKafka uses Consumer Groups to allow a pool of processes to divide the work of consuming and processing records. All AIOKafkaConsumer instances sharing the same group_id are part of the same group.
Kafka balances the partitions between all members in the group so that each partition is assigned to exactly one consumer in the group. This provides scalability and fault tolerance:
- Rebalancing: If a process fails, its partitions are reassigned to other consumers. If a new consumer joins, partitions are moved from existing consumers to the new one.
- Scalability: If a topic has four partitions and a group has two processes, each process consumes from two partitions.
Conceptually, a Consumer Group acts as a single logical subscriber made up of multiple processes.
# Process 1
consumer = AIOKafkaConsumer(
"my_topic", bootstrap_servers='localhost:9092',
group_id="MyGreatConsumerGroup" # This enables Consumer Groups
)
await consumer.start()
async for msg in consumer:
print("Process %s consumed msg from partition %s" % (os.getpid(), msg.partition))
# Process 2
consumer2 = AIOKafkaConsumer(
"my_topic", bootstrap_servers='localhost:9092',
group_id="MyGreatConsumerGroup" # Part of the same group
)
await consumer2.start()
async for msg in consumer2:
print("Process %s consumed msg from partition %s" % (os.getpid(), msg.partition))