Introducing a new way to review your PRs.

Read the announcement

aio-libs / aiokafka

asyncio client for kafka

View on GitHub

19 documents · Updated Nov 23, 2026

docs / producer-subsystem

Kafka producer subsystem

The Kafka producer subsystem publishes records to Kafka without blocking the application on each broker request. It accepts records through an asynchronous API, groups them by topic partition, sends them through a background task, and completes caller futures when Kafka accepts or rejects the data. Its settings define the balance between speed, durability, retry behavior, duplicate prevention, and atomic transactions.

Producer lifecycle

Producer startup and shutdown

The producer starts by discovering the cluster and then starts its background delivery task. A normal shutdown waits for queued records to finish before it closes the sender and broker connections, so applications should use stop() or the async context manager for a clean end to the lifecycle. Cluster discovery and broker connection behavior are described in Client and cluster connectivity. References: aiokafka/…/producer.py• L363-398

Record publication

AIOKafkaProducer is the public entry point for record publication. A call to send() resolves topic metadata, serializes the key and value, selects a partition, and places the record in the producer buffer. It returns a future for the delivery result rather than waiting for the broker; send_and_wait() provides the waiting form of the same flow. References: aiokafka/…/producer.py• L39-59, aiokafka/…/producer.py• L438-537

The following diagram shows how an application record becomes a broker result.

flowchart LR
    A[Application] --> B[send or send_and_wait]
    B --> C[Serialization and partition choice]
    C --> D[Per-partition buffer]
    D --> E[Background sender]
    E --> F[Produce request]
    F --> G[Broker acknowledgement or error]
    G --> H[Delivery future]

Record batching

Per-partition accumulation

The producer accumulates records in batches for each topic partition. A batch closes when it reaches its size limit or its linger period ends, while a full buffer makes a later send() wait for space. This groups small records into fewer requests and also gives compression a larger data set to process. References: aiokafka/…/message_accumulator.py• L333-345, aiokafka/…/message_accumulator.py• L472-521, aiokafka/…/producer.py• L104-122

Only one batch for a partition is delivered at a time. The queue keeps records in append order, so later records wait behind an earlier batch even when metadata or the partition leader changes. The lower-level create_batch() and send_batch() APIs let an application define batch contents directly when the normal record API is not enough. See Producer accumulation and delivery pipeline for the detailed batch and sender flow. References: aiokafka/…/message_accumulator.py• L538-570, aiokafka/…/producer.py• L537-582

Request delivery

Background sender

The sender is the background part of the producer that turns ready batches into produce requests. It groups batches by their current partition leaders, avoids overlapping delivery for the same partition, and waits for new data, linger expiry, or metadata updates. This separation lets application coroutines add records while network work continues in the event loop. Delivery measurements and client events are covered in Metrics and instrumentation. References: aiokafka/…/message_accumulator.py• L571-636

Acknowledgement modes

The acks setting defines when the broker response is enough to complete a delivery future. The modes have different durability and error visibility:

ModeBroker waitProducer consequence
0No acknowledgementThe future completes without a broker result, and the producer cannot retry a failure it cannot observe.
1The leader writes the recordA leader failure before replication can lose an acknowledged record.
allThe in-sync replicas acknowledgeThis is the strongest available write guarantee, subject to the cluster's replica settings.

The default is 1. Idempotent and transactional production changes the effective setting to all. References: aiokafka/…/producer.py• L78-103, aiokafka/…/producer.py• L256-292

Retry and completion behavior

The sender retries broker errors that Kafka marks as retriable. For ordinary production, a batch can expire while it waits for a usable leader or a successful response; the producer then completes its futures with the failure. A retry can be uncertain after a timeout because the broker may have written the record before the client saw the error, so application retries can create duplicates. References: aiokafka/…/message_accumulator.py• L342-345

When a batch succeeds, the producer maps the broker offset and timestamp to the batch future and to each record future. When it fails, the same failure is delivered to the waiting records. A cancelled record future does not cancel the broker work already queued by send(). References: aiokafka/…/message_accumulator.py• L202-324, aiokafka/…/producer.py• L514-522

Delivery guarantees

Idempotent production

Idempotent production uses producer identity and per-partition sequence data so retried batches are recognized as the same logical write. Set enable_idempotence=True when a producer must avoid duplicates caused by its own retries; this mode requires acks=all and keeps retrying instead of treating the normal batch lifetime as a final timeout. It does not replace durable topic configuration or make unrelated application retries safe. See Idempotent and transactional production for the producer identity and transaction state model. References: aiokafka/…/producer.py• L269-287, aiokafka/…/producer.py• L274-292, aiokafka/…/message_accumulator.py• L538-551

Transactional production

Transactional production extends idempotent delivery across a group of records. A transactional_id enables this mode and requires each record to be sent inside an active transaction. Commit waits for the transaction's pending batches before it asks Kafka to commit; an exception in the transaction context aborts the transaction instead. Records become visible to consumers only after commit when those consumers use read-committed isolation. References: aiokafka/…/producer.py• L269-287, aiokafka/…/producer.py• L582-665, aiokafka/…/message_accumulator.py• L441-457

The transaction can also include consumer offsets through send_offsets_to_transaction(). This joins record publication and offset progress into one commit decision, which supports consume-process-produce workflows without exposing a successful output while leaving the input offset uncommitted. References: aiokafka/…/producer.py• L619-639

Transaction ownership

The transaction manager tracks the producer identity, sequence numbers, partitions, consumer group offsets, and transaction state. A transactional identity belongs to one active producer instance at a time; if another instance uses the same identity, Kafka fences the older producer and its work must stop. References: aiokafka/…/producer.py• L269-287

Change checklist

When these files or sections are changed, remember to consider these:

  • Changes to acks, retry expiry, or batch completion must preserve the meaning of the futures returned by both send() and send_batch().
  • Changes to per-partition queueing or sender concurrency must preserve append order and the single in-flight batch rule.
  • Changes to idempotent sequence assignment must stay aligned with the record batch producer identity and with duplicate-response handling.
  • Changes to transaction commit order must keep pending produce batches and transactional offset commits ahead of the final transaction marker.
  • Changes to transactional identity or state transitions must preserve fencing and the distinction between abortable and fatal errors.

Important failure modes

TriggerConsequenceGuard
The buffer cannot drain before the send timeoutsend() raises a Kafka timeout before the record is scheduled.Increase capacity or drain rate, or apply an application-level timeout around the send coroutine.
A non-idempotent request times out after reaching the brokerA later application retry can write a duplicate.Use idempotence when duplicate prevention is required, and treat the original result as unknown.
acks=0 is used during a broker or network failureThe producer cannot detect the failure and the returned result has no broker offset.Use an acknowledgement mode that matches the required durability.
A transactional producer sends outside an active transactionThe send is rejected and no record is queued.Begin a transaction before sending and end it with commit or abort.
Two live producers use the same transactional_idKafka fences one producer; its transaction and later sends fail.Assign a unique identity to each active producer instance.
The sender task fails with an unexpected errorPending batch futures fail and the producer cannot continue normal delivery.Surface the sender error, stop the producer, and create a new producer after fixing the cause.

Key files

FileWhy to read it
aiokafka/…/producer.pyDefines the public producer lifecycle, send APIs, configuration rules, and transaction entry points.
aiokafka/…/message_accumulator.pyExplains per-partition buffering, batch lifetime, ordering, back-pressure, and delivery futures.
aiokafka/…/sender.pyShows how ready batches become broker requests, how retries work, and how transaction requests are sequenced.
aiokafka/…/transaction_manager.pyDefines idempotent sequence state and the transaction state and ownership model.
docs/producer.rstGives the user-facing contract for batching, acknowledgements, retries, idempotence, and transactions.
tests/test_producer.pyDemonstrates the public send, flush, shutdown, ordering, acknowledgement, and retry guarantees.
tests/test_transactional_producer.pyDemonstrates commit, abort, fencing, transactional offset handling, and transaction boundary checks.