KatInterview

Binary Protocol for String Dictionary Persistence

Data Structure DesignModel answer
MediumModel answerData Structure Designserializationbinary-protocolsvalidation

Last updated

Build a binary encoder and decoder for string dictionaries with strict validation of format integrity, size bounds, and key ordering.

Problem

Implement a binary encoding scheme for persisting and restoring dictionaries that map strings to strings. Your solution must produce consistent output regardless of insertion order and must thoroughly validate incoming data against malformed or malicious input.

Protocol Structure

The binary representation consists of:

  1. Header: 4-byte unsigned integer (big-endian) specifying how many entries follow
  2. Body: A sequence of entries, each containing:
    • 4-byte key length (big-endian)
    • Key data (UTF-8 bytes)
    • 4-byte value length (big-endian)
    • Value data (UTF-8 bytes)

Entries must appear sorted by their raw key bytes in ascending order.

Implementation Requirements

Implement this class:

class KVStoreSerializer:
    MAX_KEY_SIZE: int = 65_536       # 64 KiB
    MAX_VALUE_SIZE: int = 1_048_576  # 1 MiB

    def serialize(self, store: dict[str, str]) -> bytes:
        """Encodes a string dictionary into binary format."""
        pass

    def deserialize(self, data: bytes) -> dict[str, str]:
        """Reconstructs a dictionary from binary data. Raises ValueError on invalid input."""
        pass

Validation Requirements for deserialize

Your decoder must reject input by raising ValueError when:

  • The byte stream ends prematurely (missing declared fields or data)
  • Extra bytes remain after reading all declared entries
  • Keys appear in the wrong order or duplicate keys exist
  • Any key exceeds 64 KiB or any value exceeds 1 MiB
  • Key or value bytes are invalid UTF-8

Test Cases

Empty dictionary:

  • Input: {}
  • Output: b'\x00\x00\x00\x00'

Single pair:

  • Input: {"hello": "world"}
  • Binary starts with \x00\x00\x00\x01 (one entry), followed by \x00\x00\x00\x05hello\x00\x00\x00\x05world

Multiple entries must appear sorted by key bytes, not insertion order.

Hints

Hint 1

Use length prefixes rather than delimiters to handle arbitrary string content without escaping

Hint 2

Sort entries by encoded key bytes before writing to ensure consistent output

Hint 3

Validate every length field against both the stated limits and the remaining buffer before attempting to read

Hint 4

Check that each key is strictly greater than the previous one to catch both duplicates and misordering in a single comparison