KatInterview

Binary Wire Format for a Nested Key-Value Map

Data Structure DesignModel answer
MediumModel answerData Structure Designserializationbinary-formatchecksum

Last 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) -> bytes
  • decode(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 equal s.
  • 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.