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.

View as Markdown

Binary messages are fast to read because every field sits at a known byte offset (how a binary message is put together). 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:

  1. 0symbol41A41A50P4cL20␠20␠20␠20␠AAPL, then four spaces
The symbol AAPL in 8 bytes, padded with 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:

  1. 0symbol42B54T43C55U53S44D54TBTCUSDT
  2. 7end00␀the zero byte that ends it
BTCUSDT ended by a zero byte
  • 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 is written this way:

OffsetBytesFieldTypeValueMeaning
6207symbol.lengthuint877 bytes follow
63–6942 54 43 55 53 44 54symbol.varDatauint8"BTCUSDT"
The BestBidAskStreamEvent at byte 686 of the synthetic BTCUSDT stream (btcusdt-stream.sbe), field by field; offsets count from the frame's first byte
  • 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:

 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
OffsetBytesFieldTypeValueMeaning
0–35a 00 00 00length prefixuint329090 message bytes follow
4–512 00messageHeader.blockLengthuint1618root block: 18 bytes
6–710 27messageHeader.templateIduint1610000TradesStreamEvent
8–901 00messageHeader.schemaIduint161
10–1100 00messageHeader.versionuint160
12–192d e2 da bd c0 69 06 00eventTimeutcTimestampUs18051264001398212027-03-15 16:00:00.139821 UTC
20–27d9 df da bd c0 69 06 00transactTimeutcTimestampUs18051264001392252027-03-15 16:00:00.139225 UTC
28fepriceExponentexponent8-2× 10^-2
29f8qtyExponentexponent8-8× 10^-8
30–3119 00trades.blockLengthuint162525 bytes per entry
32–3502 00 00 00trades.numInGroupuint3222 entries follow
36–43ac 80 ef fa 00 00 00 00trades[0].idtradeId4210000044
44–51ae f9 5f 00 00 00 00 00trades[0].pricemantissa64628983862898.38
52–5928 23 00 00 00 00 00 00trades[0].qtymantissa6490000.00009000
6001trades[0].isBuyerMakerboolEnum1True
61–68ad 80 ef fa 00 00 00 00trades[1].idtradeId4210000045
69–76ad f9 5f 00 00 00 00 00trades[1].pricemantissa64628983762898.37
77–8450 46 00 00 00 00 00 00trades[1].qtymantissa64180000.00018000
8501trades[1].isBuyerMakerboolEnum1True
8607symbol.lengthuint877 bytes follow
87–9342 54 43 55 53 44 54symbol.varDatauint8"BTCUSDT"
The TradesStreamEvent at byte 7203 of the synthetic BTCUSDT stream (btcusdt-stream.sbe), field by field; offsets count from the frame's first byte

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:

  1. 0eventTime57c7d8bdc06906001,805,126,400,001,879
  2. 8symbol pointer1800000007000000offset 24, length 7
  3. 16clientId pointer1f00000004000000offset 31, length 4
  4. 24symbol42544355534454BTCUSDT, in the tail section at byte 24
  5. 31clientId4f524431ORD1, at byte 31
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
  • 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) 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, variable-length data fields).

Layout of DepthSnapshotStreamEvent in the Binance Spot Streams SBE schema, as the Market Data Visualizer lays it out
OffsetSizeNameTypePresenceSince
018DepthSnapshotStreamEventblock0
08eventTimeutcTimestampUsrequired0
88bookUpdateIdupdateIdrequired0
161priceExponentexponent8required0
171qtyExponentexponent8required0
184bidsgroup groupSize16Encoding0
182.blockLengthuint16
202.numInGroupuint16
2216[0]entry
228.pricemantissa64required0
308.qtymantissa64required0
384asksgroup groupSize16Encoding0
382.blockLengthuint16
402.numInGroupuint16
4216[0]entry
428.pricemantissa64required0
508.qtymantissa64required0
581symboldata varString80

Open the bids group in the Market Data Visualizer's layout

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
RowIts listColumn valueRepetition levelMeans
06289838, 628983762898380a new row starts
062898371the same list continues
1628822262882220a 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, so a query can read only the price column of a list of trades across millions of rows without touching id or qty.

Sources

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