Binary Wire Format for a Nested Key-Value Map
Data Structure DesignModel answerLast updated
Design and implement a versioned, checksummed binary format that converts a nested key-value map to bytes and back, and compare it with JSON and MessagePack.
You are building persistence for an in-memory key-value store. The store is a map from UTF-8 string keys to values. Each value is one of:
- a 64-bit signed integer
- a 64-bit float
- a boolean
- a UTF-8 string
- another map of the same shape (nesting of any reasonable depth)
Write two functions:
encode(store) -> bytesdecode(data: bytes) -> store
Before coding, define the binary layout. It must cover:
- a magic number and a version
- a type tag for each value
- length prefixes
- a fixed byte order
- an integrity checksum
- a plan for forward and backward compatibility
Requirements:
decode(encode(s))must equals.- Both directions run in O(n) time in the size of the data and use little extra memory beyond the output.
- The decoder must treat input as untrusted. Truncated, corrupted, or hostile buffers must raise a clean error. They must never read out of bounds, loop forever, or exhaust the stack.
Finish with a short comparison of your format against a text format such as JSON and against a general binary format such as MessagePack.
Hints
Hint 1
Write the byte layout on paper first and give every field an exact width and byte order. Once the layout is fixed, the code follows it directly.
Hint 2
Length-prefix every value, including fixed-size ones. That one decision gives you bounds checking, the ability to skip tags you do not recognise, and a way to confine a nested map to its own byte window.
Hint 3
You cannot know a nested map's size before you have written it. Reserve four bytes, write the child, then go back and patch the length in place.
Hint 4
Validate in a fixed order: size, magic, major version, flags, declared length, checksum, and only then parse. Inside the parse, check every read against the end of the current window and cap the nesting depth.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat this as a small protocol design problem. Fix the layout first, then write an encoder that follows it and a decoder that trusts nothing.
Layout (all integers little-endian)
Buffer := Header Payload Trailer
Header := magic "KVST" (4) | major u8 | minor u8 | flags u16 | payload_len u32 -> 12 bytes
Payload := Map
Map := count u32 | Entry * count
Entry := key_len u32 | key bytes | tag u8 | body_len u32 | body bytes
Trailer := crc32 u32 (covers Header + Payload)
| tag | type | body |
|---|---|---|
| 1 | int64 | 8 bytes, two's complement |
| 2 | float64 | 8 bytes, IEEE-754 (NaN, inf and -0.0 preserved) |
| 3 | bool | 1 byte, 0 or 1 only |
| 4 | string | raw UTF-8 |
| 5 | map | a nested Map |
Little-endian is the native order on x86 and ARM, so no byte swapping is needed on common hardware. What matters is that the format states the order explicitly.
Why the length prefix on every value
It costs 4 bytes per value, and it buys three things:
- Safe reads. Every read is compared with the end of the current window.
- Forward compatibility. A reader that meets an unknown tag skips
body_lenbytes and carries on. - Isolation. A child map is decoded with its own end offset, so a corrupt child cannot consume its parent's bytes.
Compatibility rules
- A different major version means the layout changed. Reject the buffer.
- A higher minor version only adds tags or optional trailing data. An older reader skips unknown tags. A stricter variant keeps them as opaque bytes so they survive a re-save.
- Tags are never renumbered or redefined, so new readers always accept old data.
flagsis reserved (compression, for example). Reject any bit you do not understand, because silently ignoring one would misread the payload.
Encoder
Append to one bytearray. For nested maps, write a 4-byte placeholder, encode the child, then patch the length with pack_into. Each byte is written once, so there is no second pass and no per-level temporary buffer.
Decoder
- Check the buffer is at least header plus trailer, then check magic, major, and flags.
- Check
12 + payload_len + 4 == len(data). - Verify the CRC before parsing, so random corruption is rejected cheaply.
- Parse with a
memoryview(no copies) and an explicitendfor each window. Cap depth at 64. - After a nested map, require that it consumed exactly its declared bytes.
Code
import struct, zlib
MAGIC = b"KVST"
MAJOR, MINOR = 1, 0
INT, FLT, BOOL, STR, MAP = 1, 2, 3, 4, 5
MAX_DEPTH = 64
U32_MAX = 0xFFFFFFFF
HDR = struct.Struct("<4sBBHI")
U32 = struct.Struct("<I")
I64 = struct.Struct("<q")
F64 = struct.Struct("<d")
class FormatError(ValueError):
pass
def encode(store: dict) -> bytes:
buf = bytearray(HDR.size)
_put_map(buf, store, 0)
plen = len(buf) - HDR.size
if plen > U32_MAX:
raise ValueError("store too large")
HDR.pack_into(buf, 0, MAGIC, MAJOR, MINOR, 0, plen)
buf += U32.pack(zlib.crc32(buf))
return bytes(buf)
def _put_map(buf, m, depth):
if depth > MAX_DEPTH:
raise ValueError("nesting too deep")
buf += U32.pack(len(m))
for k, v in m.items():
if not isinstance(k, str):
raise TypeError("keys must be str")
kb = k.encode("utf-8")
buf += U32.pack(len(kb)) + kb
_put_value(buf, v, depth)
def _put_value(buf, v, depth):
if isinstance(v, dict):
buf.append(MAP)
at = len(buf)
buf += b"\0\0\0\0" # placeholder
_put_map(buf, v, depth + 1)
U32.pack_into(buf, at, len(buf) - at - 4) # back-patch
return
if isinstance(v, bool): # before int
tag, body = BOOL, (b"\x01" if v else b"\x00")
elif isinstance(v, int):
if not -(1 << 63) <= v < (1 << 63):
raise OverflowError("int64 range")
tag, body = INT, I64.pack(v)
elif isinstance(v, float):
tag, body = FLT, F64.pack(v)
elif isinstance(v, str):
tag, body = STR, v.encode("utf-8")
else:
raise TypeError(type(v).__name__)
buf.append(tag)
buf += U32.pack(len(body)) + body
def decode(data: bytes) -> dict:
mv = memoryview(data)
if len(mv) < HDR.size + 4:
raise FormatError("too short")
magic, major, minor, flags, plen = HDR.unpack_from(mv, 0)
if magic != MAGIC:
raise FormatError("bad magic")
if major != MAJOR:
raise FormatError("unsupported major version")
if flags:
raise FormatError("unknown flags")
end = HDR.size + plen
if end + 4 != len(mv):
raise FormatError("length mismatch")
if zlib.crc32(mv[:end]) != U32.unpack_from(mv, end)[0]:
raise FormatError("checksum mismatch")
store, pos = _get_map(mv, HDR.size, end, 0)
if pos != end:
raise FormatError("trailing bytes")
return store
def _u32(mv, pos, end):
if pos + 4 > end:
raise FormatError("truncated")
return U32.unpack_from(mv, pos)[0], pos + 4
def _text(mv, a, b):
try:
return str(mv[a:b], "utf-8")
except UnicodeDecodeError:
raise FormatError("invalid utf-8") from None
def _get_map(mv, pos, end, depth):
if depth > MAX_DEPTH:
raise FormatError("nesting too deep")
n, pos = _u32(mv, pos, end)
out = {}
for _ in range(n):
klen, pos = _u32(mv, pos, end)
if pos + klen + 1 > end:
raise FormatError("truncated key")
key = _text(mv, pos, pos + klen)
pos += klen
if key in out:
raise FormatError("duplicate key")
tag = mv[pos]
vlen, pos = _u32(mv, pos + 1, end)
vend = pos + vlen
if vend > end:
raise FormatError("truncated value")
if tag == INT:
if vlen != 8: raise FormatError("bad int")
out[key] = I64.unpack_from(mv, pos)[0]
elif tag == FLT:
if vlen != 8: raise FormatError("bad float")
out[key] = F64.unpack_from(mv, pos)[0]
elif tag == BOOL:
if vlen != 1 or mv[pos] > 1: raise FormatError("bad bool")
out[key] = bool(mv[pos])
elif tag == STR:
out[key] = _text(mv, pos, vend)
elif tag == MAP:
out[key], p = _get_map(mv, pos, vend, depth + 1)
if p != vend: raise FormatError("map size mismatch")
# unknown tag: skipped via vend (forward compatibility)
pos = vend
return out, pos
Complexity
- Time: O(n) for both directions. Each byte is written or read once, and the CRC is one linear pass.
- Space: The encoder uses the output buffer plus O(depth) recursion. The decoder uses a zero-copy view plus the result it builds, also with O(depth) recursion. Use
zlib.crc32incrementally if you want to avoid slicing large buffers.
Trade-offs against other formats
| This format | JSON | MessagePack | |
|---|---|---|---|
| Size | Compact; fixed 4-byte lengths cost a little on tiny values | Verbose; numbers and escapes as text | Compact; variable-width ints save more |
| Speed | Fast, no parsing of text | Slower; number and string parsing | Fast |
| Skippable fields | Yes, by length | Must scan to find the end | Yes for most types |
| Schema and integrity | Versioned, checksummed | None built in | None built in |
| Readability and tooling | Needs a custom tool | Human-readable, universal | Wide library support |
Choose a custom format when you control both ends and need a checksum and versioning. Choose JSON for debuggability and interoperability, and MessagePack when you want compactness without maintaining your own spec.
Common mistakes
- Checking
isinstance(v, int)beforebool, so booleans are stored as integers. - Trusting
countor lengths and allocating or looping before validating them. - Letting a child map read past its own length.
- Unbounded recursion on deeply nested hostile input.
- Not rejecting unknown flags or a different major version.
- Forgetting that invalid UTF-8 can arrive inside a CRC-valid buffer.
- Accepting trailing bytes, which hides framing bugs.