Skip to content

Lesson 3 of 9 · 24m

Framing and Wire Formats: Turning Streams into Messages

Protocols need explicit message boundaries — length prefixes, delimiters, serialization choices, and the parser state machine that avoids partial-read chaos.

Once TCP gives you a byte stream, your first protocol job is framing: deciding where one message ends and the next begins. Most custom-protocol outages are framing bugs. They hide during local tests because loopback often delivers bytes in convenient chunks, then appear in production when segment sizes change.

Delimiters work until payloads contain them

Text protocols often use newline-delimited messages:

buffer = bytearray()

while chunk := sock.recv(4096):
    buffer.extend(chunk)
    while b"
" in buffer:
        line, _, rest = buffer.partition(b"
")
        buffer = bytearray(rest)
        handle_line(line)

This is simple and debuggable with nc, but it requires an escaping or encoding rule. JSON Lines avoids ambiguity by making each line a complete JSON document; newline inside a string is encoded as \n, not raw byte 0x0a.

Length prefixes are the boring correct default

Binary protocols commonly send a fixed-size header containing the payload length:

import struct

def send_frame(sock, payload: bytes) -> None:
    sock.sendall(struct.pack("!I", len(payload)) + payload)

def read_exact(sock, n: int) -> bytes:
    chunks = []
    remaining = n
    while remaining:
        chunk = sock.recv(remaining)
        if not chunk:
            raise EOFError("peer closed mid-frame")
        chunks.append(chunk)
        remaining -= len(chunk)
    return b"".join(chunks)

!I means network byte order, unsigned 32-bit integer. Read the four-byte length with read_exact, then read exactly that many payload bytes. Enforce a maximum size before allocation or parsing — a hostile peer can claim a two-gigabyte frame.

Pick serialization by consumer, not fashion

JSON is inspectable and broadly supported, but verbose and type-weak. Protobuf, MessagePack, and CBOR are compact and schema-friendly, but harder to inspect by hand. Custom structs are fastest to write and fastest to regret unless compatibility is designed deliberately. Whatever the encoding, framing is separate: JSON can sit inside a length-prefixed binary frame, and protobuf can sit inside a newline protocol if encoded safely.

Parsers are state machines

A robust parser holds partial bytes across reads, consumes complete frames, rejects oversized or malformed input, and preserves leftover bytes for the next message. Never parse directly from a single recv result. Write tests that split every fixture at every byte boundary; this catches off-by-one framing mistakes better than one happy-path integration test.

Field notes

  • Always define maximum frame size, encoding, endianness, and error behavior in writing.
  • Include a protocol version even when you think version one is final.
  • Do not use pickle on network input; it is code execution with extra steps.
  • Put authentication and authorization after framing, not before a message boundary exists.
  • Fuzz the parser with truncated frames, extra bytes, and concatenated valid messages.

Was this lesson helpful?

Sign in to rate