Unit 3 of 13 · about 4 hours · implement

Length-prefixed and delimited framing, partial reads and writes and coalesced messages

TCP delivers a byte stream, not messages. Without framing, one send can arrive as two reads or three sends as one read, and the parser reads across message boundaries.

You'll be able to

  • Implement a length-prefixed framer that reassembles split messages and splits coalesced buffers.
  • Explain why one send is not one message on a byte stream and where delimiter framing needs escaping.
  • Test partial, split-delimiter and coalesced cases with fixed byte fixtures.

Covers

Length-prefixed and delimiter-based framingPartial reads, partial writes and coalesced messages
1

Read

In this order, only the parts listed

0 of 3 done

  1. Beej sections on send, recv and partial sendsBeej's Guide to Network Programming

    Section 5.7 send and recv: short sends and recv returning 0 on peer close; Section 7.4 Handling Partial send: the sendall loop that repeats until all bytes leave; Section 7.6 Son of Data Encapsulation: a length header on each packet so the receiver can find where one message ends

  2. Avro 1.12.0 message framingProtocol Buffers and Avro - Unknown Fields and Schema Resolution

    Message Framing: a message is a list of buffers, each a four-byte big-endian length plus bytes, terminated by a zero-length buffer; framing lets large binary objects travel as their own buffers and be copied fewer times

  3. DDIA 2e Chapter 5: length prefixes in encodingsDDIA 2e - Chapter 5 Encoding and Evolution

    Chapter 5, JSON, XML, and Binary Variants (pp. 165-169): in the MessagePack walk-through on p. 169, a string preceded by its length needs no end marker or escaping

2

Focus on

  • A length prefix states the frame size up front, so the receiver buffers exactly that many bytes. A delimiter scans for a terminator, so payload bytes need escaping and a split delimiter needs a carried-over buffer.
  • send may move fewer bytes than requested and recv may return any positive amount up to the buffer size. Loops on both sides, not larger buffers, fix this.
  • Coalescing is normal, not a bug: Nagle's algorithm on the sender and buffering in the receiver's kernel join sends. The framer must emit zero, one or several messages per read.
  • The Systems unit on sockets, partial reads and writes, and message framing taught the socket calls. Here the new work is the framed parser and its fault fixtures.
Common mistakes · 3
  • Treating recv returning 0 as an empty message. It means the peer closed; a zero-length frame is a separate protocol event such as the Avro terminator.
  • Growing the receive buffer to avoid partial reads. The stream can split anywhere, so any read size still needs the reassembly loop.
  • Scanning for a delimiter without unescaping. Payload bytes that match the terminator split one message into two corrupt ones.
3

Try it yourself

Closed-book, before checking anything

From a blank file, implement a four-byte big-endian length-prefixed framer with a 1 MiB cap, then feed it a split header, a body in two chunks and two messages in one read, then feed a line-delimited variant a \r\n split across reads, and emit exactly the right messages.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.One send of 5 bytes arrives as 2 then 3 bytes. What does a correct receiver do?Answer

    Buffer both chunks against the length prefix and emit the message only when all 5 payload bytes arrive. Partial reads are expected on a stream.

  2. 2.Two 5-byte messages arrive in one recv of 18 bytes including prefixes. How many messages emerge?Answer

    Two, with no leftover. The framer consumes two length-plus-payload frames from the 18 bytes: 00000005 plus 5 bytes, twice.

  3. 3.Why does a length prefix avoid the escaping problem of delimiter framing?Answer

    The prefix gives the exact byte count, so payload bytes are never scanned for a terminator. Delimited framing must escape or forbid the terminator inside payloads.

  4. 4.A line-delimited parser splits inside \r\n. What state must survive across reads?Answer

    The trailing \r and the unfinished line buffer. The next read may start with \n, and only the pair terminates the frame.

You're done when

Your framer passes split-header, split-body, coalesced-pair and split-delimiter fixtures with no leftover bytes and no cross-boundary reads.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 13 more in the section
  • DDIA 2e - Chapter 5 Encoding and EvolutionMartin Kleppmann and Chris Riccomini · primary

    Read formats, schema evolution, service RPC, durable workflows and event-driven dataflow. Write a four-version compatibility table and connect each compatibility claim to a wire fixture.

  • Protocol Buffers and Avro - Unknown Fields and Schema ResolutionGoogle and the Apache Software Foundation · required

    Read the proto3 guide on field numbers, defaults and unknown fields (kept through binary parsing and reserialization, lost through JSON) and the Avro 1.12.0 schema resolution rules (https://avro.apache.org/docs/1.12.0/specification/). Build round-trip fixtures that show each rule.

  • Beej's Guide to Network ProgrammingBrian Hall · support

    Use the client, server, send, receive, select or poll, and partial-transfer sections when socket behavior is unclear. This is a protocol mechanics reference, not the distributed-systems spine.

Also in this section

  • gRPC Guides - Deadlines, Cancellation, Status Codes, Retry and Flow ControlgRPC Authors · required

    Read the deadlines, cancellation, status codes, retry (enabled by default with no default policy; no retry once response headers arrive), keepalive and flow-control guides. Turn each into a rule your own RPC layer follows, and check a claim against grpcio before you rely on it.

  • Building Distributed Systems - The MessengerBuild Distributed Systems · support

    Track 1 is free: do the RPC subtrack (sync RPC with timeout, timeout and retry loop, async callbacks, callback reaper, exponential backoff) and the deduplication task. Tasks are graded in the browser after login, so treat a pass as a drill and keep your local harness as the evidence.

  • MIT 6.5840 - RPC and Threads plus Lab 2 Key/Value ServerMIT PDOS · required

    Read the Lecture 2 notes (notes/l-rpc.txt and notes/kv.go) on RPC failure and at-most-once execution, then do Lab 2: a versioned Put key/value server whose client returns ErrMaybe when a retried Put may already have run, and a lock built on it. Keep the course tests, then add cancellation, size-limit and mixed-version faults in your own harness.

  • DSLabs - Lab 1 Exactly-Once RPCUniversity of Washington (Ellis Michael) · support

    Labs are Java 21 message-passing state machines tested on an emulated network and by model-checking search tests that print a minimal violating trace; run them with the run-tests.py script and its --lab and --part options. Lab 1 builds an "exactly-once" RPC abstraction for an unreplicated key/value server on a network that drops, duplicates and reorders messages. Use it to check your request identity and duplicate-suppression design against exhaustive orderings.

  • HLD Handbook - Networking, API Design and BackpressureHLD Handbook · required

    Read only Part 0 networking and API design, then the load balancer, service discovery, rate limiting and reliability chapters needed for the protocol design. Use the diagrams to review boundaries, not as a substitute for fault tests.

  • AWS Builders' Library - Timeouts, Retries and Backoff with JitterAmazon Web Services · required

    Read the whole article for timeout choice, retries at one layer, retry amplification across hops, capped exponential backoff and jitter. Derive the request multiplier for retries at every layer of a call chain before writing your retry policy.

  • AWS Builders' Library - Making Retries Safe with Idempotent APIsAmazon Web Services · support

    Read the caller-provided client request identifier pattern, the validation error for a repeated identifier with different parameters, the semantically equivalent response to a retry and why the identifier is retained only for a bounded interval. Compare that interval with your own duplicate-suppression state.

  • Building Distributed Systems - The NetworkerBuild Distributed Systems · optional

    Only the first three tasks are free (TCP echo, connection pool and backlog, graceful shutdown and drain). Tasks are graded in the browser after login, so treat a pass as a drill and keep your local harness as the evidence.

  • AlgoMaster System Design - Selected Networking and API ProblemsAlgoMaster · optional

    Use the problems on idempotency and retries (Deduplicate Idempotent Requests, Build an Idempotent Consumer, Classify Retry Outcomes), rate limiting (sliding-window log and token bucket), the Least Requests load balancer and the queue visibility timeout. For every solved component, add an external fault test and explain what its simplified judge does not establish.

  • Replicated Log and Stream Processor - Protocol SliceRoadmap-Final · support

    Create the repository, message schema, request and node identities, deadline and retry contract, deterministic network scheduler and raw event format. Keep this same artifact through DS-9.

  • RFC 9000 - QUIC Version 1IETF · reference

    Read Section 2 (streams), Section 4 (flow control) and Section 9 (connection migration) for QUIC transport behavior. No implementation; compare with TCP behavior from the Systems stage.

  • RFC 9114 - HTTP/3IETF · reference

    Read Sections 3 (connection setup), 6 (stream mapping) and 7 (framing) for how HTTP semantics map onto QUIC streams.

  • W3C Trace ContextW3C · reference

    Read Section 3.2 (traceparent fields), Section 3.3 (tracestate) and Section 4 (processing model) for trace correlation without synchronized clocks.