Client event listener instrumentation
Client event listener instrumentation gives applications callback points for producer delivery work and consumer partition changes. The library does not own metric storage or export. An application connects these callbacks to its monitoring system and controls labels, aggregation, and alerts. This page is part of Observability and client utilities, with related producer, consumer, and connectivity behavior described in Producer subsystem, Consumer subsystem, and Client and cluster connectivity.
Listener model
Event scope
The library has two listener contracts with different purposes. ProducerListener reports work in the producer's delivery path. ConsumerRebalanceListener reports changes to a consumer's automatically managed partition assignment. Neither contract reports every record or every network operation.
| Listener | Event scope | Typical monitoring use |
|---|---|---|
ProducerListener | Batch attempts, final batch outcomes, and buffer waits | Delivery rate, retry rate, latency, failure rate, and queue pressure |
ConsumerRebalanceListener | Partition revocation and assignment around a group rebalance | Rebalance count, assignment changes, and rebalance duration |
AIOKafkaClient | No public monitoring listener stream | Application-level tracking of client start and stop, plus logs or other client metrics |
Producer events describe batches rather than individual record latency. A batch can contain records added at different times, so batch_age_seconds is an upper bound for record latency. All producer duration values use seconds. Empty batches produce no lifecycle events.
References: aiokafka/listeners.py• L11-75 aiokafka/abc.py• L4-84 aiokafka/client.py• L190-202
Batch lifecycle
The producer exposes the path from queue entry to a final outcome. A retry starts another dispatch attempt, but it does not create another completion or failure event for the same batch.
This diagram shows how producer activity becomes listener callbacks and then becomes application metrics.
flowchart LR
A[Record or batch submission] --> B[Accumulator queue]
B -->|space wait| W[Buffer-wait callback]
B --> D[Dispatch callback]
D -->|retry| D
D --> C[Completion callback]
D --> F[Failure callback]
W --> M[Application collector]
D --> M
C --> M
F --> M
M --> E[Monitoring integration]
References: aiokafka/…/message_accumulator.py• L256-324 aiokafka/…/message_accumulator.py• L346-363
Listener registration
Producer registration
ProducerListener is the registration contract between a producer and an application integration. An application derives a listener and overrides only the events it needs. AIOKafkaProducer validates the supplied listeners when it is created and passes the registered set to the producer's batch path.
Registration takes a snapshot of the iterable. Each listener must be a ProducerListener, and the same instance cannot be registered more than once. With the default empty collection, the producer has no listener callbacks.
References: aiokafka/listeners.py• L11-19 aiokafka/listeners.py• L77-86 aiokafka/…/producer.py• L183-185 aiokafka/…/producer.py• L204-236 aiokafka/…/producer.py• L300-336
Consumer registration
ConsumerRebalanceListener is registered through AIOKafkaConsumer.subscribe, where it follows a topic or pattern subscription. The listener receives callbacks before partitions leave the consumer and after the new assignment is ready. A later subscription replaces the earlier listener. Manual partition assignment does not use this callback path because it does not join a consumer group.
The consumer validates the listener type before storing it with the subscription state. Unsubscribing clears the stored listener, so monitoring code must register it again on a later subscription.
References: aiokafka/…/consumer.py• L1022-1094 aiokafka/…/subscription_state.py• L138-177 aiokafka/…/subscription_state.py• L179-193 aiokafka/abc.py• L4-18
Callback behavior
Producer listener methods have no-op defaults. The producer keeps only methods that a listener overrides, so an integration can subscribe to one event without receiving unused calls. Callbacks run synchronously in registration order on the producer path.
Producer callback failures are logged and do not stop later listeners or normal producer work. Listener code must stay fast and non-blocking. An application should place slow or asynchronous work on its own queue. Consumer rebalance callbacks are different: the consumer waits for them during the rebalance before it continues group coordination.
References: aiokafka/listeners.py• L21-75 aiokafka/listeners.py• L89-107 aiokafka/…/message_accumulator.py• L22-28 aiokafka/abc.py• L36-45
Notification paths
Producer callback path
The batch accumulator notifies listeners when it hands a non-empty batch to the sender, when the batch completes, when it fails, and when a producer operation waits for space. A successful completion records whether the producer received an acknowledgment. With acks=0, completion is reported as unacknowledged because the producer does not wait for a broker response.
The buffer-wait notification is emitted after the send operation finishes waiting. Its duration includes all waits in that operation, and it is still reported when the operation later times out or fails.
References: aiokafka/…/message_accumulator.py• L256-324 aiokafka/…/message_accumulator.py• L352-363 aiokafka/…/message_accumulator.py• L472-530 aiokafka/…/producer.py• L440-582
Retry reporting
Retries are visible through repeated dispatch events. Each dispatch includes an attempt number and measures queue time only for that attempt. Batch size and record count also describe that attempt, so an exporter must not use dispatch events to count final delivered records when retries are possible. Use completion record counts for that purpose.
References: aiokafka/listeners.py• L21-37 aiokafka/…/message_accumulator.py• L346-363 docs/metrics.rst• L59-68
Consumer rebalance path
The consumer stores the rebalance listener with its subscription. The group coordinator invokes the listener during automatic assignment changes: it first signals revoked partitions, then completes the group assignment and signals assigned partitions before fetching resumes. This makes the callbacks suitable for saving offsets or clearing state at ownership boundaries, as well as for rebalance metrics.
The path does not run for direct assign use. It also does not run before normal consumer shutdown. Monitoring integrations that need start or stop signals must record those boundaries around the consumer API calls separately.
References: aiokafka/…/consumer.py• L379-455 aiokafka/…/consumer.py• L515-530 aiokafka/…/consumer.py• L1022-1061 aiokafka/abc.py• L47-84
Shared client path
AIOKafkaClient is the shared connection and metadata service used by producers and consumers. It has no public listener interface for bootstrap, request, fetch, connection, start, or stop events. Its internal connection-close callback marks metadata as stale and requests a refresh; it is a client control path, not a monitoring callback contract.
Producer and consumer shutdown call the shared client after their own work is complete. Monitoring code should therefore measure those lifecycle boundaries at the producer or consumer API level instead of expecting client listener notifications.
References: aiokafka/client.py• L190-202 aiokafka/client.py• L259-286 aiokafka/client.py• L395-400 aiokafka/client.py• L429-457 aiokafka/…/producer.py• L365-398 aiokafka/…/consumer.py• L379-390 aiokafka/…/consumer.py• L515-530
Lifecycle coverage
Producer lifecycle events
Producer listeners cover the part of the producer lifecycle that affects record delivery. They show queue pressure, each send attempt, final success, acknowledgment mode, total batch age, and final failure. Producer start and stop are not separate listener events. Normal shutdown instead flushes pending batches and closes the sender and shared client.
References: aiokafka/…/producer.py• L365-398 aiokafka/…/message_accumulator.py• L433-470
Consumer lifecycle events
Consumer monitoring has two separate surfaces. Rebalance listeners expose automatic partition ownership changes. Consumer start and stop expose the broader client, fetcher, and coordinator lifecycle only through awaited API calls, so an integration must record those boundaries around the calls.
References: aiokafka/…/consumer.py• L379-455 aiokafka/…/consumer.py• L515-530 aiokafka/…/consumer.py• L1022-1094
Monitoring integration
Collector mapping
The library does not create, store, aggregate, sample, or export metric values. A listener converts callback data into the metric types required by the chosen monitoring system. A Prometheus example observes durations and sizes in histograms and counts retries, completed records, failed batches, and buffer waits.
Applications choose labels such as topic, partition, acknowledgment state, and exception type. That choice defines the cost and usefulness of the resulting metric set. Rebalance listeners can add assignment-oriented metrics, while client start and stop metrics belong around the owning producer or consumer.
References: docs/metrics.rst• L11-24 docs/metrics.rst• L109-160 examples/prometheus_metrics.py• L3-47 aiokafka/…/consumer.py• L1022-1061
Change checklist
When these files or sections are changed, remember to consider these:
- Keep listener method names and keyword fields aligned between
ProducerListener, producer registration, accumulator notification, and every listener subclass. - Keep retry semantics separate from final batch outcome metrics so a retried batch does not inflate delivery counts.
- Keep acknowledgment labels consistent with the
acks=0meaning of unacknowledged completion. - Preserve listener ordering, duplicate-instance rejection, and callback error isolation when changing producer registration behavior.
- Keep consumer listener replacement, manual-assignment exclusions, and callback ordering aligned with subscription and coordinator behavior.
- Review topic, partition, outcome, and exception labels before changing them because monitoring queries and series counts depend on them.
- Do not imply client connection or shutdown events are emitted by a listener unless a new public client contract is added.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A producer listener blocks in a synchronous callback | Producer send work is delayed | Send slow work to an application queue |
| A producer listener callback raises an exception | The event can be lost while the producer continues | Log and track listener errors outside the producer path |
| A dispatch event is used to count delivered records | Retries can cause double counting | Count records from the completion event |
acks=0 is treated as broker acknowledgment | Monitoring reports stronger delivery proof than the producer has | Keep unacknowledged completion as a separate label or outcome |
| A rebalance listener performs slow work | Group reassignment is delayed | Bound callback work and move non-critical work out of the rebalance path |
| A monitoring integration expects callbacks for manual assignment or shutdown | Assignment or lifecycle metrics are missing | Instrument the surrounding consumer API calls and use group subscriptions for rebalance events |
| Per-exception or per-topic labels grow without bound | The monitoring backend receives too many time series | Apply a fixed label policy in the listener |
Key files
| File | Why to read it |
|---|---|
| aiokafka/listeners.py | Defines the producer listener contract, callback selection, and registration rules. |
| aiokafka/…/producer.py | Shows how applications register listeners and how producer start and stop bound delivery work. |
| aiokafka/…/message_accumulator.py | Shows where queue, dispatch, completion, failure, and wait events enter the notification path. |
| aiokafka/…/sender.py | Shows how broker results and retries lead to batch outcomes. |
| aiokafka/…/consumer.py | Shows consumer listener registration and the consumer lifecycle boundaries. |
| aiokafka/abc.py | Defines the consumer rebalance callback contract and its ordering guarantees. |
| aiokafka/…/subscription_state.py | Connects a registered rebalance listener to the consumer's subscription state. |
| aiokafka/client.py | Shows the shared client lifecycle and why connection events are not a public monitoring listener stream. |
docs/metrics.rst | Defines producer callback meaning and shows monitoring adapter choices. |
| examples/prometheus_metrics.py | Shows one monitoring integration and its metric choices. |