0Pricing
FastAPI Backend Development Bootcamp · 강의

Kafka 이벤트의 비동기 생성과 소비

aiokafka를 FastAPI와 통합해 이벤트 루프를 차단하지 않고 이벤트를 발행하고 소비합니다.

Kafka 이벤트의 비동기 생성과 소비은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why async Kafka in FastAPI

FastAPI runs on an asyncio event loop. If you publish or poll Kafka with a blocking client (like the standard kafka-python library), every network call freezes the entire loop, stalling all concurrent requests.

  • aiokafka is a native asyncio Kafka client that never blocks the loop.
  • Its send and getone operations are coroutines you await.
  • This lets one worker handle thousands of in-flight requests while Kafka I/O is pending.

In this lesson you will wire an AIOKafkaProducer and an AIOKafkaConsumer into a FastAPI app the right way.

Producer lifecycle with lifespan

A producer maintains TCP connections and a background sender task. You must start() it once at app boot and stop() it on shutdown — never per request. The modern FastAPI way is the lifespan context manager.

  • await producer.start() opens connections and the sender loop.
  • await producer.stop() flushes pending batches and closes cleanly.
  • Store the producer on app.state so routes can reach it.
from contextlib import asynccontextmanager
from fastapi import FastAPI
from aiokafka import AIOKafkaProducer


@asynccontextmanager
async def lifespan(app: FastAPI):
    producer = AIOKafkaProducer(
        bootstrap_servers="localhost:9092",
        enable_idempotence=True,
    )
    await producer.start()
    app.state.producer = producer
    try:
        yield
    finally:
        await producer.stop()


app = FastAPI(lifespan=lifespan)

Publishing an event from a route

Inside a route, grab the shared producer and await producer.send_and_wait(...). The send_and_wait call returns once the broker has acknowledged the record, giving you back-pressure and delivery confirmation.

  • Kafka keys and values are bytes — encode JSON yourself or pass a serializer.
  • The returned RecordMetadata tells you the partition and offset.
  • Use the message key to guarantee per-entity ordering across partitions.
import json
from fastapi import FastAPI, Request

app = FastAPI()


@app.post("/orders")
async def create_order(payload: dict, request: Request):
    producer = request.app.state.producer
    value = json.dumps(payload).encode("utf-8")
    key = str(payload["order_id"]).encode("utf-8")
    meta = await producer.send_and_wait(
        "orders", value=value, key=key
    )
    return {"partition": meta.partition, "offset": meta.offset}

Serializers vs manual encoding

Instead of calling json.dumps(...).encode() on every send, you can hand aiokafka a value_serializer and key_serializer. The producer applies them automatically, so routes pass plain Python objects.

  • value_serializer receives your object and must return bytes.
  • This centralizes encoding and avoids repetition across routes.
  • In production teams often swap JSON for Avro or Protobuf via a schema registry.
import json
from aiokafka import AIOKafkaProducer

producer = AIOKafkaProducer(
    bootstrap_servers="localhost:9092",
    value_serializer=lambda v: json.dumps(v).encode("utf-8"),
    key_serializer=lambda k: str(k).encode("utf-8"),
)

# Now routes can send native objects:
# await producer.send_and_wait("orders", value={"id": 7}, key=7)

send vs send_and_wait

Two producer methods, two trade-offs:

  • send() returns a future immediately and lets aiokafka batch records in the background — high throughput, but you do not yet know if delivery succeeded.
  • send_and_wait() awaits the broker ack — slower per call, but gives you a result and surfaces errors right away.

For request handlers where the client needs confirmation, prefer send_and_wait. For fire-and-forget bulk emits, use send and optionally await the futures later.

# Fire many records fast, then wait once for all of them
futures = []
for item in batch:
    fut = await producer.send("events", value=item)
    futures.append(fut)

# Awaiting the futures surfaces any delivery errors
for fut in futures:
    record_meta = await fut

The blocking trap to avoid

The single most common mistake is mixing a synchronous client into the async app. Below is a standalone demo of why blocking the loop hurts: a blocking time.sleep inside a coroutine stalls everything, while asyncio.sleep yields control.

Run it and notice the awaited version lets both tasks overlap — exactly the behavior aiokafka gives you for real network I/O.

import asyncio
import time


async def good_io(name):
    await asyncio.sleep(0.2)  # yields the loop
    print(f"{name} done at {time.strftime('%X')}")


async def main():
    start = time.perf_counter()
    await asyncio.gather(good_io("A"), good_io("B"))
    print(f"both finished in {time.perf_counter() - start:.2f}s")


asyncio.run(main())

Consumer as a background task

A FastAPI app serves HTTP, but a Kafka consumer must poll continuously. The clean pattern: start the consumer in lifespan and run its poll loop as an asyncio background task, cancelling it on shutdown.

  • asyncio.create_task(...) launches the loop without blocking startup.
  • On shutdown, cancel the task, then await consumer.stop().
  • Always wrap the loop body so one bad message does not kill the consumer.
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI
from aiokafka import AIOKafkaConsumer


async def consume(consumer: AIOKafkaConsumer):
    async for msg in consumer:
        try:
            handle(msg.value)
        except Exception as exc:
            print("handler failed:", exc)


@asynccontextmanager
async def lifespan(app: FastAPI):
    consumer = AIOKafkaConsumer(
        "orders",
        bootstrap_servers="localhost:9092",
        group_id="order-workers",
    )
    await consumer.start()
    task = asyncio.create_task(consume(consumer))
    try:
        yield
    finally:
        task.cancel()
        await consumer.stop()


app = FastAPI(lifespan=lifespan)

Iterating messages and decoding

An AIOKafkaConsumer is an async iterator: async for msg in consumer awaits each new record. Each msg exposes topic, partition, offset, key, and value as bytes.

  • Decode msg.value the same way you encoded it on the producer side.
  • You can also pass a value_deserializer to the consumer constructor.
  • msg.timestamp carries the broker or producer timestamp for latency metrics.
import json
from aiokafka import AIOKafkaConsumer

consumer = AIOKafkaConsumer(
    "orders",
    bootstrap_servers="localhost:9092",
    group_id="order-workers",
    value_deserializer=lambda b: json.loads(b.decode("utf-8")),
)


async def run():
    async for msg in consumer:
        event = msg.value  # already a dict
        print(event["order_id"], "at offset", msg.offset)

Offset commits: at-least-once delivery

Auto-commit (the default) commits offsets on a timer, which can lose messages if the worker crashes after committing but before processing. For reliable processing, set enable_auto_commit=False and commit after you finish handling a message.

  • Manual commit gives at-least-once semantics — a crash replays the last uncommitted message.
  • Because messages can repeat, your handlers must be idempotent.
  • Commit in small batches to balance throughput against replay cost.
consumer = AIOKafkaConsumer(
    "orders",
    bootstrap_servers="localhost:9092",
    group_id="order-workers",
    enable_auto_commit=False,
    auto_offset_reset="earliest",
)


async def run():
    async for msg in consumer:
        await process(msg.value)   # do the work first
        await consumer.commit()    # then advance the offset

Concurrency and partition ordering

Within a single partition Kafka preserves order, and an async-for loop processes those records sequentially. To scale, you have two levers:

  • More partitions + more consumers in the same group_id — Kafka assigns partitions across instances automatically.
  • Bounded concurrency per worker with a semaphore, when per-message work is I/O-heavy and strict ordering is not required.

If ordering per entity matters, keep that entity on one partition via a stable message key and process its partition serially.

import asyncio

sem = asyncio.Semaphore(10)


async def handle_bounded(value):
    async with sem:
        await do_async_work(value)


async def run(consumer):
    async for msg in consumer:
        # Schedule work without blocking the poll loop
        asyncio.create_task(handle_bounded(msg.value))

Graceful shutdown and error handling

A robust deployment cleans up so in-flight data is not lost:

  • On shutdown, cancel the consumer task and await consumer.stop() — this commits offsets (if auto-commit) and leaves the group cleanly so rebalancing is fast.
  • await producer.stop() flushes buffered records before closing.
  • Wrap per-message handling in try/except and route poison messages to a dead-letter topic instead of crashing the loop.

Never call start()/stop() inside request handlers — that thrashes connections and breaks consumer group membership.

async def consume(consumer, dlq_producer):
    async for msg in consumer:
        try:
            await process(msg.value)
            await consumer.commit()
        except PermanentError:
            await dlq_producer.send_and_wait(
                "orders.dlq", value=msg.value, key=msg.key
            )
            await consumer.commit()  # skip the poison message

Quick Check

You need reliable processing where a worker crash must never silently drop an order event. Which consumer configuration best supports this?

Recap

You integrated Kafka into FastAPI without blocking the event loop:

  • aiokafka provides awaitable producer and consumer clients native to asyncio.
  • Manage the producer and consumer in the lifespan context: start() at boot, stop() at shutdown — never per request.
  • send_and_wait confirms delivery; send maximizes throughput.
  • Run the consumer poll loop as an asyncio background task and iterate with async for.
  • Disable auto-commit and commit after processing for at-least-once delivery, keeping handlers idempotent.
  • Scale with more partitions and consumers in a group, preserve per-entity order via the message key, and shut down gracefully with a dead-letter topic for poison messages.

자주 묻는 질문

“Kafka 이벤트의 비동기 생성과 소비” 강의는 무료인가요?

네 — “Kafka 이벤트의 비동기 생성과 소비” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“Kafka 이벤트의 비동기 생성과 소비”에서 뭘 배우나요?

aiokafka를 FastAPI와 통합해 이벤트 루프를 차단하지 않고 이벤트를 발행하고 소비합니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“Kafka 이벤트의 비동기 생성과 소비” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Kafka 이벤트의 비동기 생성과 소비
  2. 스키마 레지스트리와 Avro 계약 진화
  3. 트랜잭션 아웃박스 패턴
  4. 멱등 소비자와 정확히 한 번 의미론
← FastAPI Backend Development Bootcamp(으)로 돌아가기