Backend Engineer Guide: Event-Driven Microservices with Apache Kafka & aiokafka

Building event-driven Python microservices with Apache Kafka and aiokafka requires careful control over consumer offset commits, partition rebalance callbacks, and poison-pill message isolation. A naive consumer with enable_auto_commit=True commits offsets in the background before your coroutine finishes writing to PostgreSQL—silently losing financial or order events if the pod crashes mid-batch. Worse, a single slow await exceeding max_poll_interval_ms triggers a consumer group rebalance storm. As a backend engineer, here is how I architect production-grade aiokafka consumers.

1. Manual Offset Commits & Rebalance-Safe Consumer Loop

We disable auto-commit, process records in bounded micro-batches inside an idempotent database transaction, commit exact partition offsets only after PostgreSQL durability is confirmed, and register a ConsumerRebalanceListener to flush pending work before partitions are revoked:

# messaging/kafka_worker.py
import asyncio
import json
import logging
from aiokafka import AIOKafkaConsumer, AIOKafkaProducer, ConsumerRebalanceListener, TopicPartition
from aiokafka.structs import OffsetAndMetadata

logger = logging.getLogger(__name__)

class GracefulRebalanceListener(ConsumerRebalanceListener):
    def __init__(self, consumer: AIOKafkaConsumer, pending_offsets: dict[TopicPartition, OffsetAndMetadata]):
        self.consumer = consumer
        self.pending_offsets = pending_offsets

    async def on_partitions_revoked(self, revoked: set[TopicPartition]) -> None:
        if self.pending_offsets:
            logger.info("Flushing %d partition offsets before rebalance", len(self.pending_offsets))
            await self.consumer.commit(self.pending_offsets)
            self.pending_offsets.clear()

    async def on_partitions_assigned(self, assigned: set[TopicPartition]) -> None:
        logger.info("Assigned partitions: %s", assigned)

async def consume_order_events(bootstrap_servers: str) -> None:
    pending_offsets: dict[TopicPartition, OffsetAndMetadata] = {}
    consumer = AIOKafkaConsumer(
        "orders.events.v1",
        bootstrap_servers=bootstrap_servers,
        group_id="billing-ledger-projector",
        enable_auto_commit=False,
        auto_offset_reset="earliest",
        max_poll_records=50,
        max_poll_interval_ms=300000,
        session_timeout_ms=45000,
    )
    dlq_producer = AIOKafkaProducer(bootstrap_servers=bootstrap_servers, acks="all")
    await consumer.start()
    await dlq_producer.start()
    consumer.subscribe(["orders.events.v1"], listener=GracefulRebalanceListener(consumer, pending_offsets))

    try:
        async for msg in consumer:
            tp = TopicPartition(msg.topic, msg.partition)
            try:
                event = json.loads(msg.value.decode("utf-8"))
                await process_event_idempotently(event, msg.offset)
            except Exception as exc:
                logger.exception("Poison-pill message at %s:%d; routing to DLQ", tp, msg.offset)
                await dlq_producer.send_and_wait(
                    "orders.events.v1.dlq",
                    value=msg.value,
                    headers=[("error", str(exc).encode("utf-8"))],
                )
            pending_offsets[tp] = OffsetAndMetadata(msg.offset + 1, "")
            if len(pending_offsets) >= 10:
                await consumer.commit(pending_offsets)
                pending_offsets.clear()
    finally:
        if pending_offsets:
            await consumer.commit(pending_offsets)
        await consumer.stop()
        await dlq_producer.stop()

2. Partition Key Ordering Guarantees

Always key messages by the domain aggregate root ID (e.g., order_id or account_id) so all state transitions for a single entity land on the same Kafka partition and are processed strictly in causal order.

3. Related Event-Driven & Backend Engineering Resources


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 25+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs