Frame Length-Prefixed Messages Over a TCP Stream Like gRPC
Last updated: November 29, 2026
Quick Overview
TCP delivers a byte stream, not messages; implement an encoder and an incremental decoder for gRPC-style frames (1 byte compressed flag, 4 byte big-endian length, payload) that copes with reads splitting or merging frames and rejects oversized messages.
0
0
0 solved
TCP delivers a byte stream, not messages; implement an encoder and an incremental decoder for gRPC-style frames (1 byte compressed flag, 4 byte big-endian length, payload) that copes with reads splitting or merging frames and rejects oversized messages.
gRPC carries most RPC traffic inside and outside Google, and its message framing is a common fundamentals question. The interviewer checks that you know recv can return any number of bytes and that a length prefix must be bounded before allocating.
What the Interviewer Expects
- Explain why TCP needs application-level framing
- Encode a fixed header with struct packing in network byte order
- Buffer partial reads and emit only complete frames
- Handle many frames in one read and one frame across many reads
- Enforce a maximum message size before buffering the payload
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
- Why is a length prefix better than a delimiter for binary payloads?
- How does HTTP/2 framing sit underneath gRPC messages?
- How would you avoid quadratic copying when the buffer grows?
- What should the decoder do after a protocol error?
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
encode(payload, compressed=False)returns header plus payload.FrameDecoder(max_size).feed(chunk)returns a list of complete(compressed, payload)frames.- Partial frames stay buffered unti...
High-Level Design
The header is struct.pack('>BI', flag, len), 5 bytes, big-endian as network protocols conventionally use. The decoder keeps a bytearray buffer and a read offset. On each feed it appends the chun...