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 / record-encoding-and-decoding

Kafka record encoding and decoding

The record layer turns Kafka record bytes into records that producers and consumers can use. It reads old message formats and current record batches, builds bytes for outgoing data, checks data integrity, and preserves the metadata needed for timestamps, offsets, compression, transactions, and control markers. The Kafka protocol model provides the wider context for how these records move through Kafka requests and responses.

Record format families

The record layer supports two Kafka wire-format families. The magic value selects the family: values 0 and 1 use the legacy message format, while value 2 and later use the default record batch format. The related record batch format guide covers these wire layouts in more detail.

Legacy record format

The legacy format stores each message with an offset, length, CRC, magic value, attributes, and key/value data. Magic 0 has no timestamp. Magic 1 adds a timestamp and a timestamp type. Legacy messages do not carry record headers. aiokafka/…/legacy_records.py reads these messages and composes them into batches for older broker versions.

Legacy compression wraps a set of messages inside one outer message. The reader expands that message before it returns the inner records. It restores the record offsets and applies the wrapper timestamp when the batch uses broker-assigned time.

References: aiokafka/…/legacy_records.py• L36-109 aiokafka/…/legacy_records.py• L112-285 aiokafka/…/legacy_records.py• L317-508

Default record batch format

The default format groups records into one batch with shared batch metadata. The batch carries offsets, timestamps, producer state, transaction state, attributes, and a record count. Each record then carries delta values plus a nullable key, a nullable value, and zero or more headers. aiokafka/…/default_records.py provides the reader and builder for magic 2 and later.

The batch stores a base offset and base timestamp. Each record stores an offset delta and timestamp delta, so the reader reconstructs the values that callers see. This shared metadata lets one batch represent producer and transaction state without repeating it in every record.

References: aiokafka/…/default_records.py• L92-244 aiokafka/…/default_records.py• L246-356 aiokafka/…/default_records.py• L383-583

Record stream handling

The record stream is the in-memory view of bytes received from or prepared for Kafka. aiokafka/…/memory_records.py walks the stream by reading each length field, then uses the magic byte to create the matching legacy or default batch reader.

Batch selection

The stream reader uses the common leading position of the length field to find the next batch without first knowing its format. It checks that the complete batch is present, rejects a batch that is smaller than the minimum record overhead, and returns no next batch when only an incomplete trailing slice remains. This gives fetch handling a stable sequence of batches even when one response contains mixed format versions.

The high-level record package exposes MemoryRecords as the entry point. The shared protocols in aiokafka/…/_protocols.py keep the two format families aligned around batch iteration, record fields, metadata, and CRC checks.

References: aiokafka/…/memory_records.py• L1-20 aiokafka/…/memory_records.py• L37-105 aiokafka/…/_protocols.py• L80-120 aiokafka/…/_protocols.py• L203-260

Record composition and parsing

Builders accept record fields and return metadata while they add records to a size-limited batch. A later build step writes the batch header, final offsets and timestamps, producer state, compression choice, and checksum. Readers expose records through iteration and report the batch's next offset so fetch code can advance even when compaction removes the final record.

The main composition flow is shared in shape but not in wire details:

flowchart LR
    A[Record fields] --> B{Format version}
    B -->|Magic 0 or 1| C[Legacy batch builder]
    B -->|Magic 2 or later| D[Default batch builder]
    C --> E[Optional compression and CRC]
    D --> F[Optional compression and CRC32C]
    E --> G[Kafka batch bytes]
    F --> G
    G --> H[MemoryRecords]
    H --> I{Magic byte}
    I -->|0 or 1| J[Legacy batch reader]
    I -->|2 or later| K[Default batch reader]
    J --> L[Decoded records]
    K --> L

The default builder also tracks producer ID, producer epoch, and base sequence for idempotent or transactional publishing. The legacy builder returns per-record CRC metadata, while default record metadata reports the record size and timestamp because the batch CRC is the relevant integrity value.

References: aiokafka/…/_protocols.py• L14-77 aiokafka/…/_protocols.py• L157-200 aiokafka/…/legacy_records.py• L317-573 aiokafka/…/default_records.py• L383-693

Compression and integrity

Compression reduces the bytes sent for a batch, while CRC checks detect changes in the bytes that Kafka returned. The builder selects a codec through batch attributes. The reader checks that the matching codec is available before it expands the records.

Compression codecs

Legacy batches support gzip, Snappy, and LZ4. Default batches support those codecs plus Zstandard. The default builder keeps data uncompressed when compression does not make the batch smaller. A missing codec library or a codec that the selected legacy version cannot use raises UnsupportedCodecError instead of producing data that the reader cannot handle.

References: aiokafka/…/legacy_records.py• L94-109 aiokafka/…/legacy_records.py• L158-190 aiokafka/…/legacy_records.py• L458-502 aiokafka/…/default_records.py• L130-147 aiokafka/…/default_records.py• L222-244 aiokafka/…/default_records.py• L547-583

CRC validation

Legacy messages use a CRC over the message data after the stored CRC field. Default batches use CRC-32C over the batch attributes and records, while excluding the partition leader epoch. The reader exposes validate_crc() so fetch code can check a complete batch before it yields records.

CRC calculation has a Python path and an optional accelerated path. Both paths use the same CRC-32C result for default batches, and the record layer keeps the check separate from record iteration so callers can choose when to validate.

References: aiokafka/…/legacy_records.py• L154-156 aiokafka/…/default_records.py• L350-356 aiokafka/…/util.py• L117-150 aiokafka/…/cutil.pyi• L9-12 aiokafka/…/fetcher.py• L207-217

Control and transaction records

Control records carry transaction state rather than user data. A default batch marks itself as a control batch through its attributes. The control record key contains a small version and type pair. ControlRecord.parse() decodes that pair, while ABORT_MARKER and COMMIT_MARKER define the known marker values in aiokafka/…/control_record.py.

The fetch path reads control batches for transaction state but does not return them as consumer records. At READ_COMMITTED isolation, an abort marker ends the set of records that must be hidden for its producer. Transactional data from an aborted producer is skipped, while ordinary control batches are skipped at every isolation level.

References: aiokafka/…/control_record.py• L5-25 aiokafka/…/default_records.py• L115-123 aiokafka/…/default_records.py• L187-192 aiokafka/…/fetcher.py• L219-262 aiokafka/…/fetcher.py• L273-294

Accelerated record implementations

The record layer has a Python implementation and optional Cython implementations for stream walking, legacy records, default records, variable-length integers, and CRC-32C. Normal imports select the accelerated classes when their extensions are available. The AIOKAFKA_NO_EXTENSIONS setting forces the Python path.

The two paths share the same public protocols and record behavior. If an extension cannot be imported, the layer falls back to Python so encoding and decoding remain available without a compiler-built module. The accelerated modules are performance options, not a second record format.

References: aiokafka/util.py• L85-98 aiokafka/…/memory_records.py• L107-117 aiokafka/…/legacy_records.py• L576-603 aiokafka/…/default_records.py• L696-729 aiokafka/…/cutil.pyi• L9-12 aiokafka/…/util.py• L123-150 setup.py• L22-53

Change checklist

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

  • Keep magic-byte dispatch in MemoryRecords aligned with every supported batch reader.
  • Keep batch builders and readers aligned when a field, delta rule, attribute bit, or record header changes.
  • Keep the CRC coverage and CRC implementation aligned between Python and Cython paths.
  • Keep codec availability checks consistent for build and read paths, including legacy-version limits.
  • Keep control-batch flags and marker parsing aligned with fetch filtering at READ_COMMITTED isolation.
  • Keep producer state and next_offset behavior aligned with fetch offset advancement and transaction filtering.
  • Keep the .pyi contracts aligned with both Python fallbacks and accelerated record classes.

Important failure modes

TriggerConsequenceGuard
A batch length points past the available response bytesThe stream stops before that batch, so the fetch layer can wait for or refetch the remaining bytesMemoryRecords checks the complete slice before it returns a batch
A batch has an invalid CRCThe consumer raises CorruptRecordException instead of returning changed dataFetch handling validates each batch when CRC checks are enabled
A configured codec has no support libraryBuild or read fails with UnsupportedCodecErrorCodec availability is checked before compression or decompression
A default record has a negative header count or leaves bytes unreadThe batch is rejected as corruptThe default reader checks header count and exact record length
A control batch is treated as user dataTransaction markers can reach the consumer or aborted data can be exposedFetch handling consumes marker state and skips all control batches
An accelerated extension is missingPerformance falls back to PythonImport selection uses the Python implementation when extensions are unavailable

Key files

FileWhy to read it
aiokafka/…/memory_records.pyShows how one byte stream selects and yields legacy or default batches.
aiokafka/…/legacy_records.pyDefines the old message formats, their builders, compression, and CRC behavior.
aiokafka/…/default_records.pyDefines the current batch format, record fields, headers, producer state, compression, and CRC-32C behavior.
aiokafka/…/control_record.pyDefines the transaction marker payload and the abort and commit markers.
aiokafka/…/fetcher.pyShows how decoded batches become consumer records and how CRCs, transactions, and control batches affect delivery.
aiokafka/…/_protocols.pyStates the common contracts shared by Python and accelerated implementations.
aiokafka/…/util.pyProvides variable-length integer and CRC-32C support used by the default format.
aiokafka/record/_crecords/default_records.pyxShows the accelerated default-batch path and its shared wire-format contract.
aiokafka/record/_crecords/cutil.pyiDescribes the accelerated CRC and variable-length integer helpers.
setup.pyShows which record operations can use Cython extensions.