KatInterview

Reframing Chunked Async Reads into Length-Prefixed Frames

Data Structure DesignModel answer
HardModel answerData Structure Designstreamingstate-machineasync

Last 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.