Binary Protocol for String Dictionary Persistence
Data Structure DesignModel answerLast 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:
- Header: 4-byte unsigned integer (big-endian) specifying how many entries follow
- 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires building a self-describing binary format with two critical properties: determinism and robustness.
Core Design Decisions
Length-prefixed fields: Each string is preceded by its byte length as a 4-byte integer. This eliminates ambiguity—you always know exactly how many bytes to consume next. Delimiter-based approaches would require escaping because keys and values can contain any characters.
Deterministic encoding: Two dictionaries with identical content must produce identical bytes. Achieve this by sorting entries by their UTF-8 byte representation before writing. Python dictionaries maintain insertion order, so without sorting, {"a": "1", "b": "2"} and {"b": "2", "a": "1"} would produce different output despite being logically equal.
Defensive parsing: The decoder must never assume well-formed input. Before reading N bytes, verify that N bytes remain. Before allocating based on a declared length, check that the length is within bounds. At the end, ensure no trailing data remains.
Serialization Strategy
- Convert all keys and values to UTF-8 bytes, checking size limits
- Sort the encoded pairs by key bytes (ascending lexicographic order)
- Write the entry count as a 4-byte big-endian integer
- For each pair, write: key length, key bytes, value length, value bytes
- Concatenate all pieces into a single byte string
Checking size limits during serialization ensures your encoder never produces output its own decoder would reject.
Deserialization Strategy
Use a cursor to track position in the input buffer. For each read operation:
- Verify sufficient bytes remain for the next field
- Extract and validate the field
- Advance the cursor
Early rejection of invalid counts: If the declared entry count is N, at minimum 8N bytes are needed (two 4-byte length fields per entry). Check this immediately after reading the count.
Ordering validation: Track the previous key. When reading a new key, verify it's strictly greater than the previous one. This single check enforces both uniqueness and correct sort order.
Final validation: After reading all entries, the cursor must exactly equal the buffer length. Any remaining bytes indicate corruption or a versioning mismatch.
Why This Works
Correctness: The encoder and decoder use the same field order and the same sorting logic. Every dictionary has exactly one valid encoding, and every valid encoding decodes to one dictionary.
Security: Malicious inputs with oversized length fields, enormous entry counts, or crafted overflow conditions are caught by bounds checks before causing memory issues or infinite loops.
UTF-8 byte order: UTF-8 preserves Unicode code point ordering, so sorting by bytes is equivalent to sorting by strings for valid UTF-8. Using bytes is more explicit and matches what the decoder validates.
Complexity
Let B = total byte size, N = number of entries, K = average key length.
Encoding: O(B + N log N × K) — UTF-8 conversion is O(B), sorting is O(N log N) comparisons, each comparison is O(K)
Decoding: O(B) — each byte is examined once; key comparisons are bounded by key length
Space: O(B) for both operations
Edge Cases and Common Mistakes
Empty strings: Both empty keys and empty values are valid and have length 0. The empty string sorts before all non-empty strings.
Exact limits: A key of exactly 65,536 bytes is valid. Only lengths strictly greater than the limit are rejected.
Byte vs. character limits: Limits apply to encoded bytes, not Unicode characters. A string with 40,000 two-byte characters is 80,000 bytes and exceeds the key limit.
UTF-8 validation: Lone surrogates, overlong encodings, and truncated sequences must all be rejected. Python's strict UTF-8 codec handles this, but wrap decoding exceptions in a clear error message.
Type checking: Non-string keys or values should be rejected, not silently converted. This prevents accidental misuse.
Overflow in count: More than 2³²−1 entries cannot fit in a 4-byte count field.
Implementation
import struct
_U32_STRUCT = struct.Struct(">I")
class KVStoreSerializer:
MAX_KEY_SIZE: int = 65_536
MAX_VALUE_SIZE: int = 1_048_576
def serialize(self, store: dict[str, str]) -> bytes:
if len(store) > 0xFFFFFFFF:
raise ValueError("entry count exceeds 4-byte limit")
encoded_pairs: list[tuple[bytes, bytes]] = []
for key, value in store.items():
if not isinstance(key, str) or not isinstance(value, str):
raise ValueError("all keys and values must be strings")
key_bytes = key.encode("utf-8")
value_bytes = value.encode("utf-8")
if len(key_bytes) > self.MAX_KEY_SIZE:
raise ValueError(f"key size {len(key_bytes)} exceeds limit")
if len(value_bytes) > self.MAX_VALUE_SIZE:
raise ValueError(f"value size {len(value_bytes)} exceeds limit")
encoded_pairs.append((key_bytes, value_bytes))
encoded_pairs.sort(key=lambda pair: pair[0])
chunks = [_U32_STRUCT.pack(len(encoded_pairs))]
for key_bytes, value_bytes in encoded_pairs:
chunks.append(_U32_STRUCT.pack(len(key_bytes)))
chunks.append(key_bytes)
chunks.append(_U32_STRUCT.pack(len(value_bytes)))
chunks.append(value_bytes)
return b"".join(chunks)
def deserialize(self, data: bytes) -> dict[str, str]:
buffer = memoryview(data)
buffer_len = len(buffer)
cursor = 0
def read_uint32() -> int:
nonlocal cursor
if buffer_len - cursor < 4:
raise ValueError("insufficient data for length field")
value, = _U32_STRUCT.unpack_from(buffer, cursor)
cursor += 4
return value
def read_chunk(length: int, max_size: int, name: str) -> bytes:
nonlocal cursor
if length > max_size:
raise ValueError(f"{name} size {length} exceeds maximum {max_size}")
if buffer_len - cursor < length:
raise ValueError(f"insufficient data for {name}")
chunk = bytes(buffer[cursor:cursor + length])
cursor += length
return chunk
entry_count = read_uint32()
if entry_count * 8 > buffer_len - cursor:
raise ValueError("entry count inconsistent with remaining data")
result: dict[str, str] = {}
last_key_bytes: bytes | None = None
for _ in range(entry_count):
key_len = read_uint32()
key_bytes = read_chunk(key_len, self.MAX_KEY_SIZE, "key")
if last_key_bytes is not None and key_bytes <= last_key_bytes:
raise ValueError("keys must be strictly increasing")
value_len = read_uint32()
value_bytes = read_chunk(value_len, self.MAX_VALUE_SIZE, "value")
try:
key_str = key_bytes.decode("utf-8")
value_str = value_bytes.decode("utf-8")
except UnicodeDecodeError as e:
raise ValueError(f"invalid UTF-8 encoding: {e}")
result[key_str] = value_str
last_key_bytes = key_bytes
if cursor != buffer_len:
raise ValueError(f"unexpected trailing data: {buffer_len - cursor} bytes remain")
return result
This implementation is production-ready: it handles all edge cases, provides clear error messages, and processes data efficiently in a single pass.