# Variable-sized data and lists in binary messages

> How binary formats fit text, byte strings and lists whose length changes from message to message into fields at fixed offsets, the common patterns and their trade-offs, and how common formats choose among them.

Page: https://structure.fi/guides/variable-sized-data/

Binary messages are fast to read because every field sits at a known byte offset ([how a binary message is put together](https://structure.fi/guides/binary-message/#fields-and-padding)). Real trading data does not always fit that neat picture. Binance's market-data streams send each update's symbol as text, so its length changes with the instrument: `BTCUSDT` for one, `ETHBTC` for another. On CME, one aggressive order can fill against one resting order or eighty, and the trade summary message carries one entry for each order filled, so its list is as long as the trade needs. An order book snapshot likewise carries as many price levels as the book has.

The moment one field's length can change, every field *after* it loses its fixed offset. Binary formats have settled on a handful of patterns for variable-sized values (text, byte strings, and lists of records), each trading size, decoding speed, random access and safety differently.

## Different ways to encode variable-sized data

Say you want to send a variable-length symbol like `BTCUSDT`, or a list of trades. Every format builds from the same patterns:

### 1. Fixed maximum with padding

Pick a ceiling, say 8 bytes for a stock symbol, and always write 8 bytes, padding shorter values with spaces or zero bytes:

The symbol AAPL in 8 bytes, padded with spaces:

| Offset | Bytes | Holds | Note |
| --- | --- | --- | --- |
| 0 | `41 41 50 4c 20 20 20 20` | symbol | AAPL, then four spaces |

- **Strengths:** every field keeps a constant offset, there is nothing to parse, and 8 bytes compare or copy as one 64-bit integer.
- **Weaknesses:** short values waste bytes, and the day a symbol is longer than the ceiling, it is cut short or the format has to change.

### 2. Terminator (sentinel byte)

Write the bytes followed by an end marker that cannot appear inside the data, like the zero byte at the end of a C string or the newline at the end of a line of text:

BTCUSDT ended by a zero byte:

| Offset | Bytes | Holds | Note |
| --- | --- | --- | --- |
| 0 | `42 54 43 55 53 44 54` | symbol | BTCUSDT |
| 7 | `00` | end | the zero byte that ends it |

- **Strengths:** one byte of overhead whatever the length; simple for text.
- **Weaknesses:** the reader has to look at every byte to find the end (no jumping ahead), arbitrary bytes cannot use it without escaping because `0x00` can be part of the data, and a missing terminator sends the reader past the end of the buffer. In C, where every string ends with a zero byte, that is one of the most common security bugs: a string whose terminator is missing or overwritten makes the program read, or copy, memory that belongs to something else (a buffer over-read or overflow).

### 3. Length prefix (for strings, byte strings and nested messages)

Write the length as a small integer just before the bytes. The symbol at the end of the best-bid-and-ask message from [how a binary message is put together](https://structure.fi/guides/binary-message/#an-example-message) is written this way:

The BestBidAskStreamEvent at byte 686 of the synthetic BTCUSDT stream (btcusdt-stream.sbe), field by field; offsets count from the frame's first byte:

| Offset | Bytes | Field | Type | Value | Meaning |
| --- | --- | --- | --- | --- | --- |
| 62 | `07` | symbol.length | uint8 | 7 | 7 bytes follow |
| 63–69 | `42 54 43 55 53 44 54` | symbol.varData | uint8 | "BTCUSDT" |  |

- **Strengths:** works for any bytes (`0x00` included), lets a reader check in one comparison that the bytes fit in what it received, and lets it skip the field in one addition (`offset + 1 + 7`).
- **Weaknesses:** the width of the length caps the size (255 bytes for one byte of length, 65,535 for two), and every field *after* it moves with the length. That is why formats with fixed offsets put variable-length fields at the very end of a message.

### 4. Count prefix (for lists of records)

For a list of records that all have the same shape, such as trades or order book levels, write a small header saying how many records follow (and often how many bytes each takes), then the records back to back.

Here is a real `TradesStreamEvent` with **2 trades** from the same synthetic `btcusdt-stream.sbe` sample, at byte 7203 of the file. After the 8-byte message header and the 18-byte block of fixed fields comes the list header, `trades.blockLength` (bytes per trade) and `trades.numInGroup` (how many trades), then the two trades, then the symbol:

The TradesStreamEvent at byte 7203 of the synthetic BTCUSDT stream (btcusdt-stream.sbe), field by field; offsets count from the frame's first byte:

```text
 0  5a 00 00 00 12 00 10 27 01 00 00 00 2d e2 da bd  Z......'....-...
16  c0 69 06 00 d9 df da bd c0 69 06 00 fe f8 19 00  .i.......i......
32  02 00 00 00 ac 80 ef fa 00 00 00 00 ae f9 5f 00  .............._.
48  00 00 00 00 28 23 00 00 00 00 00 00 01 ad 80 ef  ....(#..........
64  fa 00 00 00 00 ad f9 5f 00 00 00 00 00 50 46 00  ......._.....PF.
80  00 00 00 00 00 01 07 42 54 43 55 53 44 54        .......BTCUSDT
```

| Offset | Bytes | Field | Type | Value | Meaning |
| --- | --- | --- | --- | --- | --- |
| 0–3 | `5a 00 00 00` | length prefix | uint32 | 90 | 90 message bytes follow |
| 4–5 | `12 00` | messageHeader.blockLength | uint16 | 18 | root block: 18 bytes |
| 6–7 | `10 27` | messageHeader.templateId | uint16 | 10000 | TradesStreamEvent |
| 8–9 | `01 00` | messageHeader.schemaId | uint16 | 1 |  |
| 10–11 | `00 00` | messageHeader.version | uint16 | 0 |  |
| 12–19 | `2d e2 da bd c0 69 06 00` | eventTime | utcTimestampUs | 1805126400139821 | 2027-03-15 16:00:00.139821 UTC |
| 20–27 | `d9 df da bd c0 69 06 00` | transactTime | utcTimestampUs | 1805126400139225 | 2027-03-15 16:00:00.139225 UTC |
| 28 | `fe` | priceExponent | exponent8 | -2 | × 10^-2 |
| 29 | `f8` | qtyExponent | exponent8 | -8 | × 10^-8 |
| 30–31 | `19 00` | trades.blockLength | uint16 | 25 | 25 bytes per entry |
| 32–35 | `02 00 00 00` | trades.numInGroup | uint32 | 2 | 2 entries follow |
| 36–43 | `ac 80 ef fa 00 00 00 00` | trades[0].id | tradeId | 4210000044 |  |
| 44–51 | `ae f9 5f 00 00 00 00 00` | trades[0].price | mantissa64 | 6289838 | 62898.38 |
| 52–59 | `28 23 00 00 00 00 00 00` | trades[0].qty | mantissa64 | 9000 | 0.00009000 |
| 60 | `01` | trades[0].isBuyerMaker | boolEnum | 1 | True |
| 61–68 | `ad 80 ef fa 00 00 00 00` | trades[1].id | tradeId | 4210000045 |  |
| 69–76 | `ad f9 5f 00 00 00 00 00` | trades[1].price | mantissa64 | 6289837 | 62898.37 |
| 77–84 | `50 46 00 00 00 00 00 00` | trades[1].qty | mantissa64 | 18000 | 0.00018000 |
| 85 | `01` | trades[1].isBuyerMaker | boolEnum | 1 | True |
| 86 | `07` | symbol.length | uint8 | 7 | 7 bytes follow |
| 87–93 | `42 54 43 55 53 44 54` | symbol.varData | uint8 | "BTCUSDT" |  |

The symbol starts at byte 82 of the message (86 of the frame, after its 4-byte length). With one trade it would start at byte 57, and with 21 trades at byte 557: each trade adds 25 bytes. Fixed fields go *before* the list so their offsets never change; the reader switches to walking entry by entry only when it reaches the list.

- **Strengths:** compact (no tag repeated per record), fast to scan, and entry `i` sits at `start + i × entry size` as long as every entry has the same size.
- **Weaknesses:** that direct jump is lost as soon as an entry holds its own list or a variable-length string, because then entries no longer share one size.

### 5. Offsets into a tail section

Keep the fixed part of the message truly fixed: store an `(offset, length)` pair in the fixed block for each variable-sized value, and put the values themselves in a section at the end of the buffer. FlatBuffers, Cap'n Proto and Apache Arrow's string columns work this way:

A fixed block whose variable-sized values live in a tail section; each pointer is an offset and a length, 4 bytes each, low byte first:

| Offset | Bytes | Holds | Note |
| --- | --- | --- | --- |
| 0 | `57 c7 d8 bd c0 69 06 00` | eventTime | 1,805,126,400,001,879 |
| 8 | `18 00 00 00 07 00 00 00` | symbol pointer | offset 24, length 7 |
| 16 | `1f 00 00 00 04 00 00 00` | clientId pointer | offset 31, length 4 |
| 24 | `42 54 43 55 53 44 54` | symbol | BTCUSDT, in the tail section at byte 24 |
| 31 | `4f 52 44 31` | clientId | ORD1, at byte 31 |

- **Strengths:** real random access: you can read `clientId` without touching `symbol`, and read the message in place without copying.
- **Weaknesses:** bytes spent on every pointer, harder writing (the offsets have to be computed or filled in afterwards), and a reader has to check every offset and length against the buffer, or a bad one sends it outside the message or into another value.

### 6. No lists inside a message: one message per item

Sometimes the cleanest way to avoid variable-length lists is not to have them. Instead of one book update carrying a list of 20 price level changes, send 20 small fixed-size "add order" or "delete order" messages one after another. Nasdaq's TotalView-ITCH feed works this way: every message type has a fixed size (an Add Order message is always 36 bytes, with its stock symbol padded to 8 bytes with spaces), and a change to many orders is many messages.

- **Strengths:** every message has one small, constant layout with no moving offsets, simple enough to decode in hardware.
- **Weaknesses:** every item repeats the framing and the shared fields (symbol, time, sequence number), and an update that has to apply as a whole needs an explicit "end of batch" signal.

## What goes wrong when decoding variable-sized data

Three bugs show up as soon as a message stops having a fixed size:

- **Indexing into entries of different sizes:** assuming `entry[i]` starts at `start + i × entry size` works for fixed entries like `trades` above, and silently reads garbage the day an entry gains a nested list or a variable-length string.
- **Trusting a length or count:** a corrupt or hostile `length = 65535` in a 70-byte message makes a reader run past the buffer or allocate far too much memory. Check `offset + length <= message end` before reading or allocating.
- **Forgetting the empty list:** with a count prefix, an empty list still writes its header (count `0`), and the next field starts right after it. Reading entry 0 without checking the count reads the next section's bytes as a record. A format with tags writes nothing at all for an empty list.

## How common formats choose

### SBE (count-prefixed groups and length-prefixed data)

SBE combines **count-prefixed repeating groups** (`<group>`) with **length-prefixed variable-length data** (`<data>`), in a strict order: fixed fields first, groups second, variable-length data last, both in the message and inside each group entry.

Every group starts with a small header holding `blockLength` (the size of one entry's fixed fields, so older decoders can skip fields that newer versions add; see [schema versioning](https://structure.fi/guides/schema-versioning/)) and `numInGroup` (the number of entries). In Binance's Spot Streams schema, `DepthSnapshotStreamEvent` uses `groupSize16Encoding` (`uint16` `blockLength`, `uint16` `numInGroup`) for `bids` and `asks`, then `varString8` (a `uint8` length and UTF-8 bytes) for `symbol` ([how an SBE message is laid out](https://structure.fi/guides/sbe-message-layout/), [variable-length data fields](https://structure.fi/guides/sbe-variable-length-data/)).

Layout of DepthSnapshotStreamEvent in the Binance Spot Streams SBE schema, as the Market Data Visualizer lays it out:

| Offset | Size | Name | Type | Presence | Since |
| --- | --- | --- | --- | --- | --- |
| 0 | 18 | DepthSnapshotStreamEvent | block |  | 0 |
| 0 | 8 |  eventTime | utcTimestampUs | required | 0 |
| 8 | 8 |  bookUpdateId | updateId | required | 0 |
| 16 | 1 |  priceExponent | exponent8 | required | 0 |
| 17 | 1 |  qtyExponent | exponent8 | required | 0 |
| 18 | 4 |  bids | group groupSize16Encoding |  | 0 |
| 18 | 2 |   .blockLength | uint16 |  |  |
| 20 | 2 |   .numInGroup | uint16 |  |  |
| 22 | 16 |   [0] | entry |  |  |
| 22 | 8 |    .price | mantissa64 | required | 0 |
| 30 | 8 |    .qty | mantissa64 | required | 0 |
| 38 | 4 |  asks | group groupSize16Encoding |  | 0 |
| 38 | 2 |   .blockLength | uint16 |  |  |
| 40 | 2 |   .numInGroup | uint16 |  |  |
| 42 | 16 |   [0] | entry |  |  |
| 42 | 8 |    .price | mantissa64 | required | 0 |
| 50 | 8 |    .qty | mantissa64 | required | 0 |
| 58 | 1 |  symbol | data varString8 |  | 0 |

[Open the bids group in the Market Data Visualizer's layout](https://structure.fi/tools/market-data-visualizer/app/#open?sample=binance-stream&node=m10002%2Fg100&place=layout&guide=variable-sized-data&section=block-39)

### Protobuf (repeated tagged fields and length-delimited blocks)

Protobuf has no fixed offsets to protect, so it uses **length prefixes** for strings, bytes and nested messages, and marks lists with `repeated`, with no count in front and no bytes at all for an empty list:

- **Repeated nested messages:** each element is written as its own record: the field's tag, the element's length, then its bytes. With `message Trade { int64 id = 1; int64 price = 2; int64 qty = 3; bool is_buyer_maker = 4; }` and `repeated Trade trades = 5`, the two trades above become `2a 10` and 16 bytes, then `2a 11` and 17 bytes (the lengths differ because varints are shorter for smaller numbers). Elements do not even have to be next to each other.
- **Packed repeated numbers** (the default in proto3 and Editions 2023 for lists of numbers): all elements go into one record, a tag, the total length, then the varints back to back, so the tag is not repeated; reading is still element by element.

### Parquet (columnar repetition and definition levels)

Parquet stores data by column, so it never keeps one row's list items next to the row's other fields. It writes every item of a list field, across all rows, into one column, and stores a small **repetition level** beside each value to mark where a new row's list starts (and a **definition level** for empty and null lists):

Two rows of a list of prices, flattened into one column with repetition levels:

| Row | Its list | Column value | Repetition level | Means |
| --- | --- | --- | --- | --- |
| 0 | 6289838, 6289837 | 6289838 | 0 | a new row starts |
| 0 |  | 6289837 | 1 | the same list continues |
| 1 | 6288222 | 6288222 | 0 | a new row starts |

A `0` starts a new row; a `1` continues the same list. Both kinds of level compress tightly with [run-length and bit-packed encoding](https://structure.fi/guides/parquet-encodings-and-compression/#rle-and-bit-packing), so a query can read only the `price` column of a list of trades across millions of rows without touching `id` or `qty`.

## Sources

- https://github.com/FIXTradingCommunity/fix-simple-binary-encoding/blob/master/v1-0-STANDARD/doc/03MessageStructure.md
- https://www.fixtrading.org/standards/sbe/
- https://github.com/binance/binance-spot-api-docs/blob/master/sbe/schemas/stream_1_0.xml
- https://protobuf.dev/programming-guides/encoding/#repeated
- https://protobuf.dev/programming-guides/encoding/#packed
- https://www.nasdaqtrader.com/content/technicalsupport/specifications/dataproducts/NQTVITCHSpecification.pdf
- https://parquet.apache.org/docs/file-format/nestedencoding/
- https://github.com/apache/parquet-format/blob/master/LogicalTypes.md

Reviewed by Structure on 2026-11-24. Last changed 2026-11-24.
