Frame Messages Over a TCP Stream Using Length Prefixes
Last updated: November 29, 2026
Quick Overview
A warehouse scanner client sends messages to a server over a raw TCP socket, and the server sometimes sees half messages or two messages glued together. Explain why and implement length-prefixed framing that decodes correctly regardless of how bytes are split across reads.
Amazon
November 29, 20260
0
0 solved
A warehouse scanner client sends messages to a server over a raw TCP socket, and the server sometimes sees half messages or two messages glued together. Explain why and implement length-prefixed framing that decodes correctly regardless of how bytes are split across reads.
Fulfillment center devices and internal services often speak simple binary protocols, and assuming one send equals one recv is a classic production bug. The interviewer checks TCP stream semantics, buffer management, byte order, and defensive limits.
What the Interviewer Expects
- States that TCP preserves byte order but not message boundaries
- Uses a fixed-size length header in network byte order
- Buffers partial headers and partial bodies across reads
- Rejects oversized lengths to avoid memory exhaustion
- Handles peer close mid-frame and zero-length messages
Key Topics to Cover
How to Approach This
- Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
- Choose data structures based on access patterns, not familiarity.
- Prefer immutable data and message passing over shared mutable state for concurrency.
- Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
- Compare length prefixes with delimiter-based framing such as newline-delimited JSON.
- How would you add a message type and version to the header?
- How would you avoid copying when frames are large?
- Where would TLS fit in this stack?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice System Design ProblemsSample Answer
Requirements
- Message: 4-byte unsigned big-endian length, then that many payload bytes.
- Decoder accepts arbitrary chunks from
recvand returns zero or more complete messages. - Frames over 1 MiB are a protoco...
High-Level Design
TCP delivers a byte stream; Nagle's algorithm, segmentation, and the receive buffer all mean one send can arrive in pieces or merged with the next. The decoder keeps a bytearray: while at least 4 ...