← Questions

Read whole messages from a socket stream

0
AppleCodingLast asked Sep 2025

A coding interview question asked in Apple's technical phone screen, last asked Sep 2025. It tests networking, parsing and buffers.

TCP delivers a stream of bytes, not messages. A single recv(k) may return part of a message, several messages, or nothing at all. Write a reader that turns the stream into whole messages, in two framing variants.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • The reader wraps a socket with recv(k: int) -> bytes, which returns between 0 and k bytes; b"" means the peer closed the connection.
  • Variant A, length-prefixed: each message is a 4-byte big-endian unsigned length followed by that many bytes. read_message() -> bytes | None returns exactly one message per call, or None at a clean end of stream.
  • Variant B, newline-delimited: read_line() -> str | None returns the next line without its \n, or None at end of stream.
  • Both keep an internal buffer across calls.

Example

Variant A, with recv returning these chunks in turn:

b"\x00\x00"
b"\x00\x02hi\x00\x00\x00\x03ab"
b"c"
b""

read_message()  ->  b"hi"     # the header was split across two reads
read_message()  ->  b"abc"    # its body was split across two reads
read_message()  ->  None      # clean end of stream

Constraints

  • Messages may be empty (length 0) or large; set a maximum message size.
  • End of stream in the middle of a header or body is an error, not a clean close.

Clarifying questions

  • What should happen on end of stream with a partial message buffered?
  • Is there a maximum message size, and what happens above it?
  • Is the socket blocking? Are timeouts needed?
  • In variant B, is \r\n possible, and is a final line without \n valid?

What a strong answer covers

  • A buffer plus a loop that calls recv until enough bytes are present, then slices off exactly one message and keeps the rest.
  • Avoiding O(n^2) copying: a bytearray with a read offset, or a deque of chunks.
  • Rejecting oversized lengths before allocating, so a bad header can't exhaust memory.
  • Distinguishing a clean close from a truncated message; handling timeouts and interrupted calls.
  • Unit tests with a fake socket that returns scripted chunks: one byte at a time, many messages in one chunk, zero-length messages, truncation.

Follow-ups

  • Make it non-blocking for use with an event loop.
  • Write the matching sender, and handle partial sends.
  • Support a protocol where the length is a variable-length integer.

Where it's asked

  • Apple · Technical phone screen · Last asked Sep 2025

What it tests

networking · parsing · buffers

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding