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 / cluster-metadata-and-routing

Cluster metadata and broker routing

Cluster metadata is the client’s current view of the Kafka cluster. It maps brokers to network endpoints and maps each topic partition to its leader so producers, consumers, and coordination flows can send requests to the right node. This page is a child of Client and cluster connectivity; see also Connection, transport, and authentication for the connection layer.

Cluster metadata model

The client keeps a replaceable in-memory view of cluster state. A metadata response supplies the broker list and the topic and partition records that form this view. The view does not fetch data itself; the client refresh task obtains responses and applies them to the view.

Broker and controller state

Each broker record binds a broker ID to a host, port, and optional rack. The client uses the broker ID as the routing key, then uses the endpoint to open or reuse a connection. Metadata can also identify the cluster controller, but controller status is separate from partition-leader status.

The client starts with bootstrap endpoints because it does not yet know the cluster’s broker IDs. After a valid metadata response, the discovered brokers replace the temporary bootstrap view. A broker must exist in the current view before the client can create a normal connection to that broker.

References: aiokafka/cluster.py• L43-96 aiokafka/cluster.py• L207-220 aiokafka/client.py• L196-242 aiokafka/client.py• L397-441

Topic and partition state

Topic metadata records the partitions known for a topic. Each partition record contains its leader, replica broker IDs, in-sync replica broker IDs, and any error tied to that record. The leader is the broker that normally receives writes and leader-bound reads for that partition.

The view distinguishes three cases:

  • A missing topic or partition is unknown to the current metadata view.
  • A known partition with leader -1 exists but has no usable leader yet.
  • A known partition with a non-negative leader ID can be routed to that broker.

The view also tracks internal topics and topics that the client is not authorized to read. Internal topics stay hidden from the normal topic set unless a caller asks for them. The broker-to-partition index lets the client see which partitions a broker leads.

References: aiokafka/cluster.py• L98-148 aiokafka/cluster.py• L221-276 aiokafka/structs.py• L19-67

Metadata refresh lifecycle

Metadata refresh is a control loop that turns bootstrap information, client interest, and routing errors into a current cluster view. The client can refresh on a timer or wake the loop when the current view may no longer be safe to use.

Bootstrap discovery

Bootstrap uses any configured seed endpoint that can answer a metadata request. The seed does not need to list every broker. Once the response contains a usable broker list, later requests use the discovered broker endpoints instead of depending on the seed connection.

If a cluster has no usable broker records yet, the client keeps the bootstrap connection long enough to try again. If every configured seed fails, bootstrap stops with a connection error and no routing decisions can proceed.

References: aiokafka/client.py• L190-246 aiokafka/cluster.py• L64-74

Refresh triggers

The background synchronizer refreshes metadata after the configured metadata age. The client also wakes it when a caller adds a topic, sets a new tracked topic set, or forces an update. Broken or timed-out broker connections and broker responses that mark metadata as invalid also request a refresh.

The refresh request can cover the tracked topics or all topics. A topic wait repeats this process until the requested topic appears, authorization fails, or the request timeout is reached. This makes metadata discovery part of the producer and consumer request path rather than a separate setup step.

The refresh path tries known brokers in a shuffled order. A successful response replaces the broker, controller, partition, internal-topic, and authorization state as one update. A response with no broker records is not accepted as a usable cluster layout.

References: aiokafka/client.py• L248-328 aiokafka/client.py• L330-378 aiokafka/client.py• L380-439 aiokafka/client.py• L486-518 aiokafka/errors.py• L81-130

Refresh sequence

The following flow shows how the client moves from a seed endpoint to a routing decision and then refreshes when that decision becomes stale.

flowchart TD
    A[Bootstrap endpoint] --> B[Metadata request]
    B --> C[Broker and topic state]
    C --> D{Route request}
    D --> E[Known broker]
    D --> F[Unknown or unavailable leader]
    E --> G[Send request]
    G --> H{Metadata still valid?}
    H -->|Yes| I[Continue using route]
    H -->|No| J[Force metadata refresh]
    F --> J
    J --> B

References: aiokafka/client.py• L219-246 aiokafka/client.py• L284-328 aiokafka/client.py• L330-342 aiokafka/…/sender.py• L155-169

Request routing

Routing starts with the logical target of a request. Partition work uses the partition leader, while group and transaction work uses a coordinator found through a separate lookup. The client keeps these roles distinct because a coordinator is not selected from the partition-leader map.

Partition leader routing

A producer first resolves a topic to a partition. If no partition is supplied, it chooses from all known partitions and can prefer partitions with an available leader. The sender then groups pending batches by the leader ID from cluster metadata and sends one produce request per target broker.

If the leader is unknown or unavailable, the sender does not guess a broker. It waits for a metadata update. If a produce response reports an invalid route, the batch can be retried after metadata refresh and backoff, subject to the request’s retry rules.

References: aiokafka/…/producer.py• L400-438 aiokafka/…/message_accumulator.py• L563-604 aiokafka/…/sender.py• L779-809

Consumer read routing

The consumer groups fetch work by node for its assigned partitions. It normally reads from the partition leader. When the broker provides a valid preferred read replica, the consumer can use that replica for fetches until the preference expires or the broker leaves the current metadata view.

Offset reset requests remain leader-bound even when fetches may use a follower. If no leader is known, the consumer delays the work and requests metadata rather than sending a request to an unsafe target.

References: aiokafka/…/fetcher.py• L582-668 aiokafka/…/fetcher.py• L684-724

Coordinator routing

A coordinator is the broker responsible for a coordination key, such as a consumer group or a transactional ID. The client sends a FindCoordinator request through any known broker, receives the coordinator ID, and then opens a dedicated coordination connection to that ID.

Coordinator IDs are cached by the component that uses them. A coordinator error, failed connection, or unavailable coordinator clears the usable route and causes a later lookup. This lookup is independent of the partition leader used for produce and fetch traffic.

References: aiokafka/client.py• L273-282 aiokafka/client.py• L524-547 aiokafka/…/coordination.py• L9-69 aiokafka/…/group_coordinator.py• L550-584 aiokafka/…/sender.py• L212-267

Routing state relationships

The same metadata view supports several routing decisions, but each decision uses a different part of the state. This separation prevents a broker that is valid for one role from being treated as the target for another role without a matching lookup.

Routing needState usedResult
Produce to a partitionTopic partition and leader IDProduce request grouped by leader broker
Fetch assigned recordsPartition leader or valid preferred read replicaFetch request grouped by read broker
Reset a fetch positionPartition leader IDLeader-bound offset request
Consumer group coordinationGroup coordinator lookup resultDedicated group-coordinator request
Transaction coordinationTransaction coordinator lookup resultDedicated transaction-coordinator request

References: aiokafka/cluster.py• L98-148 aiokafka/…/message_accumulator.py• L563-604 aiokafka/…/fetcher.py• L594-668 aiokafka/client.py• L524-547

Change checklist

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

  • Changes to metadata response fields must preserve the conversion into broker, controller, partition, internal-topic, and authorization state.
  • Changes to leader or preferred-replica handling must keep produce, fetch, and leader-bound offset requests on compatible routes.
  • Changes to metadata scope must keep topic discovery, all-topic fetches, and tracked-topic refreshes consistent.
  • Changes to coordinator lookup must preserve the distinction between the lookup broker and the returned coordination broker.
  • Changes to invalid-metadata error flags must still wake the refresh path before retriable work is sent again.

Important failure modes

TriggerConsequenceGuard
All bootstrap endpoints failThe client cannot build an initial broker viewTry each configured seed and stop with a bootstrap connection error only after all fail
Metadata response has no broker recordsThe response cannot provide a usable cluster layoutReject the update and retain the need to refresh
Partition leader is unknown or -1Produce, fetch, or offset work cannot select a safe nodeWait for a forced metadata refresh instead of guessing a broker
Broker returns an invalid-metadata errorA cached route may point to an old leaderMark the route stale and refresh before retrying where the operation allows it
Coordinator lookup returns an unavailable or unusable nodeGroup or transaction requests cannot startRetry lookup, refresh metadata, and verify the coordination connection
Requested topic remains absent or unauthorizedTopic work cannot become routableKeep waiting only within the request timeout, then raise the matching topic error

Key files

FileWhy to read it
aiokafka/cluster.pyDefines the central broker, topic, partition, leader, controller, and refresh state model.
aiokafka/client.pyCoordinates bootstrap, periodic and forced refreshes, broker connections, topic waits, and coordinator lookup.
aiokafka/…/metadata.pyDefines the metadata request and response contract across broker API versions.
aiokafka/structs.pyDefines the broker, partition, and topic-partition values used by the routing model.
aiokafka/…/message_accumulator.pyShows how pending partition work is grouped by leader broker.
aiokafka/…/fetcher.pyShows leader and preferred-replica selection for fetch and offset work.
aiokafka/…/coordination.pyDefines the coordinator lookup contract.
aiokafka/…/group_coordinator.pyShows how group coordination waits for and verifies a coordinator.
aiokafka/…/sender.pyShows coordinator caching and metadata-driven produce retries.