Kafka consumer subsystem
The Kafka consumer subsystem turns a Kafka topic subscription into an ordered stream of ConsumerRecord values. It keeps subscription state, partition ownership, background fetch work, read positions, and group offsets in step while the application consumes data through the async consumer API. It relies on client and cluster connectivity to reach brokers and works with metrics instrumentation for operational insight.
Consumer lifecycle
The lifecycle starts when the consumer loads cluster metadata and selects a way to own partitions. It then prepares each partition position, fetches data in the background, returns records to the application, and stores progress as offsets.
flowchart LR
A[Application] --> B[Subscription]
B --> C{Partition ownership}
C -->|Consumer group| D[Group coordinator]
C -->|Manual assignment| E[Local assignment]
D --> F[Active assignment]
E --> F
F --> G[Position setup]
G --> H[Background fetch]
H --> I[Deserialize and filter]
I --> A
I --> J[Consumed position]
J --> K[Offset commit]
Subscription and assignment
Subscription state is the shared contract between the public consumer, the group coordinator, and the fetcher. It records which topics or partitions the consumer should use and exposes change signals so async tasks do not keep using an old assignment.
Subscription modes
The consumer supports topic subscription, pattern subscription, and direct partition assignment. Topic and pattern subscriptions use automatic ownership when a group is configured; direct assignment gives this consumer its partitions and does not cause group rebalances.
subscribe(topics=...)follows named topics.subscribe(pattern=...)follows topics that match a pattern as metadata changes.assign(...)selects exactTopicPartitionvalues and cannot be combined with subscription.
See consumer group coordination for the group path and group assignment strategies for how a group spreads partitions across members.
References: aiokafka/…/consumer.py• L458-487 aiokafka/…/consumer.py• L1013-1085 aiokafka/…/subscription_state.py• L136-177
Assignment state
An assignment creates one state record per partition. That state tracks whether the partition is waiting for a starting offset, consuming, paused, or no longer assigned. A new assignment makes the old one inactive, which lets the fetcher stop work and prevents records from the old owner from reaching the application.
The assignment also carries wait signals for committed offsets, valid positions, and revocation. This gives the fetcher and coordinator a safe way to wait for the next group state instead of polling stale values.
References: aiokafka/…/subscription_state.py• L307-356 aiokafka/…/subscription_state.py• L383-455 aiokafka/…/subscription_state.py• L457-555
Group ownership
With a group_id, the group coordinator keeps this consumer in a Kafka consumer group. The group joins, selects an assignment strategy, receives partition ownership, and keeps the membership alive with heartbeats. Topic or partition changes request a new join, so ownership can move to match the current group.
Without a group_id, the no-group coordinator still tracks metadata and assigns all partitions for a topic subscription to this consumer. It does not provide group offset storage or load sharing with other consumers.
The full join and rebalance flow is described in consumer group coordination.
References: aiokafka/…/consumer.py• L370-446 aiokafka/…/group_coordinator.py• L85-128 aiokafka/…/group_coordinator.py• L604-740
Fetch and record delivery
The fetcher runs as a background task after startup. It groups ready partitions by broker, sends fetch requests, and places results in per-partition buffers so application calls can receive records without making each call perform broker I/O.
Fetch processing
For each active partition, the fetcher chooses one of three broad actions: reset the position, wait because the partition is paused or already buffered, or fetch more data. It wakes getone() and getmany() callers when new data arrives and discards buffered work when the assignment becomes inactive.
The fetcher can read from a broker replica selected by the cluster when the broker supports a preferred read replica. Metadata changes and fetch errors cause it to refresh its route and retry when the error is safe to retry.
See consumer fetch and position for the detailed fetch pipeline and position rules.
References: aiokafka/…/consumer.py• L384-399 aiokafka/…/fetcher.py• L427-580 aiokafka/…/fetcher.py• L582-682
Record conversion
Fetched batches become ConsumerRecord values only after the consumer applies record checks and read rules. Optional key and value deserializers turn broker bytes into application values. CRC checks can reject damaged data, control records are not exposed, and read_committed hides records from aborted transactions.
The fetcher advances its next fetch offset through records and through batches that contain no user-visible record. This keeps control records, compacted batches, and filtered transactions from causing the same broker data to be fetched forever.
References: aiokafka/…/fetcher.py• L166-205 aiokafka/…/fetcher.py• L207-271 aiokafka/…/fetcher.py• L296-330
Application delivery
getone() returns one record from the requested partitions or waits for a record. getmany() drains available records into a map keyed by TopicPartition and can wait for more data up to its timeout. Both APIs first check coordination errors and avoid returning records while a rebalance is still in progress.
Pause affects fetching but not subscription or group ownership. Resume makes the partition eligible for new fetch work again.
References: aiokafka/…/consumer.py• L1103-1145 aiokafka/…/consumer.py• L1147-1200 aiokafka/…/consumer.py• L1202-1242
Position management
A partition position is the offset of the next record that the consumer will fetch. The subsystem keeps this position separate from the last offset committed for the group, which allows an application to consume ahead of its durable restart point.
Initial position
After assignment, the consumer first asks the group coordinator for the committed offset when group storage is available. If no offset exists, or if the current offset is no longer available, the configured reset rule selects the earliest or latest available offset. A none rule turns the missing position into an error instead of choosing one.
Manual seeking overrides this choice. seek_to_beginning() and seek_to_end() request an offset lookup, while seek() sets an exact offset and clears buffered records for that partition.
References: aiokafka/…/fetcher.py• L27-54 aiokafka/…/fetcher.py• L918-997 aiokafka/…/fetcher.py• L1291-1319
Position advancement
The fetcher moves the position as it yields records to the application. The position is updated to the next fetch offset even when a fetched batch has no record to return. This makes the position suitable for both continued fetching and offset commits.
The public position() call waits until a valid position exists. highwater() reports the next offset produced by the broker, while the last stable offset reports the safe read limit for committed transactions.
References: aiokafka/…/fetcher.py• L57-137 aiokafka/…/fetcher.py• L1163-1205 aiokafka/…/consumer.py• L652-735
Rebalance position safety
When ownership changes, the consumer marks the old assignment inactive and waits for the new assignment before returning more records. A fetched result is also checked against the current partition position, so a seek, pause, or rebalance cannot silently deliver data that no longer matches the requested state.
References: aiokafka/…/fetcher.py• L73-104 aiokafka/…/fetcher.py• L1207-1266 aiokafka/…/subscription_state.py• L221-239
Offset commits
Offset commits provide the restart point for a consumer group. The committed value is the next offset to read, so an application normally commits one more than the last record it has completed.
Commit paths
The consumer supports explicit commits through commit() and periodic commits when auto-commit is enabled. An explicit commit can use the current position or a caller-provided map of partition offsets. Commits require a group and an active assignment.
The coordinator sends commits with the current group generation and member identity. If the group has already moved the partition to another member, the commit fails rather than claiming progress for a partition this consumer no longer owns.
References: aiokafka/…/consumer.py• L523-595 aiokafka/…/group_coordinator.py• L944-979 aiokafka/…/group_coordinator.py• L986-1138
Commit refresh
The coordinator refreshes committed offsets when a new assignment needs them. The fetcher uses those values to set initial positions, so a restart or rebalance resumes from the group checkpoint before applying the reset rule.
This refresh is separate from the current consumed position. A consumer can move forward locally without making that progress durable until an explicit or automatic commit succeeds.
References: aiokafka/…/group_coordinator.py• L863-912 aiokafka/…/group_coordinator.py• L1140-1224 aiokafka/…/subscription_state.py• L418-434
Shutdown commit
Stopping the consumer closes coordination after it gives the coordinator a chance to perform the final automatic commit. A group consumer then leaves the group when possible, while the fetcher stops its background task and releases pending fetch waiters.
References: aiokafka/…/consumer.py• L506-521 aiokafka/…/group_coordinator.py• L355-387 aiokafka/…/group_coordinator.py• L981-985
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the subscription mode rules aligned with both the public
subscribe()andassign()APIs and the coordinator path that handles each mode. - Preserve the handoff between assignment activity, fetch buffers, and position waiters. A stale assignment can return records or positions for the wrong group member.
- Keep commit values as next-record offsets and send them with the active group generation and member identity.
- Keep deserialization, transaction filtering, and next-fetch offset updates consistent. Filtering a record must not stop the partition from advancing.
- Keep reset behavior aligned across missing commits, out-of-range offsets, and explicit seek operations.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
The application does not consume within max_poll_interval_ms | The coordinator treats the member as idle and the group reassigns its partitions | Continue calling getone() or getmany() while processing records, or tune the interval for the processing time |
A partition has no committed offset and auto_offset_reset is none | Fetching stores a NoOffsetForPartitionError and the consumer cannot start that partition | Choose earliest or latest, or set a position before consuming |
| A rebalance or seek invalidates a buffered fetch result | The result is discarded instead of being returned from an inactive or changed position | Wait for the new assignment and use the public position and seek APIs |
| A commit reaches the broker after group membership changes | The commit raises CommitFailedError; the old member must not claim the partition | Commit before long processing gaps and handle rebalance callbacks |
| A record is larger than the per-partition fetch limit | The partition can fail to make fetch progress | Set max_partition_fetch_bytes at least as high as the broker's largest message |
An open transaction is ahead of the last stable offset in read_committed mode | Later records stay hidden until the transaction completes | Treat the last stable offset as the current read limit |
Key files
| File | Why to read it |
|---|---|
| aiokafka/…/consumer.py | Public lifecycle, subscription, assignment, fetch, seek, and commit API |
| aiokafka/…/subscription_state.py | Shared model for subscriptions, assignments, partition positions, pauses, and change signals |
| aiokafka/…/fetcher.py | Background fetch lifecycle, record conversion, position reset, and buffered delivery |
| aiokafka/…/group_coordinator.py | Group join and rebalance flow, heartbeats, committed-offset refresh, and commits |
| aiokafka/…/abstract.py | Common contract for partition assignment strategies |
| aiokafka/…/roundrobin.py | A concrete example of how group members receive partitions |