Producer accumulation and delivery pipeline
The producer delivery pipeline turns a call to publish a record into a partitioned, buffered batch and then into a broker request. The accumulator controls batch lifetime and backpressure. The sender chooses broker targets, manages in-flight work, handles replies, and completes the futures returned to the caller.
Pipeline stages
The pipeline moves each record through a small set of ownership changes. The public producer accepts the record and selects its topic partition. The accumulator holds it until the batch is ready. The sender transfers the batch to the broker leader and maps the broker result back to the record futures.
The main path is:
AIOKafkaProducer.sendwaits for topic metadata, serializes the key and value, selects a partition, and adds the record to the accumulator.- The accumulator appends the record to the current batch for that topic-partition. It returns a record future as soon as the record is accepted.
- The sender wakes when data arrives or when a batch's linger period ends. It drains ready batches and groups them by their current partition leader.
- The sender builds one produce request for the batches assigned to a broker and sends it with the configured acknowledgement rule.
- The response handler completes each batch. A successful response supplies the base offset and timestamp used to resolve the batch and record futures.
This diagram shows how ownership moves from the caller to the accumulator and then to the sender.
flowchart LR
Call[Producer send call] --> Validate[Metadata and record checks]
Validate --> Acc[Accumulator by topic-partition]
Acc --> Ready[Size or linger makes batch ready]
Ready --> Group[Group batches by leader]
Group --> Request[Broker produce request]
Request --> Reply{Broker result}
Reply -->|success| Complete[Resolve metadata futures]
Reply -->|no acknowledgements| NoAck[Resolve futures with no metadata]
Reply -->|retriable error| Retry[Back off and re-enqueue]
Reply -->|final error| Fail[Fail batch futures]
Retry --> Acc
References: aiokafka/…/producer.py• L440-524 aiokafka/…/message_accumulator.py• L386-415 aiokafka/…/sender.py• L98-177
Record batching
The accumulator keeps separate queues for each topic-partition so records for one Kafka partition stay ordered. A batch accepts records until it reaches its size limit or is closed. A linger period can delay a smaller batch so records that arrive close together can share one request.
The accumulator applies backpressure when the current batch cannot accept another record. The send call then waits for that batch to leave the accumulator. If the wait exceeds the request timeout, the send call raises KafkaTimeoutError; this timeout means the record was not scheduled, not that a broker rejected it.
The batch carries two levels of completion state:
- The batch future represents delivery of the whole batch.
- Each record future carries metadata for one record, including its topic, partition, and final offset when acknowledgements provide one.
An explicit batch follows the same queue and completion path as individual records. The producer creates the batch before submission, then the accumulator waits until the earlier batch for that topic-partition has drained before queuing another one.
References: aiokafka/…/message_accumulator.py• L29-145 aiokafka/…/message_accumulator.py• L147-199 aiokafka/…/message_accumulator.py• L464-513 aiokafka/…/message_accumulator.py• L667-707 aiokafka/…/producer.py• L539-582
Batch dispatch
Dispatch removes ready batches from the per-partition queues and groups them by the broker leader known for each topic-partition. The sender does not dispatch a partition while an earlier request for that partition is in flight. This preserves order while allowing requests for different brokers to run at the same time.
The sender runs this work in a background task. It waits for new data, a linger deadline, metadata refresh, or a completed produce task. It tracks broker nodes with in-flight requests and mutes the affected topic-partitions until each request finishes. This prevents a later batch from overtaking an earlier one while still allowing independent broker requests to run together.
The accumulator keeps a dispatched batch in a pending set until its future completes. That state lets a failed batch return to its original partition queue without losing its caller futures. A new dispatch records a new attempt and refreshes the batch's delivery timing.
When metadata has no leader for a partition, the sender asks the client to refresh metadata. If the batch expires before a usable leader appears, the accumulator fails it with a leader error. A linger timer wakes the sender when a batch becomes eligible without waiting for another record.
References: aiokafka/…/message_accumulator.py• L325-369 aiokafka/…/message_accumulator.py• L530-628 aiokafka/…/sender.py• L98-177 aiokafka/…/sender.py• L276-293
Broker requests and acknowledgements
The sender builds a produce request from the encoded data of the batches assigned to one broker. The request carries the configured acknowledgement level and request timeout. The acknowledgement level defines when the broker considers the request complete from the producer's point of view.
| Acknowledgement mode | Completion result | Delivery meaning |
|---|---|---|
0 | Futures resolve with None | The producer does not wait for a broker reply and cannot learn a broker offset or most send failures. |
1 | Futures resolve after the leader acknowledges | The leader has accepted the record before completion. Followers may not have copied it yet. |
all | Futures resolve after the in-sync replicas acknowledge | The strongest broker-side durability mode. Idempotent mode requires this setting. |
For acknowledged success, the broker returns a base offset for the batch. The batch adds each record's relative offset to that base offset and resolves its record future with the resulting metadata. A broker timestamp is used when available; older response versions cause the producer to use the timestamp stored with the record.
References: aiokafka/…/producer.py• L78-100 aiokafka/…/producer.py• L271-285 aiokafka/…/sender.py• L750-799 aiokafka/…/sender.py• L810-890 aiokafka/…/message_accumulator.py• L201-265
Retry and re-enqueue flow
The sender classifies transport and partition-level errors before deciding whether a batch can be tried again. A retriable batch returns to the front of its topic-partition queue after a backoff. When an error marks metadata as stale, the sender also requests a metadata refresh and waits for that refresh before the next attempt.
Retry behavior differs by delivery mode:
- A normal batch stops retrying when its time-to-live expires. A final error is copied to the batch future and to each unfinished record future.
- An idempotent or transactional batch does not expire during normal broker retries. Producer identity, epoch, and sequence state prevent a successful retry from creating a duplicate record.
- A duplicate sequence response is treated as success. It means the broker has already advanced past the batch sequence, but the returned offset may not describe the original records.
The sender keeps the partition muted while its request is in flight. It removes that protection after the request finishes, including after re-enqueue, so a later attempt can be dispatched in order. If the sender task itself fails, its completion callback fails all batches that remain in the accumulator and marks transaction state as fatal when transactions are enabled.
References: aiokafka/…/sender.py• L77-88 aiokafka/…/sender.py• L778-889 aiokafka/…/message_accumulator.py• L557-561 aiokafka/…/message_accumulator.py• L371-373
Completion results
Completion is the point where broker state becomes caller-visible state. Success resolves the batch future and all unfinished record futures. No-ack completion resolves them with None. A failed batch resolves them with exceptions so the caller can distinguish a delivery failure from a scheduling timeout.
The producer's send_and_wait method waits for the record future and returns its metadata. Cancelling that returned future does not stop the record from being sent. Cancelling the send coroutine itself does stop scheduling. flush waits for all known batch futures, including batches already handed to the sender. Closing the producer stops new work, flushes the accumulator, and then closes the sender and client connections.
The accumulator also reports batch lifecycle events around dispatch, completion, failure, and time spent waiting for buffer space through producer listeners. These callbacks observe the same state transitions as the delivery futures and do not change the delivery result when a listener callback fails.
References: aiokafka/…/message_accumulator.py• L201-323 aiokafka/…/message_accumulator.py• L425-462 aiokafka/…/producer.py• L375-398 aiokafka/…/producer.py• L478-490 aiokafka/…/producer.py• L526-537
Transactional delivery boundary
Transactions add a coordination step around the same accumulation and produce path. Before a transactional batch is sent, the sender makes sure its partition is part of the active transaction. It also assigns producer identity and sequence state to a first attempt, while retries reuse the batch's encoded data and sequence state.
The sender performs at most one transaction-coordination request at a time. It mutes partitions that still need to be added to the transaction, so a produce request cannot race with partition registration. On commit, the accumulator closes the batches that belong to the current scope and waits for them before the sender sends the transaction end request. The transaction then completes only after the coordinator acknowledges the commit or abort.
See Producer transactions for the transaction state model and coordinator flow. The parent page Producer subsystem places this delivery path beside partition selection and the public producer API.
References: aiokafka/…/message_accumulator.py• L530-555 aiokafka/…/message_accumulator.py• L433-449 aiokafka/…/sender.py• L110-143 aiokafka/…/sender.py• L297-385 aiokafka/…/producer.py• L590-639
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the batch future and per-record futures aligned when changing broker response parsing. A changed offset or timestamp field must still map to every record's relative offset.
- Keep the accumulator's pending and per-partition queues in sync when changing retry or completion paths. A batch must be in one delivery state at a time.
- Keep acknowledgement configuration consistent with no-ack completion and idempotent delivery. Idempotent mode must not silently fall back to an acknowledgement mode that cannot support its retry guarantee.
- Keep metadata refresh and partition muting aligned when changing leader error handling. A new request must not overtake an in-flight request for the same topic-partition.
- Keep sender-task failure handling aligned with accumulator and transaction state. A background sender failure must fail pending delivery futures and make transactional state unusable.
- Keep transaction partition registration ahead of produce dispatch when changing transactional sender scheduling.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| The per-partition buffer stays full until the request timeout | send raises KafkaTimeoutError before the record is scheduled | The caller must allow the sender to drain the batch or increase the available time and batch capacity. |
| A batch has no usable leader until its lifetime expires | The batch future and its record futures fail with a leader error | The sender refreshes metadata while the batch is still valid. |
| A non-idempotent retryable batch expires | The sender stops retrying and reports the broker error to the caller | Use idempotence when the application needs retry without the normal batch lifetime limit. |
A produce request uses acks=0 | Futures resolve without offsets and broker failures are not known through the response | Use an acknowledged mode when the caller needs delivery metadata or broker error reporting. |
| The sender task fails | All pending batches fail and transactional state becomes fatal when transactions are enabled | Treat sender task failure as producer failure and recreate the producer before sending more records. |
| A transactional partition is produced before registration | The transaction flow can race with the coordinator and the transaction can fail | The sender mutes pending partitions until registration succeeds. |
Key files
| File | Why to read it |
|---|---|
| aiokafka/…/producer.py | Shows the public send, batch, flush, close, and transaction boundaries that enter and leave the pipeline. |
| aiokafka/…/message_accumulator.py | Defines per-topic-partition buffering, batch lifetime, backpressure, dispatch grouping, retry re-enqueue, future completion, and producer listener events. |
| aiokafka/…/sender.py | Defines the background loop, broker request creation, acknowledgement handling, retry decisions, in-flight partition control, sender failure handling, and transaction coordination. |
| aiokafka/…/transaction_manager.py | Explains the producer identity and transaction state that the sender uses when delivery is idempotent or transactional. |
| tests/test_message_accumulator.py | Demonstrates batch size limits, linger, unknown leaders, timeout behavior, completion, and re-enqueue invariants. |
| tests/test_sender.py | Demonstrates produce request construction, response mapping, retry outcomes, sender failures, and transaction coordination responses. |