Observability and client utilities
This shared layer gives the public clients common ways to report producer activity, encode data, choose partitions, describe results, and manage async work. It keeps client-facing behavior consistent while allowing the producer and consumer flows to focus on Kafka operations.
Shared system role
The utility layer sits below the public producer, consumer, and admin clients. It turns client events into stable values and signals that other parts of the library can use without depending on a monitoring system or a particular broker connection.
The main responsibilities are:
- report producer batch lifecycle events to an application-owned collector;
- encode and decode compressed or variable-length data used by records;
- map keys to partitions with Kafka-compatible behavior;
- expose shared records, offsets, broker, and partition values;
- classify broker failures for retry and metadata refresh decisions; and
- provide common async, version, SSL, and compatibility helpers.
Metrics collection and reporting
Producer observability uses an optional callback object. The client emits events but does not store, aggregate, sample, or export metrics. Applications connect the callbacks to a monitoring library such as Prometheus through the child page Metrics instrumentation.
Producer lifecycle signals
ProducerMetricsCollector describes four producer signals: a batch is dispatched, a batch completes, a batch fails, or a send waits for buffer space. The default callbacks do nothing, so an application can observe only the events it needs.
The events have different scopes. Dispatch is reported for each attempt, including retries. Completion and failure are reported once for the batch. Buffer wait is reported once for one send operation and can include several wait periods.
flowchart LR
Send[Producer send] --> Wait[Buffer wait]
Send --> Batch[Batch]
Batch --> Dispatch[Dispatch attempt]
Dispatch --> Retry{Retry needed?}
Retry -->|yes| Dispatch
Retry -->|no| Outcome{Terminal outcome}
Outcome --> Complete[Completed]
Outcome --> Failed[Failed]
Wait --> Collector[Metrics collector]
Dispatch --> Collector
Complete --> Collector
Failed --> Collector
All duration values use seconds. Batch age includes retries and is an upper bound for record latency because records can enter a batch at different times. A completion with acknowledged=False means that the producer finished without waiting for a broker acknowledgment, such as with acks=0.
References: aiokafka/metrics.py• L15-103 aiokafka/…/message_accumulator.py• L22-27 aiokafka/…/message_accumulator.py• L255-323
Reporting boundary
The producer accepts only a ProducerMetricsCollector instance and uses a no-op collector when none is supplied. Callbacks run synchronously on the producer path, so they must be fast and non-blocking. A collector error is logged and ignored so monitoring cannot change message delivery behavior.
This boundary keeps metric storage outside the client. The application chooses the metric names, labels, aggregation, and export path. The experimental status of this API means callback names and event details can change without a deprecation period.
References: aiokafka/…/producer.py• L178-181 aiokafka/…/producer.py• L301-307 aiokafka/…/message_accumulator.py• L22-27 aiokafka/__init__.py• L3-22
Data encoding and client values
Shared codecs and value objects define the data contracts used by record handling and public client calls. They hide wire-format choices from higher-level flows while preserving Kafka-compatible bytes and metadata.
Compression codecs
The codec layer provides one common boundary for gzip, Snappy, LZ4, and Zstandard data. It reports which codecs are available, applies Kafka-compatible framing where required, and raises a clear error when a requested codec is not installed.
Record formats use this boundary when they compose compressed batches or expand them for reading. Gzip is available from the standard runtime. Snappy and LZ4 depend on the optional cramjam package, while Zstandard uses the Python runtime support when available and otherwise uses cramjam. Client configuration can fail before sending data when its selected codec is unavailable.
References: aiokafka/codec.py• L14-32 aiokafka/codec.py• L35-49 aiokafka/codec.py• L51-65 aiokafka/codec.py• L67-209 aiokafka/…/producer.py• L190-264
Public data structures
The shared structures give clients named values for the objects that cross their boundaries. TopicPartition identifies a stream location. RecordMetadata describes a produced record. ConsumerRecord carries a consumed record and its serialized sizes. Offset and broker structures carry commit state and cluster placement data.
These values preserve the link between a record and its topic, partition, offset, timestamp, and headers. They let producer results, consumer records, metadata views, and commit inputs use the same vocabulary across client flows.
References: aiokafka/structs.py• L19-27 aiokafka/structs.py• L29-68 aiokafka/structs.py• L70-120 aiokafka/structs.py• L127-160
Partitioning and error semantics
Partitioning and errors express two decisions that affect client behavior: where a record should go and what the client should do when Kafka rejects or cannot complete an operation. Both are shared so producer and client flows apply the same rules.
Partition selection
DefaultPartitioner uses the record key to select a stable partition. It applies Kafka's Murmur2 hash to keyed records. For records without a key, it chooses from available partitions when possible and falls back to all partitions when none are marked available.
Applications can provide another partitioner when they need a different placement policy. A custom policy must return a partition from the supplied set because the producer uses the result to route the record to a broker.
References: aiokafka/partitioner.py• L4-29 aiokafka/partitioner.py• L32-96 aiokafka/…/producer.py• L209-215
Error classification
The error model turns broker error codes and local client conditions into named exceptions. BrokerResponseError subclasses retain the broker code and description. for_code maps a response code to its class and uses UnknownError when the code is not known.
Errors also carry recovery hints. A retriable error permits a later attempt, while invalid_metadata tells shared client flows to refresh their view of brokers and partitions. Other errors describe invalid input, authorization failure, unsupported features, or a terminal client state and should reach the caller instead of triggering blind retries.
References: aiokafka/errors.py• L81-127 aiokafka/errors.py• L235-285 aiokafka/errors.py• L295-327 aiokafka/errors.py• L864-877
Compatibility and runtime helpers
The helper layer keeps the clients usable across supported Python runtime setups. It validates commit values at public boundaries and controls timeout and cancellation behavior. It also exposes shared runtime flags and integer bounds without changing the client APIs.
Commit compatibility
commit_structure_validate normalizes supported offset input forms into OffsetAndMetadata values. It requires a non-empty mapping keyed by TopicPartition, which gives commit flows one shape to send to Kafka even when callers use a plain offset or an offset-and-metadata pair.
References: aiokafka/util.py• L47-71 aiokafka/structs.py• L19-27 aiokafka/structs.py• L70-83
Async and optional runtime support
The async helpers provide a timeout boundary and a cancellation helper that waits for cleanup and surfaces real task errors. Record utilities select accelerated implementations when available and fall back to Python implementations when extensions are disabled or cannot load.
The SSL helper creates a server-authentication context with hostname checks enabled. It can load trusted certificate data and an optional client certificate chain, which gives public clients one consistent setup path for secure broker connections.
References: aiokafka/util.py• L20-44 aiokafka/util.py• L74-77 aiokafka/…/util.py• L117-150 aiokafka/helpers.py• L14-90
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to collector callback names or arguments must stay aligned with producer event calls and with integrations that use topic and partition labels.
- Changes to codec availability or framing must stay aligned with both legacy and default record formats and with the producer's compression validation.
- Changes to
TopicPartition, offset values, or commit normalization must preserve the input shape expected by commit and metadata flows. - Changes to error codes or recovery flags must preserve the mapping from broker responses to retry and metadata-refresh behavior.
- Changes to task, future, timeout, or cancellation helpers must preserve cleanup behavior expected by client shutdown paths.
- Changes to optional record extensions must keep the Python fallback and the
AIOKAFKA_NO_EXTENSIONSpath behaviorally equivalent.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A selected optional compression library is not installed | Producer setup fails before it can send records | Check codec availability before enabling the compression type |
| A metrics callback blocks or performs slow async work directly | The producer hot path is delayed | Queue work for a separate task and keep callbacks non-blocking |
| A metrics callback raises an exception | The callback event is lost, but producer delivery continues | Log the callback failure and inspect collector behavior |
| A broker returns a retriable error with stale metadata | Repeating the same route can fail again | Use the error's retry and metadata-refresh hints |
Commit input is not a non-empty mapping of TopicPartition values | Commit validation raises before a request is sent | Normalize offsets through commit_structure_validate |
| A timeout expires while an awaitable is still running | The operation stops at the timeout boundary | Set a timeout that matches the operation and handle timeout cancellation |
| A caller is cancelled while a task is cleaning up | Caller cancellation can interrupt the wait before cleanup finishes | Use the cancellation helper and account for cleanup before shutdown completes |
Key files
| File | Why to read it |
|---|---|
| aiokafka/metrics.py | Defines the public producer event contract and callback defaults. |
| aiokafka/…/message_accumulator.py | Shows where dispatch, completion, failure, and buffer-wait signals enter the producer flow. |
| aiokafka/codec.py | Defines shared compression capability checks and encode/decode boundaries. |
| aiokafka/partitioner.py | Explains default key-based and unkeyed partition selection. |
| aiokafka/errors.py | Defines broker error classes and the recovery hints used by clients. |
| aiokafka/structs.py | Defines the shared topic, partition, record, broker, and offset values. |
| aiokafka/util.py | Provides commit normalization, timeout and cancellation behavior, plus shared runtime constants. |
| aiokafka/…/util.py | Shows the portable and accelerated record utility paths. |
| aiokafka/helpers.py | Provides the shared SSL context setup for secure clients. |