Reframing Chunked Async Reads into Length-Prefixed Frames
Data Structure DesignModel answerLast updated
Turn an async sequence of arbitrarily split byte chunks into complete frames, each preceded by a 4-byte big-endian length, while handling truncation and oversized lengths.
Rebuild Framed Messages from an Async Byte Stream
A network layer delivers bytes as an asynchronous sequence of chunks. The chunk boundaries are arbitrary and have nothing to do with message boundaries. The bytes themselves form a series of frames:
- A 4-byte header holding the payload length as an unsigned 32-bit integer in big-endian order.
- Followed by exactly that many payload bytes.
Write a component that reads the chunked async sequence and produces, as another async sequence, one byte array per frame, containing only the payload (no header).
Suggested C# shape
public class FrameReassembler
{
public async IAsyncEnumerable<byte[]> ReadFramesAsync(
IAsyncEnumerable<ReadOnlyMemory<byte>> source)
{
// implement
}
}
You may use another language (for example an async generator over bytes in Python) as long as the behavior is the same.
Rules
- The header is always exactly 4 bytes.
- A payload may be at most 10 MB. A larger declared length is an error.
- If the source ends while a frame is only partly received (inside a header or inside a payload), throw an
EndOfStreamException(or your language's equivalent). - If the source ends exactly between frames, or was empty, finish normally.
Example
Input bytes: 00 00 00 02 AA BB 00 00 00 01 CC
Output frames: [AA BB], [CC]
The first header declares 2 payload bytes, so AA BB is one frame. The next header declares 1 byte, so CC is the second.
Situations your solution must handle
- A chunk that holds only part of a header (say 2 of its 4 bytes).
- A chunk that holds several complete frames.
- A payload delivered across three or more chunks.
What to deliver
Describe your approach, give the implementation, and state the time and space complexity. Explain how you handle empty chunks, zero-length payloads, and invalid lengths.
Hints
Hint 1
Chunk boundaries and frame boundaries are unrelated, so keep state between chunks: how many header bytes you have so far, or how much of the current payload you have filled.
Hint 2
Model it as two states, reading header and reading payload. In each step copy min(bytes still needed, bytes left in this chunk), and loop inside a chunk until it is exhausted, since one chunk can complete many frames.
Hint 3
Check the declared length against the 10 MB limit before allocating anything, treat zero-length payloads as complete the moment the header finishes, and at end of stream raise only if a header or payload is partly filled.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Chunk boundaries are independent of frame boundaries, so the reader has to be a small state machine whose progress survives from one chunk to the next. There are two states:
- Header state. Copy bytes into a fixed 4-byte buffer until it is full. Decode it as an unsigned big-endian 32-bit integer, validate it, and allocate a payload buffer of exactly that size.
- Payload state. Copy bytes into the payload buffer until it is full, emit it, and return to the header state.
Within each chunk, keep looping until every byte is consumed, because a single chunk may finish one frame and contain several more.
State to retain between chunks: the header buffer with a headerFilled count, and (when active) the payload buffer with a payloadFilled count.
Why not accumulate into one growing buffer?
A common first attempt appends every chunk to a list or MemoryStream and repeatedly removes consumed bytes from the front. Front removal is O(n), so a long stream can degrade to quadratic time. Copying each byte straight into its final destination buffer means every byte is moved once.
Correctness argument
- Invariant: between chunks, either no payload is active and
headerFilledis in 0..3, or a payload buffer exists withpayloadFilled < length. - Each step copies
min(needed, remaining in chunk), so a step can never cross a frame boundary or discard data. - Partial headers and partial payloads survive in the counters. Several frames per chunk are handled by the inner loop.
- Zero-length payload: emit an empty array as soon as the header completes. Do not enter the payload state, otherwise the reader would wait for bytes that never arrive.
- Validation before allocation: parse the length as
uint, compare it with 10 MB while still unsigned, and only then convert toint. A hostile header therefore cannot trigger a huge allocation or an integer overflow. - End of stream: it is legal only on a frame boundary, meaning
headerFilled == 0and no payload active. Anything else is a truncated frame, so throwEndOfStreamException.
Complexity
- Time: O(T) for T total bytes, since each byte is copied once.
- Space: O(4 + L) working memory, where L is the largest payload (at most 10 MB). The payload buffer is handed to the caller, so it is the output rather than extra overhead.
Code (C#)
using System.Buffers.Binary;
public class FrameReassembler
{
private const int HeaderSize = 4;
private const uint MaxPayload = 10u * 1024 * 1024;
public async IAsyncEnumerable<byte[]> ReadFramesAsync(
IAsyncEnumerable<ReadOnlyMemory<byte>> source)
{
var header = new byte[HeaderSize];
int headerFilled = 0;
byte[]? payload = null;
int payloadFilled = 0;
await foreach (var mem in source)
{
int pos = 0;
int n = mem.Length;
while (pos < n)
{
if (payload is null)
{
int take = Math.Min(HeaderSize - headerFilled, n - pos);
mem.Slice(pos, take).CopyTo(header.AsMemory(headerFilled));
headerFilled += take;
pos += take;
if (headerFilled < HeaderSize) break;
uint len = BinaryPrimitives.ReadUInt32BigEndian(header);
headerFilled = 0;
if (len > MaxPayload)
throw new InvalidDataException($"Payload {len} exceeds limit");
if (len == 0)
{
yield return Array.Empty<byte>();
continue;
}
payload = new byte[len];
payloadFilled = 0;
}
else
{
int take = Math.Min(payload.Length - payloadFilled, n - pos);
mem.Slice(pos, take).CopyTo(payload.AsMemory(payloadFilled));
payloadFilled += take;
pos += take;
if (payloadFilled == payload.Length)
{
var done = payload;
payload = null;
yield return done;
}
}
}
}
if (headerFilled != 0 || payload is not null)
throw new EndOfStreamException("Stream ended inside a frame");
}
}
Using ReadOnlyMemory<byte> rather than a Span matters here: spans cannot be held across an await or yield, so the code slices the memory object directly.
Edge cases checked
- Header split across chunks (2 + 2 bytes), or a header ending exactly at a chunk end with the payload in the next chunk.
- Many frames in one chunk, possibly ending in a partial one.
- A payload spread over three or more chunks.
- Empty chunks: the
while (pos < n)loop simply does nothing. - Back-to-back zero-length frames.
- Declared length above 10 MB: rejected right after the header.
- EOF mid-header or mid-payload: throws. EOF on a boundary or an empty stream: completes normally.
Common mistakes
- Assuming one chunk equals one frame, or processing only one frame per chunk.
- Reading the length as a signed
int, giving negative sizes for values at or above 2^31. - Using little-endian decoding.
- Allocating before validating the length.
- Waiting for payload bytes after a zero-length header.
- Treating a clean EOF as an error, or a truncated one as success.
- Trimming the front of a growing buffer after each frame, which is quadratic.
Follow-ups worth discussing
- Lower allocation rate: rent payload buffers from
ArrayPool<byte>and yield an owner object the consumer disposes, or useSystem.IO.PipelineswithReadOnlySequence<byte>to parse in place and avoid copying. - Backpressure: an async-enumerable pull model gives it for free, since the source is only read when the consumer asks for the next frame.
- Cancellation: add an
[EnumeratorCancellation] CancellationTokenparameter and pass it to the source. - Hostile peers: beyond the size cap, add a read timeout and a limit on total buffered memory per connection.