Kafka protocol model and API messages
The Kafka protocol model turns broker requests and responses into typed messages that can be selected by API version and converted to bytes. It gives the client one shared way to describe fields, nested values, headers, normal fields, and optional tagged fields while each request family supplies its own message shapes.
Protocol model
The protocol model separates a message's meaning from its byte layout. A schema describes ordered fields, a struct holds the values, and request or response classes add the API identity that lets the connection layer choose and decode the right message.
The main relationships are:
- Primitive types encode one value, such as an integer, string, byte sequence, or Boolean.
- Schemas combine named fields and nested arrays into a wire shape.
- Structs bind schema fields to named values and provide encode, decode, and lookup operations.
- Request structures add an API key, API version, and response type.
- Responses use the same schema model to decode broker output.
- Request builders select a versioned request structure after broker support is known.
This shared model lets request-family modules focus on Kafka operations rather than define a separate serialization method for each message. See request families for the operation-specific messages.
Schema types
aiokafka/…/types.py defines the wire types used by schemas. Fixed-width numbers use big-endian encoding. Strings and bytes carry length information and can represent None; arrays carry an item count and can also represent a null array. Compact types use unsigned variable-length counts for flexible messages.
Schemas can contain nested schemas through arrays. This represents Kafka data such as a list of topics that contains a list of partitions without changing the basic message model.
References: aiokafka/…/types.py• L45-183 aiokafka/…/types.py• L318-368 aiokafka/…/types.py• L441-490
Struct messages
aiokafka/…/struct.py provides the value object for a schema. A struct accepts values by schema order or field name, encodes them through its schema, and decodes bytes into the same named shape. Request and response messages therefore share the same field access and representation rules.
Structs also compare values through their schema and fields. They remain mutable message values and are intentionally not usable as set or dictionary keys.
References: aiokafka/…/struct.py• L7-57 aiokafka/…/api.py• L179-180 aiokafka/…/api.py• L212-234
API messages
An API message is identified by an API key and a version. A request structure describes the exact fields sent for one version, while its linked response type describes the fields expected back for that same API version.
The message model uses three levels:
| Level | Purpose |
|---|---|
| Request builder | Holds the operation's input and selects a supported version. |
| Request structure | Holds the version-specific wire fields and identifies the response type. |
| Response structure | Holds the broker result using the matching response schema. |
For example, the ApiVersions operation has versioned request and response structures even when early request versions have the same empty schema. The API key remains the stable identity, while the version selects the contract. The admin definitions also keep each request version paired with its matching response version; for example, DescribeGroups v3 returns the response shape that includes authorized operations. Other admin operations use the same pattern when a later version adds a field or changes a response shape.
References: aiokafka/…/api.py• L70-142 aiokafka/…/api.py• L145-214 aiokafka/…/admin.py• L23-87 aiokafka/…/admin.py• L390-535
Request and response headers
Headers connect a message to a broker exchange. A request header carries the API key, API version, correlation ID, and client ID. A response header carries the correlation ID so the client can match the broker reply to the request.
The header form follows the message's schema. A normal message uses the version 1 request header and version 0 response header. A flexible message uses headers that end with tagged fields. This keeps header selection tied to the same schema rule as body selection.
References: aiokafka/…/api.py• L14-65 aiokafka/…/api.py• L182-199 tests/test_protocol.py• L183-196
API version selection
The connection first learns the broker's supported range for each API key through the ApiVersions exchange. A request builder then selects the highest request structure that falls within the broker's range. If no compatible version exists, the request fails as incompatible instead of sending a message with an unsupported shape.
The selection flow is:
flowchart LR
A[Broker API version ranges] --> B[Request builder]
B --> C{Compatible request version}
C -->|yes| D[Versioned request structure]
C -->|no| E[Incompatible broker version]
D --> F[Request header and body]
ApiVersions is special because it can be sent before the client knows the broker's full version map. Other request builders require a known range and can reject fields that the selected version cannot carry. For example, admin builders reject options that need a newer request version rather than silently dropping those options.
References: aiokafka/…/api.py• L70-142 aiokafka/…/admin.py• L48-87 aiokafka/…/admin.py• L214-243 tests/test_requests.py• L133-179
Serialization model
Serialization converts a typed struct into the ordered byte sequence required by the Kafka wire protocol. Deserialization reads the same sequence through the schema and rebuilds the typed struct. The schema is the single contract used in both directions.
The normal path is:
- A request builder chooses a versioned request structure.
- The structure builds a request header from its API identity and schema.
- The header and body encode their fields in schema order.
- The broker response header is parsed with the matching header form.
- The linked response type decodes the response body.
This model also handles null values, nested arrays, compact values, and variable-length integers. The separate record encoding path covers Kafka record and message payloads rather than API request and response envelopes; see record encoding and decoding.
Record message containers
Record message containers are a separate wire path used for Kafka message payloads. A message carries a format version, attributes, key, value, and optional timestamp; a message set groups messages with offsets and can report a final partial message when a fetch limit cuts through the data.
Compression is represented in message attributes. The container validates its CRC and can expand supported compressed message sets before the consumer handles their messages. This payload path is related to, but separate from, API request and response schemas.
References: aiokafka/…/message.py• L28-63 aiokafka/…/message.py• L128-235 aiokafka/…/message.py• L243-304
Tagged fields
Tagged fields are optional fields used by flexible Kafka messages. A schema declares them with numeric tags after its regular fields. During encoding, present tagged fields are written after the regular fields with a tag, byte length, and encoded value. During decoding, absent known tags become None, which allows newer fields to be omitted without shifting the regular fields.
Tags must be declared in ascending order. The decoder maps received tags by number and can preserve known fields even when some declared fields are absent. Tagged fields can contain nested schemas and compact arrays, so the same optional-field rule works inside larger message values.
The tagged-field layout is:
flowchart LR
A[Regular fields] --> B[Tagged field count]
B --> C[Tag]
C --> D[Value size]
D --> E[Encoded value]
E --> F[Next tag or end]
Flexible strings, bytes, and arrays use compact length forms. Request and response headers add an empty tagged-field section when the body schema is flexible, so the full exchange follows one consistent extension rule.
References: aiokafka/…/types.py• L189-303 aiokafka/…/types.py• L374-494 aiokafka/…/admin.py• L1452-1571 aiokafka/…/api.py• L33-64 tests/test_protocol_tagged_fields.py• L19-131
Change checklist
When these files or sections are changed, remember to consider these:
- When a schema gains or removes a field, update every affected API version and its linked response type. Field order is part of the wire contract.
- When a schema becomes flexible, keep request headers, response headers, compact types, and tagged-field handling aligned.
- When an API version range changes, check the ApiVersions message and the request builder's compatibility selection together.
- When a tagged field changes, preserve numeric tag order and the meaning of
Nonefor an absent field. - When a nested schema changes, check struct field access, equality, and array item decoding together.
- When message payload fields or attributes change, keep the message version, CRC coverage, compression flags, and message-set boundary behavior aligned.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A request has no version in the broker's supported range | The client raises an incompatible-version error instead of sending it. | Keep versioned request structures and builder inputs aligned. |
| A request option needs a newer version than the selected one | The builder rejects the request instead of sending a request with missing intent. | Gate version-specific options in the request builder. |
| A request version links to the wrong response structure | The client decodes a valid broker response with the wrong field shape. | Pair each request version with its matching response version. |
| A field is added in the wrong position | The broker reads later bytes as the wrong field type. | Treat schema order as a wire-level contract. |
| Tagged fields are declared out of numeric order | Schema creation fails before the message can be encoded. | Declare tags in ascending order. |
| A flexible body uses a normal header | Header parsing loses the tagged-field section and the exchange cannot be decoded. | Select headers from the same flexibility flag as the body schema. |
| A length prefix exceeds the available bytes | Decoding raises a buffer error instead of returning a partial value. | Preserve valid length prefixes and complete payloads. |
| A message CRC does not match its payload | The message fails integrity validation. | Recalculate or validate CRC over the encoded message body. |
| A compressed message uses an unavailable codec | Payload expansion cannot proceed. | Check codec support before handling compressed message sets. |
| A struct is used as a set or dictionary key | The operation fails because protocol values are unhashable. | Use a stable scalar or serialized value as the key. |
Key files
| File | Why to read it |
|---|---|
| aiokafka/…/api.py | Defines request builders, versioned request structures, response types, API headers, and version selection. |
| aiokafka/…/types.py | Defines primitive, nested, compact, variable-length, and tagged-field wire types. |
| aiokafka/…/struct.py | Shows how schemas become typed messages with encode, decode, field lookup, and value comparison behavior. |
| aiokafka/…/message.py | Shows the separate message and message-set payload path, including version fields, CRC checks, compression, and partial fetch data. |
| aiokafka/…/admin.py | Provides clear examples of the ApiVersions exchange, versioned API messages, compatibility gates, and flexible message schemas. |
| aiokafka/…/produce.py | Shows how one API family evolves response schemas across versions. |
| aiokafka/…/__init__.py | Maps numeric API keys to Kafka operation names. |
| tests/test_protocol_tagged_fields.py | Demonstrates optional tagged fields, compact values, nested schemas, and round-trip behavior. |