Kafka client and cluster connectivity
The shared Kafka client layer gives producers, consumers, and the admin client one path to discover brokers, keep cluster state current, open broker connections, and send protocol requests. It turns a small set of bootstrap addresses into a usable view of the cluster, then refreshes that view when time or connection errors make it stale.
Connectivity model
The client separates three concerns that work together:
- Bootstrap discovery uses one or more seed addresses to obtain the first cluster metadata. A seed does not need to list every broker.
- Cluster state records broker endpoints, topics, partitions, and partition leaders. Higher-level clients use this state to choose a destination broker.
- Broker connections provide the request path to a chosen broker. Each connection negotiates supported API versions before normal traffic starts.
The client keeps these concerns separate so a broker address can change in metadata without changing how higher-level clients ask for a request, and so a failed connection can trigger a fresh route lookup.
The child pages describe the two detailed areas:
- Broker connection transport and authentication covers socket transport, framing, request correlation, SSL, and SASL.
- Cluster metadata and broker routing covers the cluster view, partition leaders, coordinators, and routing choices.
Bootstrap and metadata lifecycle
Bootstrap discovery
Bootstrap discovery starts with the configured seed addresses. The client tries each seed until it can connect and receive a metadata response. That response replaces the temporary seed view with broker addresses advertised by the cluster, which lets later requests use the cluster's own broker map.
If every seed fails or returns an unusable response, bootstrap raises a connection error. A cluster with no usable broker list is treated as incomplete rather than as a new empty cluster, so an earlier valid view is not discarded during a bad refresh.
References: aiokafka/client.py• L190-246 aiokafka/client.py• L284-327 aiokafka/cluster.py• L79-96 aiokafka/cluster.py• L194-205
Metadata refresh
Metadata refresh keeps the cluster view aligned with broker and partition changes. The client refreshes on a timer, when a higher-level client adds a topic of interest, and when a broken or timed-out connection suggests that leadership or broker state changed. Several refresh requests that arrive together share one in-progress update.
The refresh can ask for selected topics or for all topics. It tries known brokers and the temporary bootstrap connection when one is still needed. It updates the cluster view only when the response has usable broker data, then closes the bootstrap connection after a normal broker layout is available. A requested topic with no known partitions remains pending until metadata appears or the request timeout, unknown-topic condition, or authorization failure ends the wait.
References: aiokafka/client.py• L248-341 aiokafka/client.py• L343-391 aiokafka/client.py• L393-398 aiokafka/client.py• L500-536 aiokafka/cluster.py• L221-300
Connection and request flow
Connection establishment
The client creates a connection only when a request needs a known broker. It resolves the broker ID through current metadata, reuses a live connection when possible, and prevents concurrent callers from opening duplicate connections to the same broker and connection group. Coordination traffic can use a separate connection to the same broker so it does not wait behind ordinary client traffic.
Connection setup includes transport security and broker capability discovery before the connection is made available for normal requests. See Broker connection transport and authentication for the connection-level protocol.
References: aiokafka/client.py• L393-459 aiokafka/conn.py• L54-88 aiokafka/conn.py• L201-236 tests/test_client.py• L456-503
Request dispatch
Higher-level clients submit a request with a destination broker ID. The shared client checks that the destination is ready, sends the request through the connection, and returns the decoded response. Requests on one connection are handled in order, while separate connection groups can make progress at the same time.
Most requests expect a response. Produce requests that ask for no acknowledgement are the exception. A request timeout closes the affected connection so the next attempt must establish a clean path instead of reusing a connection with unknown state.
The common request path is shown below.
flowchart TD
A[Higher-level client chooses broker ID] --> B[Shared client checks metadata]
B --> C{Live connection?}
C -- No --> D[Create broker connection]
C -- Yes --> E[Use existing connection]
D --> F[Prepare versioned request]
E --> F
F --> G[Send request and await response]
G --> H[Return decoded response]
G --> I{Failure or timeout}
I --> J[Close or discard connection]
J --> K[Refresh metadata or retry at caller]
References: aiokafka/client.py• L457-498 aiokafka/conn.py• L406-442 aiokafka/conn.py• L530-583 tests/test_client.py• L423-454
Coordinator lookup
Group and transaction work needs a coordinator, which is the broker assigned to manage a particular group or transaction key. The client sends a coordinator lookup through a known broker, returns the coordinator ID, and keeps that coordination route distinct from ordinary broker connections.
This lookup depends on current broker metadata. If the result points to a broker that is not in the current view, the client treats the view as stale instead of opening a connection to an unknown endpoint.
References: aiokafka/client.py• L538-561 aiokafka/client.py• L400-418 tests/test_client.py• L456-468
Protocol compatibility
Version negotiation
Each new broker connection first asks the broker which API versions it supports. The connection stores the supported range for each API key. When a caller submits a request, the request builder selects the highest library-supported version inside that range and encodes the matching request and response shape.
This per-connection negotiation lets the same higher-level client work with brokers that support different protocol generations. If no compatible version exists, the request fails with a version error rather than sending a message the broker cannot interpret.
References: aiokafka/conn.py• L227-247 aiokafka/…/api.py• L70-142 aiokafka/…/metadata.py• L187-293
Error handling
Connection and metadata errors
Connectivity errors affect both the current request and the trust placed in cluster state. A failed connection, connection timeout, or broken read fails pending work and asks the client to refresh metadata. A request timeout also removes the connection from future use. A node that has no usable connection produces a node-not-ready error before the request is sent.
The error model marks errors that can be retried and errors that make metadata unsafe to use. Connection failures, stale metadata, and broker responses such as an unknown topic or a changed partition leader carry these signals so higher-level clients can refresh routes instead of applying the same failed route again. An empty broker list remains a temporary metadata condition and does not erase a valid cluster view.
References: aiokafka/client.py• L314-341 aiokafka/client.py• L388-398 aiokafka/client.py• L405-450 aiokafka/client.py• L472-493 aiokafka/cluster.py• L194-205 aiokafka/cluster.py• L252-269 aiokafka/errors.py• L81-139 aiokafka/errors.py• L279-317
Protocol and response errors
The connection matches each response to the request that is waiting for it. A mismatched correlation ID puts the connection out of sync and closes it because later responses cannot be trusted. Authentication failures close the connection as well. The client maps broker error codes to typed Kafka errors, which allows higher-level clients to decide whether to retry, refresh metadata, or report a permanent failure.
This mapping preserves the broker error code while exposing common retry and metadata-refresh signals on the error type. Errors without those signals remain caller-visible failures rather than automatic connectivity retries.
References: aiokafka/conn.py• L249-310 aiokafka/conn.py• L530-581 aiokafka/errors.py• L235-317 aiokafka/errors.py• L539-587 aiokafka/errors.py• L873-886
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the bootstrap path and the normal broker path aligned when connection security or request setup changes. A connection that works only for bootstrap can leave all later requests unable to reach advertised brokers.
- Keep metadata response versions aligned with the cluster-state update rules. New broker or partition fields must not change the meaning of older response versions.
- Preserve the link between connection close reasons and metadata refresh. Without it, broker or leader changes can remain hidden until the periodic refresh.
- Preserve the request version range for every request family used by producer, consumer, coordinator, and admin callers.
- Keep connection groups distinct when adding coordination traffic. Sharing the wrong group can serialize unrelated long-running requests.
- Keep retry and metadata-refresh flags aligned with each broker error code. A wrong flag can cause a stale route to repeat or can hide a permanent error behind retries.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Every bootstrap seed is unreachable or rejects metadata | The client cannot build an initial broker map and bootstrap fails | Supply at least one reachable seed that can answer a Metadata request |
| Metadata returns no brokers during a refresh | The existing broker map stays in place and the refresh does not create a false empty cluster | Treat the response as incomplete and wait for a later refresh |
| A request targets a broker missing from current metadata | The client raises a stale-metadata or node-not-ready error instead of using an unknown endpoint | Refresh metadata before retrying the route |
| A response correlation ID does not match its request | The connection is closed because response order and ownership are no longer trusted | Recreate the connection and retry through the caller's normal policy |
| No common API version exists for a request | The request fails before it is sent | Add support for a compatible request version or use a broker with a supported range |
| A request times out | Pending work fails and the connection is closed for replacement | Retry only after the caller checks the operation's delivery or commit semantics |
| A broker error is marked with the wrong retry or metadata flag | Higher-level clients can repeat a bad route or fail to refresh a changed route | Keep error classification aligned with the broker error's meaning |
Key files
| File | Why to read it |
|---|---|
| aiokafka/client.py | Primary shared client flow for bootstrap, metadata refresh, connection reuse, request dispatch, and coordinator lookup |
| aiokafka/cluster.py | In-memory cluster view used to map broker IDs and topic partitions to routing information |
| aiokafka/conn.py | Broker connection lifecycle, API version discovery, request/response flow, and connection failure signals |
| aiokafka/…/api.py | Shared request abstraction that selects a wire version from broker capability ranges |
| aiokafka/…/metadata.py | Metadata request and response contract used to discover brokers and partition leaders |
| aiokafka/errors.py | Error classes, broker error-code mapping, and retry or metadata-invalid signals exposed to higher-level clients |