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-group-coordination

Consumer group membership and rebalance coordination

Consumer group coordination lets several AIOKafkaConsumer instances with the same group_id share topic partitions. A broker-side group coordinator tracks membership while the clients agree on an assignment, keep their membership alive, and save progress for later owners. This page complements the consumer subsystem, the fetch and position flow, and the assignment strategies.

Group membership model

The consumer group is a shared work pool. Each subscribed partition belongs to one active member in the group, so adding or removing a member changes which consumer receives records. The group coordinator is the broker that manages this membership and accepts group, heartbeat, and offset requests.

Membership identity

Each member has a member ID and belongs to a numbered generation, which is the current version of the group membership. The coordinator can also use a configured group instance ID for static membership. If another consumer takes the same static identity, the original consumer is fenced and must be restarted. A consumer without a group_id does not join this protocol and does not get group-based assignment or Kafka-backed group offset commits.

References: aiokafka/…/consumer.py• L61-65 aiokafka/…/consumer.py• L401-437 aiokafka/…/group_coordinator.py• L262-266 aiokafka/…/group_coordinator.py• L1318-1374 aiokafka/…/group.py• L128-140

Partition ownership

Topic subscription and partition ownership are separate states. A subscribed consumer can have no assignment while a group is joining or rebalancing. After the coordinator accepts a new generation, the group assigns each matching partition to one member and the consumer exposes only its current assignment to the fetch path.

Manual assignment is a separate mode. It gives one consumer direct ownership and does not trigger group rebalances when membership or topic metadata changes, although a group_id may still be used for commits.

References: aiokafka/…/subscription_state.py• L73-97 aiokafka/…/subscription_state.py• L166-176 aiokafka/…/subscription_state.py• L206-228 aiokafka/…/consumer.py• L458-479 aiokafka/…/consumer.py• L489-504

Group join and partition assignment

Joining turns a local subscription into a group-wide assignment. The coordinator gathers member metadata, selects one member as the group leader, and the leader applies the selected assignment strategy to the full member set. The coordinator then distributes the resulting assignment so each member can begin fetching its own partitions.

The sequence below shows the high-level handoff from a consumer subscription to usable partition ownership.

sequenceDiagram
    participant C as Consumer member
    participant G as Group coordinator
    participant L as Elected group leader
    participant F as Fetch path
    C->>G: JoinGroup with subscription and strategies
    G-->>C: Generation, member identity, and leader choice
    L->>L: Build one assignment for all members
    L->>G: SyncGroup with member assignments
    G-->>C: Assignment for this member
    C->>F: Publish assignment and load committed positions
    F-->>C: Fetch records from owned partitions

Join and synchronization phases

The join phase creates a new group generation and selects a common assignment protocol that the members support. The sync phase carries the leader's member-to-partition mapping back through the coordinator. A failed join or sync does not expose a partial assignment; the consumer retries, finds a new coordinator, or starts another join when the group state requires it.

References: aiokafka/…/group_coordinator.py• L1266-1404 aiokafka/…/group_coordinator.py• L1406-1528 aiokafka/…/group.py• L62-117 aiokafka/…/group.py• L209-285

Assignment strategy

An assignment strategy defines how the leader maps the group's subscribed topics and partitions to member IDs. The selected strategy must be understood by all members in the generation. The strategy affects balance and movement of ownership, while the coordinator protocol still controls when the assignment becomes active.

References: aiokafka/…/group_coordinator.py• L430-472 aiokafka/…/group_coordinator.py• L1334-1341 aiokafka/…/consumer.py• L119-127

Liveness and coordinator state

Liveness has two related meanings. Heartbeats tell the broker that a member's session is alive, while consumer activity keeps the member from exceeding the allowed processing interval. Background coordination lets this client send heartbeats during normal record processing and during a rebalance.

Heartbeat session

The consumer sends heartbeats at the configured heartbeat interval. If the coordinator receives no successful heartbeat before the session timeout, it treats the member as failed and can start a rebalance. A heartbeat that reports a rebalance asks the consumer to rejoin, but the consumer continues heartbeating so it does not lose its session while the rebalance completes.

References: aiokafka/…/group_coordinator.py• L743-797 aiokafka/…/group_coordinator.py• L799-872 aiokafka/…/group.py• L296-344 aiokafka/…/consumer.py• L143-160

Processing interval

Background heartbeats do not remove the processing limit. If the consumer stays idle for longer than max_poll_interval_ms, the coordinator leaves the group so another member can take its partitions. Before a rejoin, the consumer also checks this idle time and delays the join when the previous assignment has already exceeded the limit. Applications that perform long work between getone or getmany calls must keep that interval and the rebalance timeout aligned with the work they allow.

References: aiokafka/…/group_coordinator.py• L717-740 aiokafka/…/group_coordinator.py• L789-796 aiokafka/…/group_coordinator.py• L723-727 aiokafka/…/consumer.py• L129-142 aiokafka/…/subscription_state.py• L287-303

Coordinator state changes

The local coordinator state changes in response to broker errors and membership events. These changes control whether the consumer can continue with its current generation or must discover the coordinator and join again.

State signalCoordination responseConsumer-facing effect
Coordinator unavailable or no longer validMark the coordinator unknown and look it up againGroup requests pause until a usable coordinator is found
Rebalance in progressRequest a rejoin while keeping heartbeats activeThe current assignment is being replaced
Unknown member or old generationReset member and generation state and rejoinCommits and heartbeats for the old membership are no longer valid
Static member identity is fencedRaise a fencing error and stop trying to reclaim the identityThis consumer must be restarted
Session timeout or excessive processing idle timeLeave or lose the groupPartitions can move to other members

References: aiokafka/…/group_coordinator.py• L517-549 aiokafka/…/group_coordinator.py• L799-872 aiokafka/…/group_coordinator.py• L789-796 aiokafka/…/group_coordinator.py• L1355-1374

Rebalance lifecycle

A rebalance replaces the group's partition ownership. It can follow a member joining or leaving, a member failure, a subscription change, or a topic metadata change such as a new partition or a new topic that matches a pattern. During this handoff the consumer marks reassignment in progress, gives application code a chance to finish work, and only then starts using the new assignment.

Rebalance triggers

The coordinator requests a rejoin when the local subscription changes or when metadata changes alter the topics or partition counts known to the group. The broker can also request a rebalance when group membership changes. A pattern subscription therefore links metadata discovery to group ownership: a newly matching topic becomes part of the group only after a new assignment completes.

References: aiokafka/…/consumer.py• L1013-1046 aiokafka/…/group_coordinator.py• L46-73 aiokafka/…/group_coordinator.py• L295-298 aiokafka/…/group_coordinator.py• L698-715 aiokafka/…/subscription_state.py• L196-204

Rebalance callbacks

ConsumerRebalanceListener provides two application hooks around automatic reassignment. The consumer calls on_partitions_revoked after it marks reassignment in progress and before it rejoins. It waits for the callback to finish. After synchronization, it creates the new assignment and starts committed-offset refresh before it calls on_partitions_assigned. These hooks are the boundary for committing pending work, flushing local state, or loading state for newly owned partitions.

Callbacks are part of the coordination path. A callback that waits on a lock held by record fetching can block the rebalance and prevent the group from stabilizing.

References: aiokafka/abc.py• L4-45 aiokafka/abc.py• L47-84 aiokafka/…/group_coordinator.py• L396-428 aiokafka/…/group_coordinator.py• L474-515 aiokafka/…/subscription_state.py• L220-228

Assignment handoff

Starting a rebalance marks the subscription as being reassigned and revokes its old assignment through the assignment's lifecycle. The new assignment creates new partition state, refreshes committed offsets, and then becomes visible to the consumer callback. Each assignment has an end signal, so fetch and offset-refresh work can stop when that assignment is replaced. Pending fetches for partitions that are no longer owned must not be treated as work for the new owner.

References: aiokafka/…/group_coordinator.py• L396-418 aiokafka/…/group_coordinator.py• L480-505 aiokafka/…/subscription_state.py• L338-356 aiokafka/…/subscription_state.py• L382-433

Offset commits and position recovery

Group coordination and offset storage work together to let a new owner resume a partition. The consumer position is the next record it will fetch, while the committed offset is the durable restart point. A commit should therefore represent the next record after the work that the application has completed.

Commit timing

With auto-commit enabled, the coordinator commits consumed positions on a time schedule in the background. It also makes a final commit when the consumer closes and tries to commit the previous assignment before a rebalance. Manual commits give the application control over when processing is complete and are important for batch or external-state workflows.

References: aiokafka/…/group_coordinator.py• L954-994 aiokafka/…/group_coordinator.py• L688-696 aiokafka/…/consumer.py• L523-595

Commit ownership

An offset commit is tied to the member and generation that own the assignment. If a rebalance changes that ownership before the commit completes, the consumer raises CommitFailedError because another member may now process the partition. Coordinator errors can be retried, but an old member or generation must be handled as a membership change rather than as a successful commit.

References: aiokafka/…/group_coordinator.py• L996-1026 aiokafka/…/group_coordinator.py• L1055-1148 aiokafka/…/consumer.py• L551-572

Committed position refresh

After a new assignment arrives, the consumer refreshes committed offsets for partitions that need them. The fetch path then starts from the committed position when one exists, or applies the configured reset policy when it does not. This is why assignment changes can briefly leave position-dependent calls waiting while the new partition state becomes ready.

References: aiokafka/…/group_coordinator.py• L480-495 aiokafka/…/group_coordinator.py• L874-920 aiokafka/…/group_coordinator.py• L1150-1167 aiokafka/…/consumer.py• L671-693 aiokafka/…/subscription_state.py• L426-433 aiokafka/…/subscription_state.py• L514-525

Consumer-facing coordination boundaries

Coordination changes are visible through assignment, fetch, position, commit, and callback behavior. Applications should treat assignment as a changing resource rather than as a permanent list of partitions.

Fetch and assignment visibility

The consumer does not return records from partitions outside its active assignment. A rebalance can remove an assignment while a caller waits for data or a position, so operations that depend on ownership can wait for the next assignment or fail when the subscription ends. Applications should check current ownership before committing or processing a batch that spans a rebalance boundary.

References: aiokafka/…/consumer.py• L489-504 aiokafka/…/consumer.py• L1103-1145 aiokafka/…/consumer.py• L1147-1164 aiokafka/…/consumer.py• L671-693 aiokafka/…/subscription_state.py• L92-97

Shutdown and unsubscribe

Normal shutdown attempts a final auto-commit, stops background coordination, and leaves a dynamic group. Unsubscribe clears the subscription and asks the coordinator to leave. A stopped consumer cannot continue fetching, while a member that fails without leaving is removed after the session timeout and its partitions are reassigned.

References: aiokafka/…/group_coordinator.py• L356-388 aiokafka/…/consumer.py• L506-521 aiokafka/…/consumer.py• L1095-1101 aiokafka/…/subscription_state.py• L178-192

Change checklist

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

  • When group join or sync fields change, keep member identity, generation, assignment protocol, static membership, and fencing behavior aligned across the coordinator and group protocol messages.
  • When assignment or subscription state changes, preserve the handoff order: mark reassignment, revoke old partitions, invalidate old assignment state, refresh committed positions, then expose the new assignment.
  • When heartbeat or processing-time rules change, check the relationship between heartbeat_interval_ms, session_timeout_ms, max_poll_interval_ms, and rebalance_timeout_ms so a live member is not removed during valid work.
  • When commit error handling changes, keep coordinator rediscovery separate from old-generation recovery and preserve the CommitFailedError contract for ownership changes.
  • When rebalance callbacks change, preserve the wait-before-rejoin and assign-before-fetch ordering that application state management depends on.

Important failure modes

TriggerConsequenceGuard
The application blocks longer than max_poll_interval_ms without consuming recordsThe member leaves the group and its partitions can move to another consumerKeep processing intervals below the limit or tune the limit with the work time
A rebalance completes before a manual commitThe commit raises CommitFailedError; a different member may own the partitionCommit pending work in on_partitions_revoked before rejoin
A rebalance callback waits on a lock held by fetching or processingThe group cannot complete the rebalance and assignment remains unsettledDo not hold the shared fetch lock while waiting for callback completion
Heartbeats fail until the session timeout expiresThe coordinator removes the member and starts a rebalanceKeep the event loop able to run the background heartbeat task and use a heartbeat interval below the session timeout
Another consumer uses the same group.instance.idThe original member is fenced and coordination stopsGive each static member a unique identity and restart a fenced consumer
The subscription ends while a fetch or position call waitsThe pending operation cannot use the old assignment and may raise an illegal-state or stop errorTreat assignment as temporary and handle unsubscribe or stop as a terminal state

Key files

FileWhy to read it
aiokafka/…/group_coordinator.pyMain group lifecycle: coordinator discovery, join and sync, heartbeat, rebalance callbacks, assignment handoff, and offset commits
aiokafka/…/consumer.pyPublic group settings and the consumer-facing behavior of subscribe, assignment, commit, start, and stop
aiokafka/…/subscription_state.pyShared model for subscriptions, active assignments, partition state, and waiters used by coordination and fetching
aiokafka/…/group.pyWire-level group messages for join, sync, heartbeat, and leave operations
aiokafka/abc.pyCallback contract for saving work before revoke and restoring state after assignment
docs/examples/group_consumer.rstSmall end-to-end example of two consumers sharing partitions in one group