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 / consumer-fetch-and-position

Consumer fetch and position management

The consumer fetch system retrieves records in the background, keeps them ready for asynchronous callers, and tracks the next offset for each assigned partition. It ties record delivery to subscription state so that seeks, pauses, rebalances, and offset resets do not return data from an old ownership or position.

Fetcher role

The fetcher is the bridge between Kafka fetch responses and the consumer's getone and getmany APIs. The public consumer starts it with the current subscription state, while the fetcher manages broker requests and wakes callers when records or fetch errors become available (aiokafka/…/consumer.py• L370-399, aiokafka/…/fetcher.py• L380-439).

Background fetch cycle

The background fetch cycle waits for an active assignment, checks each partition's state, and chooses one of three actions: fetch records, obtain a position, or wait for a paused or backoff partition. It groups fetch work by broker and can refresh metadata when a leader is not known. When rack-aware reads are active, it can use a broker-selected preferred replica for fetches. It falls back to the leader when that choice expires, becomes unknown, or fails. The cycle also stops work and clears its buffered results when the assignment is lost, then starts again for the next assignment.

The main stages are:

  1. Wait for a subscription with an active assignment.
  2. Resolve missing positions from committed offsets or the reset policy.
  3. Build fetch requests for assigned, positioned, and unpaused partitions.
  4. Store successful responses by topic-partition.
  5. Wake waiting callers and fetch again after they consume the stored records.

This diagram shows how assignment state controls the path from a broker response to a caller-visible record.

flowchart TD
    A[Active assignment] --> B{Valid position?}
    B -- No --> C[Load committed or reset offset]
    C --> D[Fetch from broker]
    B -- Yes --> E{Paused or buffered?}
    E -- Paused --> F[Wait for resume]
    E -- Buffered --> G[Wait for caller consumption]
    E -- Ready --> D
    D --> H{Response matches current state?}
    H -- No --> I[Discard response]
    H -- Yes --> J[Buffer partition records]
    J --> K[Deliver to getone or getmany]
    K --> L[Advance position]
    L --> D

References: aiokafka/…/fetcher.py• L470-571 aiokafka/…/fetcher.py• L573-673 aiokafka/…/fetcher.py• L733-903

Caller delivery

getone returns one record from the buffered partitions and waits when no record is ready. getmany drains available records into a map keyed by topic-partition and can wait for more data up to its timeout. Both APIs use the same fetcher buffer, so a caller consumes prefetched data before another broker request is needed (aiokafka/…/consumer.py• L1103-1200, aiokafka/…/fetcher.py• L1154-1257).

The fetcher keeps errors in the same per-partition result path as records. If a call has already received data from another partition, it returns that data first and exposes the pending error on a later call. This prevents one partition's error from discarding records that were ready on another partition.

References: aiokafka/…/fetcher.py• L1154-1196 aiokafka/…/fetcher.py• L1198-1257 aiokafka/…/consumer.py• L1147-1199

Record buffering

The fetcher stores an in-memory result for each partition rather than exposing a broker response directly. A result contains a record iterator and the assignment that was current when the fetch started. This lets the consumer read records at its own pace while the fetch loop avoids replacing a partition's unread batch too quickly (aiokafka/…/fetcher.py• L57-143, aiokafka/…/fetcher.py• L594-606).

Partition record visibility

The partition record stream turns fetched batches into ConsumerRecord values as the caller reads them. It advances across gaps caused by log compaction and across control batches even when those batches produce no visible record. With committed isolation, it also hides records from aborted transactions. The tracked next fetch offset therefore moves past broker data that the caller does not receive.

Deserializers are applied when a record becomes a consumer record. CRC checks and message-size checks protect the boundary between broker data and caller-visible data. Failures remain associated with the affected partition.

References: aiokafka/…/fetcher.py• L165-205 aiokafka/…/fetcher.py• L206-321 aiokafka/…/fetcher.py• L820-876

Fetch limits and read replicas

Fetch requests combine per-partition limits with request-wide byte and wait limits. These limits control how much data can enter the buffer and how long Kafka may wait for enough data. When rack-aware fetching is enabled and supported by the broker, the response can guide later reads toward a preferred replica. The fetcher keeps that choice for a limited time. It removes the choice when it expires, when the node is no longer known, or when a fetch returns an error. A transport failure also removes matching entries from the failed request so later requests can return to the partition leader.

References: aiokafka/…/fetcher.py• L335-377 aiokafka/…/fetcher.py• L632-673 aiokafka/…/fetcher.py• L675-731 aiokafka/…/fetcher.py• L762-814 aiokafka/…/fetch.py• L190-219

Position lifecycle

The position is the offset of the next record the consumer will fetch for a partition. It is local consumption state. A committed offset is a recovery point stored for a group, so the fetcher uses it to establish a position but advances the position as records are delivered.

Initial and reset positions

Each newly assigned partition starts without a valid position. The fetcher first asks for the committed offset when group state supplies one. If no committed offset exists, or a fetch reports that the current offset is outside the available log, it applies auto_offset_reset: earliest selects the oldest available offset, latest selects the newest available offset, and none reports an error instead.

The reset request uses offset lookup against the partition leader. A seek or a new assignment can change the requested position while that lookup is in progress, so the fetcher checks the current partition state before applying the result.

References: aiokafka/…/fetcher.py• L19-54 aiokafka/…/fetcher.py• L909-988 aiokafka/…/fetcher.py• L869-892 aiokafka/…/subscription_state.py• L443-545

Delivered position

The partition state advances when the fetcher yields a record or finishes processing a buffered batch. The stored value is the next fetch offset, not the offset of the last record returned. This makes the value suitable for later fetches and for group offset commits (aiokafka/…/subscription_state.py• L418-425, aiokafka/…/subscription_state.py• L528-545).

The fetcher updates position even when a fetched batch contains only skipped data. This avoids asking Kafka for the same control, aborted, or compacted data again. A caller can read the position through consumer.position; highwater and last stable offset are separate broker observations and do not change it (aiokafka/…/consumer.py• L652-735).

References: aiokafka/…/fetcher.py• L105-137 aiokafka/…/fetcher.py• L245-271 aiokafka/…/consumer.py• L652-735

Explicit position changes

seek sets a partition's position immediately and removes its old buffered result. seek_to_beginning and seek_to_end mark the partition for an asynchronous reset, then wait for the new position or for the assignment to disappear. These operations wake the fetch loop so the next request uses the new offset (aiokafka/…/consumer.py• L755-862, aiokafka/…/fetcher.py• L1282-1312).

Offset lookups by time, beginning offset, and end offset are read-only queries. They return broker offsets without changing the active position. A caller that wants to consume from one of those offsets must seek to it separately (aiokafka/…/consumer.py• L905-1011, aiokafka/…/fetcher.py• L1259-1280).

References: aiokafka/…/consumer.py• L755-903 aiokafka/…/consumer.py• L905-1011 aiokafka/…/fetcher.py• L1259-1312

Subscription state

SubscriptionState is the shared state boundary between the consumer API, the group coordinator, and the fetcher. It records the current subscription, assignment, reassignment status, pause state, committed-offset requests, and per-partition position. The fetcher uses this state as the authority for whether data may be requested or returned (aiokafka/…/subscription_state.py• L27-43, aiokafka/…/subscription_state.py• L231-304).

Assignment ownership

An assignment gives each topic-partition its own state object. Automatic assignment creates a new assignment during a group change; manual assignment replaces the prior assignment without group rebalancing. When an assignment or subscription becomes inactive, its futures notify the fetcher so old requests and buffered records cannot continue as if ownership were unchanged.

The fetcher checks assignment activity and the current position both when it receives a broker response and when it is about to deliver a buffered record. This protects callers from records fetched before a rebalance or a seek.

References: aiokafka/…/subscription_state.py• L108-229 aiokafka/…/subscription_state.py• L307-425 aiokafka/…/fetcher.py• L72-103 aiokafka/…/fetcher.py• L751-793

Pause and resume state

Pausing a partition keeps it assigned but removes it from fetch work and caller delivery. Resuming completes a wait signal used by the fetch loop. Pause therefore controls flow for one partition without causing a group rebalance or changing its position (aiokafka/…/consumer.py• L1202-1242, aiokafka/…/fetcher.py• L585-630).

References: aiokafka/…/subscription_state.py• L273-286 aiokafka/…/subscription_state.py• L557-568 aiokafka/…/consumer.py• L1202-1242

Reassignment boundaries

During reassignment, the fetcher does not return prefetched records. It waits for the next active assignment, cancels work for the old assignment, and clears its buffer. Pending caller waiters can receive coordination errors from subscription state, while normal assignment changes cause the fetcher to resume with the new partition states.

This boundary is why rebalance listeners should finish work on records that must be processed before a seek or ownership change. A seek in the middle of buffered consumption can intentionally discard those buffered records (aiokafka/…/consumer.py• L763-766).

References: aiokafka/…/fetcher.py• L500-519 aiokafka/…/fetcher.py• L1200-1206 aiokafka/…/subscription_state.py• L221-271 aiokafka/…/consumer.py• L1013-1046

Fetch and position management depends on two surrounding flows. The consumer subsystem provides the public lifecycle and polling surface in consumer-subsystem. Group coordination supplies committed offsets and automatic assignments; see consumer-group-coordination.

Offset observations

Each successful fetch also records the partition highwater offset, the last stable offset when supported, and the time of the fetch. These values help callers measure lag and transaction visibility. They describe broker state at the last fetch. They are not promises that a record is ready or that the consumer position has changed.

References: aiokafka/…/fetcher.py• L795-823 aiokafka/…/consumer.py• L695-753

Change checklist

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

  • Changes to the partition result contract must preserve the link between the buffered next offset and TopicPartitionState.position.
  • Changes to assignment or reassignment signaling must preserve both fetch-task cancellation and caller waiting behavior.
  • Changes to fetch response versions must keep isolation data, error handling, and preferred-replica fields aligned with the selected protocol version.
  • Changes to seek or reset behavior must invalidate buffered results before the next fetch uses the new position.
  • Changes to committed-offset refresh must keep the distinction between a group commit and the local next-fetch position.

Important failure modes

TriggerConsequenceGuard
A fetch response returns after a seek or rebalanceOld records are not delivered, and the response is discardedCheck assignment activity and compare the response offset with the current position before buffering or delivery (aiokafka/…/fetcher.py• L72-103, aiokafka/…/fetcher.py• L751-793)
The broker reports an offset outside the available logThe partition cannot fetch at its current positionApply the configured reset policy or store OffsetOutOfRangeError when the policy is none (aiokafka/…/fetcher.py• L869-892)
No committed offset exists for an assigned partitionThe partition has no starting positionUse earliest or latest, or expose NoOffsetForPartitionError for none (aiokafka/…/fetcher.py• L919-943)
The first message exceeds the per-partition fetch limitThe partition cannot make progress from that offsetStore RecordTooLargeError and require a compatible fetch or broker message limit (aiokafka/…/fetcher.py• L820-867)
A topic read is not authorizedCalls waiting for data receive the authorization errorStore the error for the partition and wake fetch waiters (aiokafka/…/fetcher.py• L893-897, aiokafka/…/fetcher.py• L1215-1238)
A partition is paused while a result is bufferedThe result is not returned while the partition is pausedCheck pause state before yielding and wait for resume (aiokafka/…/fetcher.py• L72-103, aiokafka/…/subscription_state.py• L557-568)
A preferred read replica becomes unreachableFetch retries do not remain pinned to the failed followerEvict cached entries for the failed request and fall back to the leader (aiokafka/…/fetcher.py• L717-745)

Key files

FileWhy to read it
aiokafka/…/fetcher.pyDefines the background fetch cycle, per-partition buffering, record delivery, offset reset, and stale-result protection.
aiokafka/…/subscription_state.pyDefines the shared subscription, assignment, pause, reassignment, and position state used by the fetcher.
aiokafka/…/consumer.pyShows the public polling, position, seek, pause, and resume APIs that drive the fetcher.
aiokafka/…/fetch.pyDescribes the broker request and response shapes that carry fetch offsets, records, transaction data, and preferred replicas.