StackPractices
advanced By Mathias Paulenko

Kafka Consumer Groups with Python for Scalable Streaming

Create Kafka consumer groups in Python with partition assignment, offset management, rebalance handling, and exactly-once semantics using confluent-kafka.

Topics: messaging

Kafka consumer groups split a topic’s partitions across worker processes so you can scale reads horizontally while keeping order inside each partition. This recipe builds them with confluent-kafka — manual offset commits, rebalance callbacks, batch consumption, and a correct exactly-once pipeline that ties input offsets to output messages in one transaction.

When to Use

  • High-throughput event streaming where one process can’t keep up — click streams, IoT telemetry, financial events.
  • Pipelines where several independent consumers must each see every message — analytics plus database sync plus alerting.
  • Workloads that need per-key ordering: all events for one userId processed sequentially, without serializing the whole topic.
  • Teams already running Kafka who want a Python client built on librdkafka — the same C library behind the official clients — rather than a pure-Python implementation.

If you only need a task queue where each message goes to one worker, a consumer group still works, but RabbitMQ with pika has a simpler mental model — no offsets, no rebalances.

Prerequisites

  • Python 3.10+
  • A reachable Kafka cluster (local Docker, or a managed one like Confluent Cloud)
  • pip install confluent-kafka (v2.x — transaction support included)

Solution

A consumer group is just several processes sharing a group.id. Kafka assigns each partition to exactly one member; when members join or leave, the group rebalances and partitions move. The diagram shows a three-partition topic shared by two consumers, and what happens when a third one joins.

flowchart diagram: subgraph T[

1. Basic Consumer Group

from confluent_kafka import Consumer, KafkaError
import json

def create_consumer(group_id: str, servers: str = 'localhost:9092'):
    conf = {
        'bootstrap.servers': servers,
        'group.id': group_id,
        'auto.offset.reset': 'earliest',
        'enable.auto.commit': False,  # manual commits tie the offset to processing
        'partition.assignment.strategy': 'cooperative-sticky',
    }
    return Consumer(conf)

def consume_messages(consumer: Consumer, topic: str):
    consumer.subscribe([topic])

    try:
        while True:
            msg = consumer.poll(timeout=1.0)

            if msg is None:
                continue
            if msg.error():
                if msg.error().code() == KafkaError._PARTITION_EOF:
                    continue  # reached the end of the partition — normal
                print(f"Consumer error: {msg.error()}")
                continue

            key = msg.key().decode('utf-8') if msg.key() else None
            value = json.loads(msg.value().decode('utf-8'))

            print(f"Topic={msg.topic()}, Partition={msg.partition()}, "
                  f"Offset={msg.offset()}, Key={key}")

            process_event(value)
            consumer.commit(msg)  # offset moves only after the event is done

    except KeyboardInterrupt:
        print("Stopping consumer...")
    finally:
        consumer.close()

consumer = create_consumer('order-processors')
consume_messages(consumer, 'orders')

The _PARTITION_EOF error isn’t a failure — it just means the consumer caught up with the partition head, and it arrives periodically on low-traffic topics. enable.auto.commit: False is the setting that matters most: committing per message is safe but chatty, so the batch example below shows the throughput-friendly version.

2. Producer with Key-Based Partitioning

from confluent_kafka import Producer
import json

def create_producer(servers: str = 'localhost:9092'):
    return Producer({
        'bootstrap.servers': servers,
        'acks': 'all',
        'enable.idempotence': True,
    })

def delivery_report(err, msg):
    if err:
        print(f"Delivery failed: {err}")
    else:
        print(f"Delivered to {msg.topic()} [{msg.partition()}] at offset {msg.offset()}")

def produce_event(producer: Producer, topic: str, key: str, value: dict):
    producer.produce(
        topic=topic,
        key=key.encode('utf-8'),  # same key → same partition → ordered per key
        value=json.dumps(value).encode('utf-8'),
        callback=delivery_report,
    )
    producer.poll(0)  # serve delivery callbacks without blocking

producer = create_producer()
produce_event(producer, 'orders', 'user-123', {'orderId': 'o1', 'userId': 'user-123'})
produce_event(producer, 'orders', 'user-456', {'orderId': 'o2', 'userId': 'user-456'})
producer.flush()

acks='all' waits for every in-sync replica before reporting success; combined with enable.idempotence it covers both durability and duplicate suppression on retries. Calling producer.poll(0) periodically is required — delivery callbacks only fire while you’re inside poll() or flush().

3. Rebalance Handling

from confluent_kafka import Consumer, TopicPartition

def on_assign(consumer, partitions):
    print(f"Partitions assigned: {partitions}")
    # Optional: seek to offsets loaded from an external store
    # for consumers that track position outside Kafka.

def on_revoke(consumer, partitions):
    print(f"Partitions revoked: {partitions}")
    # Commit current positions before losing ownership,
    # or the next assignee replays this partition's tail.
    consumer.commit(asynchronous=False)

def on_lost(consumer, partitions):
    print(f"Partitions lost: {partitions}")
    # Fired when the group already reassigned them — just clean up.

def create_resilient_consumer(group_id: str):
    conf = {
        'bootstrap.servers': 'localhost:9092',
        'group.id': group_id,
        'auto.offset.reset': 'earliest',
        'enable.auto.commit': False,
        'partition.assignment.strategy': 'cooperative-sticky',
        'on_assign': on_assign,
        'on_revoke': on_revoke,
        'on_lost': on_lost,
    }
    return Consumer(conf)

consumer = create_resilient_consumer('order-processors')
consumer.subscribe(['orders'])

The difference between on_revoke and on_lost matters in failure handling: revoke is a cooperative handoff where you still own the partition and can commit; lost means the group already gave it away, so any commit attempt would fail or write offsets for a partition you no longer control. With cooperative-sticky, revocations are incremental — only the partitions that must move are revoked, so in-flight work on the rest is untouched.

4. Batch Processing with Manual Offset

from confluent_kafka import Consumer
import json
from collections import defaultdict

def consume_batch(consumer: Consumer, topic: str, batch_size: int = 100, timeout: float = 5.0):
    consumer.subscribe([topic])
    messages = []

    while True:
        msg = consumer.poll(timeout=timeout)

        if msg is None:
            if messages:
                process_batch(messages)
                consumer.commit(asynchronous=False)  # flush on idle
                messages = []
            continue

        if msg.error():
            continue

        messages.append({
            'topic': msg.topic(),
            'partition': msg.partition(),
            'offset': msg.offset(),
            'key': msg.key().decode('utf-8') if msg.key() else None,
            'value': json.loads(msg.value().decode('utf-8')),
        })

        if len(messages) >= batch_size:
            process_batch(messages)
            consumer.commit(asynchronous=False)
            messages = []

def process_batch(messages: list):
    # Group by partition — ordering guarantees apply per partition.
    by_partition = defaultdict(list)
    for msg in messages:
        by_partition[(msg['topic'], msg['partition'])].append(msg)

    for (topic, partition), msgs in by_partition.items():
        print(f"Processing {len(msgs)} messages from {topic}[{partition}]")
        for msg in msgs:
            process_event(msg['value'])

Committing per message costs a round-trip to __consumer_offsets every time; committing per batch amortizes it. The trade-off is replay window: if the consumer dies mid-batch, everything since the last commit comes back. That window is why idempotent processing matters even outside transactions.

5. Exactly-Once Semantics (Transactional)

from confluent_kafka import Consumer, Producer, TopicPartition
import json

class ExactlyOnceProcessor:
    def __init__(self, input_topic: str, output_topic: str, group_id: str):
        self.consumer = Consumer({
            'bootstrap.servers': 'localhost:9092',
            'group.id': group_id,
            'auto.offset.reset': 'earliest',
            'enable.auto.commit': False,
            'isolation.level': 'read_committed',
        })

        self.producer = Producer({
            'bootstrap.servers': 'localhost:9092',
            'transactional.id': f'{group_id}-txn-0',  # unique per instance, stable across restarts
            'enable.idempotence': True,
        })

        self.input_topic = input_topic
        self.output_topic = output_topic

    def start(self):
        self.producer.init_transactions()
        self.consumer.subscribe([self.input_topic])

        try:
            while True:
                msg = self.consumer.poll(1.0)
                if msg is None or msg.error():
                    continue

                self.producer.begin_transaction()

                try:
                    result = process_event(json.loads(msg.value().decode('utf-8')))

                    self.producer.produce(
                        self.output_topic,
                        value=json.dumps(result).encode('utf-8'),
                    )

                    # Commit the consumed offset inside the transaction —
                    # atomic with the output message.
                    self.producer.send_offsets_to_transaction(
                        [TopicPartition(msg.topic(), msg.partition(), msg.offset() + 1)],
                        self.consumer.consumer_group_metadata(),
                    )

                    self.producer.commit_transaction()

                except Exception as e:
                    print(f"Transaction failed, aborting: {e}")
                    self.producer.abort_transaction()

        finally:
            self.consumer.close()
            self.producer.flush()

Two details make this real exactly-once rather than transactional produce: send_offsets_to_transaction commits the input offset inside the same transaction as the output, and isolation.level: 'read_committed' on the consuming side hides aborted transactions. Without the offset commit, a crash between produce and commit replays the input and emits a duplicate — which is just at-least-once with extra steps.

One caveat on transactional.id: it must be unique per processor instance. Two live producers sharing an id trigger fencing — the newer one wins, the older one’s transactions get rejected. Derive it from something instance-unique (pod name, worker id) rather than a constant.

6. Running Multiple Consumers in a Group

# consumer_worker.py — run several processes, Kafka assigns partitions
import sys
import json
from confluent_kafka import Consumer

def start_worker(worker_id: str, group_id: str, topic: str):
    consumer = Consumer({
        'bootstrap.servers': 'localhost:9092',
        'group.id': group_id,
        'auto.offset.reset': 'earliest',
        'enable.auto.commit': False,
        'partition.assignment.strategy': 'cooperative-sticky',
    })

    consumer.subscribe([topic])
    print(f"[Worker {worker_id}] Subscribed to {topic}")

    try:
        while True:
            msg = consumer.poll(1.0)
            if msg is None or msg.error():
                continue

            value = json.loads(msg.value().decode('utf-8'))
            print(f"[Worker {worker_id}] P={msg.partition()} O={msg.offset()} — {value.get('id')}")
            process_event(value)
            consumer.commit(msg)
    finally:
        consumer.close()

worker_id = sys.argv[1]
start_worker(worker_id, 'order-processors', 'orders')

# Run in separate terminals:
# python consumer_worker.py worker-1
# python consumer_worker.py worker-2
# python consumer_worker.py worker-3

With 6 partitions and 3 workers, each gets 2 partitions. Add a fourth worker and a cooperative rebalance moves one partition over without stopping the others. Add a seventh and it idles — partition count is the parallelism ceiling.

How It Works

Consumer groups are Kafka’s horizontal-scaling mechanism. Every member of a group subscribes to the same topics; the group coordinator (a broker) assigns partitions so each one has exactly one owner within the group. Two independent groups on the same topic don’t interact at all — each tracks its own offsets, which is how one topic can feed analytics and a database sync simultaneously.

Offsets are per-partition positions persisted to the internal __consumer_offsets topic. A committed offset means “everything before this is done.” Auto-committing writes them on a timer regardless of processing state; manual commits let you decide what “done” means — after one message, after a batch, or inside a transaction.

Rebalances are the group’s reorganization protocol. The default range assignor historically used eager rebalancing: all members stop, all partitions get revoked, everything restarts. cooperative-sticky moves only the partitions that need a new owner, so most members keep processing through the rebalance. During the window between revocation and reassignment, the moved partition simply waits.

Exactly-once is the conjunction of three pieces: enable.idempotence kills produce retries as a duplicate source, transactions make the output write atomic, and send_offsets_to_transaction binds the input position to that same transaction so a crash can never split “input consumed” from “output produced.”

Variants

Windowed Aggregation with Faust

# pip install faust-streaming — Faust gives you Streams-like
# stateful processing (tables, windows) in Python.

import faust

app = faust.App('order-aggregator', broker='kafka://localhost:9092')
orders_topic = app.topic('orders', value_type=dict)
order_counts = app.Table('order_counts', default=int)

@app.agent(orders_topic)
async def count_orders(stream):
    async for order in stream:
        user_id = order['userId']
        order_counts[user_id] += 1
        print(f"User {user_id}: {order_counts[user_id]} orders")

Faust is the pragmatic choice when the pipeline needs state — counting, windowed joins, per-key aggregation — without standing up Kafka Streams infrastructure. For the deeper treatment, see the Kafka Stream Processing guide.

Schema Registry with Avro

from confluent_kafka import Consumer
from confluent_kafka.schema_registry import SchemaRegistryClient
from confluent_kafka.schema_registry.avro import AvroDeserializer
from confluent_kafka.serialization import SerializationContext, MessageField

schema_registry = SchemaRegistryClient({'url': 'http://localhost:8081'})
avro_deserializer = AvroDeserializer(schema_registry)

consumer = Consumer({
    'bootstrap.servers': 'localhost:9092',
    'group.id': 'avro-consumers',
})

consumer.subscribe(['orders-avro'])

msg = consumer.poll(1.0)
if msg:
    ctx = SerializationContext(msg.topic(), MessageField.VALUE)
    value = avro_deserializer(msg.value(), ctx)
    print(f"Deserialized: {value}")

The SerializationContext tells the deserializer which topic and field the bytes belong to — schema IDs are scoped per topic+field, so omitting it breaks resolution on current confluent-kafka versions.

Multiple Topics and Pattern Subscription

# Subscribe to several topics at once
consumer.subscribe(['orders', 'payments', 'shipments'])

# Or a regex pattern — assignments update as matching topics appear
consumer.subscribe(['^orders-.*'], on_assign=on_assign)

Pattern subscription re-evaluates on metadata refresh, so a new orders-eu topic joins the assignment automatically. All matched topics share the same consumer group and offset store.

What Works

  • Use cooperative-sticky assignment: the default range strategy stops the whole group during rebalances. Cooperative-sticky only moves the partitions that need to move.
  • Disable enable.auto.commit and commit deliberately: auto-commit can persist offsets before processing completes — silent data loss on crash. Manual commit after success is the only safe default.
  • Partition by a meaningful key: same key → same partition → ordered processing for that key. Keyless messages go round-robin and lose ordering entirely.
  • Set isolation.level=read_committed whenever transactions are in play, or your consumer may process messages that later abort.
  • Commit inside on_revoke: partitions you fail to flush before revocation get replayed from their last committed offset by the new owner.
  • Watch consumer lag, not just errors: kafka-consumer-groups.sh --describe --group order-processors shows lag per partition. Sustained growth is your scale-up signal.

Common Mistakes

  • More consumers than partitions: extra members sit completely idle. Six partitions means six active consumers per group, maximum — scale partitions first.
  • Auto-commit with slow processing: the 5-second default interval can commit an offset for a batch your handler hasn’t finished — gone on crash.
  • Ignoring on_revoke: uncommitted work on a revoked partition is reprocessed by its new owner. At best you get duplicates; at worst, double side effects.
  • Blocking inside the poll loop: max.poll.interval.ms (default 5 minutes) is a hard budget between poll() calls. Exceed it and the consumer gets kicked out of the group.
  • Uninitialized transactional.id collisions: two instances with the same id fence each other — transactions start failing with “producer fenced” errors that look like broker problems.
  • Reading auto.offset.reset wrong: with no committed offsets, earliest replays the entire topic history; latest skips it. Pick deliberately, don’t inherit the default.

See Also

Frequently Asked Questions

How many partitions should I create?

Size for peak consumer parallelism plus headroom — each partition maps to at most one consumer per group. Six to twelve covers most services. Partitions also cost file handles and replication traffic on every broker, and repartitioning later requires touching every producer and consumer, so err slightly high rather than low.

What is consumer lag?

Lag is the distance between the newest offset in a partition and the consumer's committed offset. It tells you whether consumption keeps pace with production. Inspect it with kafka-consumer-groups.sh --describe or Burrow — growing lag means scale or optimize; lag that never drains means a stalled consumer.

How does exactly-once work in Kafka?

Three pieces working together: enable.idempotence deduplicates producer retries, transactions make the output write atomic, and send_offsets_to_transaction commits the input offset inside the same transaction. Consumers opt in with isolation.level=read_committed so they never see aborted output. Remove any piece and you're back to at-least-once.

Can multiple consumer groups read the same topic?

Yes — that's the point of groups. Each tracks its own offsets independently, so the same topic can feed analytics, a database sync, and an alerting pipeline concurrently without any coordination between them.

What happens when a consumer crashes?

The missed heartbeats trigger session.timeout.ms (10s default in Java clients; librdkafka uses session.timeout.ms too). The group coordinator revokes the dead member's partitions and reassigns them; the new owner resumes from the last committed offset. Uncommitted work comes back — another reason handlers should be idempotent.

Cooperative or eager rebalancing — which should I pick?

Cooperative-sticky for anything long-lived: it revokes only the partitions that must move, so unaffected members keep processing. Eager (the classic range/roundrobin assignors) revokes everything on every membership change — fine for short jobs, wasteful for services that rebalance often.