Skip to main content

fastkafka2

fastkafka2 is an async, Pydantic-based Kafka framework built on confluent-kafka/librdkafka. Version 0.6 is designed for services that need bounded memory, explicit transport security, per-partition ordering, and at-least-once delivery.

Production contract

  • TLS/SASL configuration is mandatory and cannot be downgraded through raw client options.
  • Plaintext() is available only as an explicit choice for local development.
  • Consumer group IDs are explicit deployment identities; none are derived from broker URLs.
  • Auto-commit and auto-offset-store are disabled. A synchronous broker-acknowledged commit advances only after ordered processing succeeds.
  • Failed commits remain pending and are retried.
  • Processing is ordered within a partition and concurrent across partitions.
  • Both message count and total buffered bytes are bounded. Handler concurrency is globally bounded to protect databases and downstream APIs.
  • Producer delivery is broker-acknowledged, idempotence is enabled, and batches are bounded.
  • JSON/Pydantic validation is fail-closed. A handler must declare a concrete Pydantic data model.
  • Topic and DLT auto-creation are disabled by default. Production topic policy stays in infrastructure-as-code.

The delivery guarantee is at least once, not exactly once. Handlers must be idempotent, or use a database inbox/outbox/transactional design for external side effects.

Install

pip install fastkafka2

Requirements: Python 3.10 or newer, Pydantic 2, and confluent-kafka 2.x.

Minimal production service

import os

from pydantic import BaseModel, ConfigDict

from fastkafka2 import KafkaApp, KafkaHandler, KafkaMessage, SASL


class Order(BaseModel):
    model_config = ConfigDict(extra="forbid")

    order_id: str
    amount_minor: int


class EventHeaders(BaseModel):
    model_config = ConfigDict(extra="forbid")

    event_type: str
    trace_id: str


orders = KafkaHandler()


@orders("orders", headers_filter={"event_type": "created"})
async def consume_order(message: KafkaMessage[Order, EventHeaders]) -> None:
    # `order_service` is your own application service. Keep the operation idempotent by
    # order_id: at-least-once delivery can redeliver around crashes and rebalances.
    await order_service.apply_once(message.data.order_id, message.data.amount_minor)


security = SASL(
    mechanism="SCRAM-SHA-512",
    username=os.environ["KAFKA_USERNAME"],
    password=os.environ["KAFKA_PASSWORD"],
    ca_location=os.environ["KAFKA_CA_FILE"],
)

app = KafkaApp(
    title="orders-consumer",
    description="Consumes order events",
    bootstrap_servers=os.environ["KAFKA_BOOTSTRAP"],
    group_id="orders-consumer-v1",
    security=security,
    on_error="dlt",
    max_message_bytes=4 * 1024 * 1024,
    max_total_queue_size=10_000,
    max_total_queue_bytes=256 * 1024 * 1024,
    max_concurrent_handlers=128,
)
app.include_handler(orders)

Start with await app.start() and always pair it with await app.stop(), or call await app.run() for built-in SIGINT/SIGTERM handling. The application-owned producer is available as app.producer and follows the same lifecycle.

TLS and local development

TLS with broker verification:

from fastkafka2 import TLS

security = TLS(ca_location="/run/secrets/kafka-ca.pem")

mTLS adds certificate_location and key_location. Hostname and certificate verification cannot be disabled.

Local plaintext Kafka must be explicit:

from fastkafka2 import Plaintext

security = Plaintext()  # local Docker/test broker only

Do not select Plaintext() from an untrusted environment variable. Choose the security object in deployment code and mount secrets from the platform secret store.

Authentication before decoding

For Kafka, authentication happens at the transport/session layer:

TLS verification -> SASL authentication -> broker authorizes/fetches records
-> UTF-8 metadata checks -> header routing -> JSON decode -> Pydantic validation -> handler

Therefore an unauthenticated client connection cannot deliver records to the consumer for JSON/Pydantic parsing. Header filters also run before body decoding, but they are routing, not an authentication mechanism. If message-level signatures are required, verify signed metadata before accepting a handler and keep broker ACLs enabled.

Poison-message policies

on_error is explicit and fail-closed:

Policy Behaviour Source offset
pause (default) Pauses the native Kafka partition Not advanced
dlt Awaits DLT broker acknowledgement Advanced only after DLT success
skip Drops the record Requires allow_data_loss=True

With dlt, provision <source-topic>.dead before deployment. auto_create_dlt=True is intended for controlled environments; its replication factor defaults to 3. DLT records contain the raw value and origin metadata. Source key, source headers, and exception text are excluded unless explicitly enabled because they may contain credentials or personal data.

DLT publication and source-offset commit are not one Kafka transaction. A crash between those operations can duplicate a DLT record, but does not silently lose the source record.

High-load controls

Important KafkaApp/KafkaConsumerService limits:

Option Default Purpose
consume_batch 500 Records requested per consume call
max_queue_size 1,000 Per-partition queued records
max_total_queue_size 10,000 Global queued/in-flight record count
max_total_queue_bytes 256 MiB Global raw-payload byte budget
max_concurrent_handlers 256 Global business-handler concurrency
max_message_bytes 4 MiB Accepted value size and per-message fetch limit
max_header_bytes 64 KiB Accepted header budget
max_key_bytes 64 KiB Accepted key budget
max_fetch_bytes 64 MiB Maximum fetch response budget
commit_interval 0.5 s Periodic synchronous batch commit interval

Tune handler concurrency from downstream capacity, not CPU count alone. Keep queue byte budgets below the container memory limit with room for librdkafka, decoded Pydantic objects, application caches, and temporary batches.

get_stats() exposes configured limits, buffered count/bytes, and per-partition processed, failed, poison, queue, and pause state. Export these values to your metrics system and alert on sustained queue growth, paused partitions, commit errors in logs, consumer lag, and DLT rate.

Producer

producer = app.producer

await producer.send_message(
    "order-results",
    {"order_id": "o-1", "status": "accepted"},
    key="o-1",
)

delivered = await producer.send_many(
    "order-results",
    [{"order_id": f"o-{i}"} for i in range(1_000)],
)

The producer enforces idempotence, acks=all, a bounded local queue, per-message/header limits, and batch count/byte limits. send_many waits for every enqueued delivery report; partial enqueue or delivery failure raises.

Topic provisioning

Create topics outside the application with explicit partitions, replication factor, retention/compaction policy, min ISR, and ACLs. auto_create_topics=False is the default. For a single-node local broker only:

app = KafkaApp(
    title="Order Service",
    description="Validates and applies order events",
    bootstrap_servers="localhost:9092",
    group_id="order_service",
    security=Plaintext(),
    auto_create_topics=True,
    topic_num_partitions=4,
    topic_replication_factor=1,
)

Validation and routing

Every handler needs KafkaMessage[DataModel, HeadersModel], with a concrete Pydantic data model; the headers slot may be a plain dict. A bare KafkaMessage is rejected at registration. Invalid UTF-8 metadata, an oversized record, invalid JSON, schema failure, or no matching handler all follow the poison policy without advancing the offset accidentally.

For a handler that does not read the body — a router, an audit sink, a catch-all — pass require_data_model=False on the handler or on its KafkaHandler group to receive the body as decoded and unvalidated. The registration logs a warning naming the handler and topic.

audit = KafkaHandler(require_data_model=False)


@audit("events")
async def sink(message: KafkaMessage) -> None:
    ...

Body decoding is lazy: raw bytes are decoded only after metadata validation and a matching handler are established.

Release checks

From this directory:

python -m pytest -q -m "not integration"
python -m ruff check fastkafka2 tests benchmarks
python -m mypy fastkafka2
python -m bandit -q -r fastkafka2
python -m pip_audit
python -m build --outdir release-dist/$VERSION
python -m twine check release-dist/$VERSION/*

Build into a fresh, version-specific directory. dist/ accumulates artifacts from earlier releases, and twine check dist/* — or worse, twine upload dist/* — would pick them up.

Integration and throughput tests require the local broker described in docker-compose.test.yml; they refuse the previously known production address.

See SAFETY.md for the threat model and CHANGELOG.md for the 0.6 migration notes.

Metadata

Release files for fastkafka2 0.6.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastkafka2 0.6.1
File Size Uploaded Provenance Actions
fastkafka2-0.6.1.tar.gz 73.5 kB Without provenance Details for fastkafka2-0.6.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastkafka2 0.6.1
File Interpreter ABI Platform Actions
fastkafka2-0.6.1-py3-none-any.whl Python 3 none any Details for fastkafka2-0.6.1-py3-none-any.whl

Total release size: 123.1 kB

Release files / fastkafka2-0.6.1.tar.gz

Download URL fastkafka2-0.6.1.tar.gz
Size 73.5 kB
Tags Source
SHA-256 checksum
How to use checksums
07f76e1cd0e18a4d2372a1cab202131f14fa28daff262c06aa3a2ced9372940b
BLAKE2b-256 checksum
How to use checksums
cafd70edd4737490da61bbe4eaa359cc5512906020d1b4912c40cab2f82bb37b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.0

Release files / fastkafka2-0.6.1-py3-none-any.whl

Download URL fastkafka2-0.6.1-py3-none-any.whl
Size 49.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
47a8cc995723b91a52fd42e028e65bfefd8ec99b160b18242e93ea314c4b3ca1
BLAKE2b-256 checksum
How to use checksums
4cd30b6b0dd54ea8ff3a4b1c7e860cbf1760ca51cbf942eca6e3598d4d7c5b8a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.0

Security for fastkafka2 0.6.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page