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 / connection-transport-and-authentication

Broker connection transport and authentication

An individual broker connection is the asynchronous, request/response channel that carries Kafka protocol messages between an aiokafka client and one broker. It opens a network stream, negotiates usable API versions, optionally secures the stream with SSL and authenticates with SASL, then matches each response to its waiting request until the channel closes.

This page focuses on one broker channel. See Client and cluster connectivity for the wider client connection model and Cluster metadata and routing for how the client chooses a broker.

Connection lifecycle

The connection lifecycle turns a broker address and client security settings into a ready protocol channel. The client first opens the transport, then performs version discovery and authentication before normal producer, consumer, or admin traffic uses the connection.

When a connection is created, it follows this order:

  1. Open a TCP stream to the broker. Use SSL for SSL and SASL_SSL; use a plain stream for PLAINTEXT and SASL_PLAINTEXT.
  2. Send an ApiVersions request to learn the API versions that this broker supports.
  3. If the security mode uses SASL, complete the SASL handshake and token exchange.
  4. Return the ready channel to the client so normal Kafka requests can use the negotiated versions.

The connection owns one background reader. It reads complete frames and resolves the request that is waiting at the front of the connection queue. The client supplies the same transport and authentication settings when it opens connections to bootstrap brokers, data brokers, and coordinator brokers.

sequenceDiagram
    participant Client
    participant Broker
    Client->>Broker: Open TCP stream
    alt SSL transport
        Client->>Broker: Complete TLS handshake
    end
    Client->>Broker: ApiVersions request
    Broker-->>Client: Supported API versions
    alt SASL transport
        Client->>Broker: SASL handshake
        Broker-->>Client: Enabled mechanisms
        Client->>Broker: SASL authentication tokens
        Broker-->>Client: SASL responses
    end
    Client->>Broker: Normal Kafka requests
    Broker-->>Client: Correlated responses

References: aiokafka/conn.py• L219-254 aiokafka/conn.py• L256-265 aiokafka/conn.py• L267-339

Request and response framing

Kafka traffic on the connection uses length-prefixed frames. Each outbound frame contains a four-byte size followed by a request header and an encoded request body. Each inbound frame starts with the same size field and contains a response header followed by the response body.

The request header identifies the API key, API version, correlation ID, and client ID. The request object selects a version from the range learned during the version lookup. Flexible protocol versions use the matching header form with tagged fields.

The reader waits for the full size field and then the full frame. It rejects negative or oversized frames before decoding them. It parses the response header before decoding the response body. This keeps partial network reads out of request handling and lets the connection reject a response that does not belong to the request at the front of the queue.

References: aiokafka/conn.py• L424-460 aiokafka/conn.py• L524-552

Request correlation

Correlation IDs are connection-local numbers that link a response to the request that caused it. The connection assigns the next ID to each Kafka request and stores its future with the encoded request in send order.

When a response arrives, the reader compares its correlation ID with the queued request. A match resolves that request's future with the decoded response and removes the request from the queue. A mismatch means the stream is out of sync, so the connection fails the affected request and closes instead of allowing later requests to use uncertain data.

The protocol keeps one compatibility exception for an old FindCoordinator broker response that can return correlation ID zero. This exception does not change the normal rule that responses must match their queued requests.

References: aiokafka/conn.py• L424-460 aiokafka/conn.py• L555-608

Request and response I/O

The connection exposes asynchronous request futures while a single reader consumes broker responses. A request is written to the stream and waits until the reader resolves it, the request timeout expires, or the connection closes.

Most requests require a response. Produce requests with zero required acknowledgements are the special no-response case; they only wait for the writer to drain. SASL token messages use the same length framing but can also finish without a response when the selected mechanism says no further token is needed.

The connection also tracks the last completed action. When idle checking is enabled, it closes a connection that has no pending requests for the configured idle period. Client shutdown closes all owned connections and waits for their transports to finish closing.

References: aiokafka/conn.py• L390-411 aiokafka/conn.py• L424-514

SSL transport

SSL provides encrypted transport and broker identity checks before Kafka protocol traffic starts. The caller supplies an ssl.SSLContext; SSL modes require that context, and the connection passes it to the event loop when it opens the broker stream.

Use the security modes as follows:

ModeTransportSASL authentication
PLAINTEXTUnencryptedNo
SSLSSL-encryptedNo
SASL_PLAINTEXTUnencryptedYes
SASL_SSLSSL-encryptedYes

References: aiokafka/conn.py• L219-236

SASL authentication

SASL authenticates the client after the transport opens and API versions are known. SASL means Simple Authentication and Security Layer. The connection first asks the broker to accept the selected mechanism, checks the broker's enabled mechanism list, and then runs the mechanism-specific token exchange.

The supported mechanisms are:

  • PLAIN, which sends username and password credentials.
  • GSSAPI, which uses a Kerberos security context.
  • SCRAM-SHA-256 and SCRAM-SHA-512, which prove knowledge of a password without sending it as a plain credential.
  • OAUTHBEARER, which obtains a bearer token from the configured token provider.

For newer brokers, SASL tokens use SaslAuthenticate requests so the broker can return structured error information. The connection also supports the older raw length-prefixed token exchange for older API versions. The authentication exchange runs until the mechanism reports completion; only then does the connection become ready for normal traffic.

SASL_PLAINTEXT does not encrypt the authentication exchange. The connection warns when it sends PLAIN credentials over that mode. Use SASL_SSL when credentials and Kafka traffic need encryption in transit.

References: aiokafka/conn.py• L267-339 aiokafka/conn.py• L462-481 aiokafka/conn.py• L611-811

Connection failure handling

Connection failures protect the request queue and tell the client when it must obtain a fresh channel. The connection records a close reason such as broken transport, timeout, protocol desynchronization, idle drop, shutdown, or authentication failure.

Failure handling follows these rules:

FailureConnection resultClient result
Socket error, EOF, reader error, or invalid frame lengthClose the channel and fail pending futures with KafkaConnectionError.Treat the connection as retriable and refresh metadata when the failure is a broken or timed-out channel.
Request timeoutClose the channel because its in-flight state is unknown.Raise RequestTimedOutError and create a replacement channel later.
Correlation mismatchFail the affected future and close the out-of-sync channel.Retry through normal client recovery paths rather than trusting later frames.
SASL error or unsupported mechanismClose with an authentication failure.Surface the authentication or mechanism error; do not treat bad credentials as a successful connection.
Idle expiry or client shutdownClose the transport and resolve close waiters.Remove the channel from active use or finish client shutdown.

Pending requests do not remain unresolved when a connection closes. The close path fails them and invokes the client close callback once, which lets the client trigger metadata recovery for transport failures.

References: aiokafka/conn.py• L374-388 aiokafka/conn.py• L486-514 aiokafka/conn.py• L537-586

Change checklist

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

  • Keep the frame reader, request queue, and correlation check aligned if the wire header or response order changes.
  • Keep the negotiated API version ranges aligned with the request and response structures used by the version lookup and SASL handshake.
  • Keep all four security modes consistent between client validation, connection setup, SSL context use, and SASL startup.
  • Keep close reasons aligned with the client's metadata refresh rule so transport loss does not leave stale broker addresses in use.
  • Keep each SASL mechanism's token completion rule aligned with whether the broker expects a further response.

Important failure modes

TriggerConsequenceGuard
SSL or SASL_SSL has no SSL contextClient configuration fails before a connection opens.Supply a configured SSLContext.
PLAIN lacks a username or passwordClient configuration fails before SASL starts.Supply both credentials.
Broker does not list the selected SASL mechanismConnection closes during authentication.Select a mechanism enabled by the broker.
Correlation ID differs from the queued requestConnection closes as out of sync.Preserve request order and response header correlation.
A frame exceeds receive_message_max_bytesReader fails and closes the connection.Set a limit that accepts expected broker responses.
A request times outConnection closes and pending state is discarded.Allow the client to create a new connection before retry.
PLAIN runs over SASL_PLAINTEXTCredentials travel without encryption.Use SASL_SSL when transport privacy is required.

Key files

FileWhy to read it
aiokafka/conn.pyDefines the broker channel lifecycle, frame I/O, correlation queue, SSL selection, SASL exchange, idle handling, and close behavior.
aiokafka/client.pyShows how the wider client opens per-broker channels, sends requests, turns failures into recovery, and closes connections.
aiokafka/…/api.pyDefines request version selection and the request and response header contract.
aiokafka/…/admin.pyDefines the API-version and SASL handshake/authentication message shapes.
aiokafka/helpers.pyDefines the supported SSL context setup for broker and optional client certificate verification.
aiokafka/errors.pyDefines the connection, timeout, correlation, and SASL errors exposed to callers.
tests/test_sasl.pyShows end-to-end SASL use across producer, consumer, and admin client connections.