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-batch-formats

Record batch formats and validation

Record batches are the wire-level containers that carry Kafka records from a broker to the client and from the producer to the broker. This area lets the client accept older message formats and the current batch format through one iterator while preserving offsets, timestamps, headers, transaction state, and data-integrity checks.

Batch format families

The record layer supports two format families. Legacy batches use magic 0 or 1 and represent one message or a compressed message set. Default batches use magic 2 or newer and represent a single batch with shared metadata and a sequence of compact records.

Format familyRecord featuresBatch meaning
LegacyOptional timestamp, nullable key and value, no record headersA batch can contain one message or a compressed set of messages
DefaultRelative offsets and timestamps, record headers, producer state, transaction flagsOne batch carries shared metadata and a record count

Both families expose a common high-level shape to the fetch path. The differences remain visible where they affect compatibility: legacy records expose a CRC as their checksum, while default records expose no per-record checksum because integrity belongs to the batch.

References: aiokafka/…/legacy_records.py• L30-73 aiokafka/…/default_records.py• L7-55 aiokafka/…/_protocols.py• L123-154 aiokafka/…/_protocols.py• L203-252

Legacy batches

Legacy batches preserve compatibility with Kafka message versions 0 and 1. Magic 0 has no timestamp, while magic 1 adds a timestamp and timestamp type. Legacy attributes also identify the compression codec and whether the timestamp came from record creation or broker append time.

Compression wraps the message data inside the legacy batch. Iteration expands that data into individual records and restores the record offsets needed by the consumer. The batch checks that a supported codec is available before it reads compressed data, and it rejects unsupported or invalid compression states.

References: aiokafka/…/legacy_records.py• L79-109 aiokafka/…/legacy_records.py• L147-190 aiokafka/…/legacy_records.py• L238-285

Default batches

Default batches are the format for magic 2 and newer. A batch stores shared offset, timestamp, producer, transaction, and compression metadata. Each record then stores deltas from the batch values, plus nullable key and value fields and a list of string-and-value headers.

The batch converts relative offsets and timestamp deltas into the absolute values exposed by the record interface. For append-time timestamps, every record uses the batch maximum timestamp. This keeps the compact wire format compatible with the consumer-facing record model.

Default batches can use the codecs named by their batch attributes. The reader expands compressed record data before it iterates over records, while the builder keeps compression only when it reduces the batch size.

References: aiokafka/…/default_records.py• L86-147 aiokafka/…/default_records.py• L156-244 aiokafka/…/default_records.py• L246-348 aiokafka/…/default_records.py• L547-583

Memory record containers

aiokafka/…/memory_records.py provides MemoryRecords, a byte-backed container for a fetch response. It does not need to know the full format before it starts: the shared leading layout gives it the length of the next item, and the magic byte selects the batch reader.

The container advances through complete batch slices without copying the original fetch buffer. It reports whether another complete batch is ready, returns a format-specific batch, and leaves incomplete trailing bytes for the fetch layer to handle as a partial response. A slice smaller than the minimum legacy record overhead is treated as corrupt rather than as a usable batch.

This diagram shows how one fetch buffer becomes a sequence of format-specific batches and then common record objects.

flowchart LR
    A[Fetch response bytes] --> B[MemoryRecords]
    B --> C{Magic byte}
    C -->|0 or 1| D[Legacy batch]
    C -->|2 or newer| E[Default batch]
    D --> F[Legacy records]
    E --> G[Default records]
    F --> H[Consumer record flow]
    G --> H

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

Record iteration contract

Batch iteration turns wire records into a protocol-compatible record interface. Both record types provide offset, timestamp, timestamp type, key, value, and headers, so downstream fetch code can process them without branching on the wire format.

The contract has format-specific limits. Legacy records may have no timestamp and always have an empty header list. Default records always have a timestamp and may carry headers. A nullable key or value remains None in either format, so consumers can distinguish a missing field from an empty byte string.

The fetch path uses the batch's next_offset after iteration. This matters when compaction removes the last record or when a compressed legacy batch contains records whose offsets differ from the outer batch offset. The consumer can therefore advance past the complete batch without re-fetching it.

References: aiokafka/…/_protocols.py• L123-154 aiokafka/…/_protocols.py• L219-252 aiokafka/…/default_records.py• L218-220 aiokafka/…/default_records.py• L328-348 aiokafka/…/legacy_records.py• L151-152 aiokafka/…/legacy_records.py• L238-285 aiokafka/…/fetcher.py• L254-271

Checksums and validation

Checksums protect different units in the two format families. Legacy validation uses CRC-32 over the message data after the legacy CRC field. Default validation uses CRC-32C over the batch data from the attributes field to the end of the batch, which excludes the partition leader epoch.

Validation occurs before normal record iteration for default batches because iteration may replace the compressed payload with its expanded form. The reader then validates record structure while it reads: invalid header counts, negative header key sizes, mismatched record lengths, and leftover bytes produce CorruptRecordException.

Validation targetCheckExposed result
Legacy batchCRC-32 over the batch payloadvalidate_crc() and each legacy record checksum
Default batchCRC-32C over shared batch data and recordsvalidate_crc() and no per-record checksum
Memory containerComplete length and minimum-size checksCorruptRecordException for malformed batch slices
Default record streamRecord lengths, header counts, and consumed bytesCorruptRecordException during iteration

References: aiokafka/…/legacy_records.py• L154-156 aiokafka/…/default_records.py• L350-356 aiokafka/…/default_records.py• L282-345 aiokafka/…/memory_records.py• L72-105

Control records

Control records are broker-created records that mark transaction boundaries rather than user data. A control batch is identified by the control attribute in a default batch, and its record key contains a two-field marker with a version and a marker type.

The record layer recognizes abort and commit markers. The fetcher uses the abort marker to stop tracking an aborted producer, then skips every control batch before it yields user records. This keeps transaction coordination metadata out of the application record stream.

sequenceDiagram
    participant F as Fetcher
    participant B as Control batch
    participant R as Control record key
    F->>B: Read batch flags
    B-->>F: Control batch
    F->>R: Parse version and marker type
    R-->>F: Abort or commit marker
    F->>F: Update transaction state
    F-->>F: Skip control batch

References: aiokafka/…/default_records.py• L187-192 aiokafka/…/control_record.py• L5-32 aiokafka/…/fetcher.py• L220-252 aiokafka/…/fetcher.py• L285-294

Change checklist

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

  • Keep the shared leading offsets used by MemoryRecords aligned with every supported batch header. A header layout change can make format selection or length slicing fail before a batch reader runs.
  • Keep validate_crc() and the corresponding builder CRC range aligned. A change to the covered bytes can make locally built batches fail broker or reader validation.
  • Keep default record delta decoding aligned with default batch metadata. Offset or timestamp changes must preserve the absolute values required for fetch offset advancement.
  • Keep control marker encoding aligned with fetcher transaction handling. Changes to marker version or type can make aborted data visible or leave an aborted producer marked active.
  • Keep the common record protocols aligned across legacy and default records. A missing nullable field, header, or checksum behavior can break consumer record conversion.

Important failure modes

TriggerConsequenceGuard
Fetch data ends before a complete batch is availableThe container stops exposing a batch and the fetch layer must wait for more dataLength and minimum-slice checks in MemoryRecords
Batch CRC does not match its covered bytesCorrupt data can be detected before records are usedCall validate_crc() before normal iteration
Required compression library is unavailableThe batch cannot be decodedCodec availability checks raise UnsupportedCodecError
Default record length or header count is invalidIteration cannot safely locate the next recordStructural checks raise CorruptRecordException
A control batch is treated as user dataTransaction markers could reach the applicationThe fetcher parses abort markers and skips all control batches

Key files

FileWhy to read it
aiokafka/…/memory_records.pyShows how one fetch buffer is split into legacy and default batches.
aiokafka/…/legacy_records.pyDefines compatibility behavior for magic 0 and 1 records.
aiokafka/…/default_records.pyDefines the current batch metadata, record fields, compression, and CRC-32C validation.
aiokafka/…/control_record.pyDefines transaction marker values carried by control records.
aiokafka/…/_protocols.pyStates the common batch and record contracts used by both format families.
aiokafka/…/fetcher.pyShows how validation results, offsets, control batches, and records affect consumer output.
docs/record-encoding-and-decoding.mdParent page for the wider record serialization and deserialization flow.