Streaming Parsers in Python: Chunked Reads and Delimited Messages

Read large files in chunks with flat memory and parse delimited or length-prefixed messages split across chunks, in linear time.

Guide · 9 min read

A streaming parser reads input in chunks as it arrives and emits each complete record, such as a line, a delimited message or a length-prefixed frame, as soon as the bytes that end it show up. It never loads the whole input, so memory stays at roughly one chunk plus one incomplete record whether the input is a kilobyte or a terabyte. The hard part is that chunk boundaries fall anywhere: in the middle of a record, in the middle of a multi-byte delimiter, or between two bytes of a UTF-8 character. In Python the standard tools are a generator, a bytearray buffer, bytes.find with a start offset so you never rescan what you have already searched, and iter(lambda: f.read(size), b"") to pull fixed-size chunks from a file.

This guide covers bounded-memory chunked reads, a delimited message parser that handles splits anywhere in linear time, the quadratic trap most first drafts fall into, length-prefixed framing, and the asyncio equivalents. Every snippet is complete and runs on Python 3.12 or newer.

Reading a file in fixed-size chunks

The first rule of bounded memory is never to call f.read() or f.readlines() on input you don't control. Read a fixed number of bytes at a time instead. The two-argument form of iter calls a function until it returns the sentinel, which turns read into a chunk iterator.

import os
import tempfile
import tracemalloc

CHUNK = 64 * 1024

with tempfile.TemporaryDirectory() as tmp:
    src = os.path.join(tmp, "big.bin")
    dst = os.path.join(tmp, "copy.bin")
    with open(src, "wb") as f:
        for _ in range(160):
            f.write(os.urandom(CHUNK))

    tracemalloc.start()
    with open(src, "rb") as fin, open(dst, "wb") as fout:
        for chunk in iter(lambda: fin.read(CHUNK), b""):
            fout.write(chunk)
    _, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()

    size_mb = os.path.getsize(dst) / 2**20
    print(f"copied {size_mb:.0f} MiB with peak traced memory under 1 MiB: {peak < 2**20}")
    # copied 10 MiB with peak traced memory under 1 MiB: True

Ten MiB went through with well under one MiB of Python allocations, and the peak would be the same for ten GiB. shutil.copyfileobj(fin, fout, CHUNK) does exactly this loop and is what you would use in production. In an interview, write the loop, then mention it.

Three details interviewers check on a file copy: open both files in binary mode, so nothing is decoded or newline-translated; refuse to copy a file onto itself, which os.path.samefile detects and which would otherwise truncate the source before reading it; and write to a temporary file and os.replace it into place if a half-written destination would be harmful.

Parsing delimited messages from chunks

Network data arrives in chunks of whatever size the OS hands over. One recv can hold half a message, three messages, or the first two bytes of a three-byte delimiter. A parser keeps unconsumed bytes in a buffer, appends each chunk, and yields every complete message it can find.

from collections.abc import Iterable, Iterator


def split_messages(chunks: Iterable[bytes], delimiter: bytes = b"\n") -> Iterator[bytes]:
    if not delimiter:
        raise ValueError("delimiter must not be empty")
    buffer = bytearray()
    for chunk in chunks:
        searched = max(0, len(buffer) - len(delimiter) + 1)
        buffer += chunk
        start = 0
        while (end := buffer.find(delimiter, max(start, searched))) != -1:
            yield bytes(buffer[start:end])
            start = end + len(delimiter)
            searched = start
        del buffer[:start]
    if buffer:
        yield bytes(buffer)


print(list(split_messages([b"hel", b"lo\nwor", b"ld\n", b"tail"])))
# [b'hello', b'world', b'tail']
print(list(split_messages([b"a<E", b"N", b"D>b<END", b">"], b"<END>")))
# [b'a', b'b']
print(list(split_messages([b"\nx\n\ny\n"])))
# [b'', b'x', b'', b'y']

Each line of that function exists for a reason.

  • searched is where the next search starts. Bytes before it were already searched and contained no delimiter. Backing up len(delimiter) - 1 bytes catches a delimiter that straddles the old end of the buffer and the new chunk, like <E + N + D> above.
  • start moves forward through the buffer as messages are yielded, and del buffer[:start] compacts once per chunk. Deleting after every message would shift the remaining bytes each time, which is quadratic when one chunk holds thousands of messages.
  • Empty messages are real. Two delimiters in a row produce b"", and so does a delimiter at the very start. A trailing delimiter does not produce a final empty message, because the buffer is empty at the end.
  • It is a generator, so it pulls the next chunk only when the caller asks for a message that needs one, and the caller can stop early without the rest of the stream being read.
  • bytes(...) copies each message out of the buffer, so later edits to the buffer can't change what the caller holds.

The empty-delimiter check runs when iteration starts, not when split_messages is called, because a generator body doesn't run until the first next(). If the spec wants the error at call time, split it into a plain function that validates and returns an inner generator.

The quadratic trap

The common first draft looks shorter.

import time


def naive(chunks, delimiter=b"\n"):
    buffer = b""
    for chunk in chunks:
        buffer += chunk
        while delimiter in buffer:
            message, buffer = buffer.split(delimiter, 1)
            yield message
    if buffer:
        yield buffer


def linear(chunks, delimiter=b"\n"):
    buffer = bytearray()
    for chunk in chunks:
        searched = max(0, len(buffer) - len(delimiter) + 1)
        buffer += chunk
        start = 0
        while (end := buffer.find(delimiter, max(start, searched))) != -1:
            yield bytes(buffer[start:end])
            start = end + len(delimiter)
            searched = start
        del buffer[:start]
    if buffer:
        yield bytes(buffer)


def one_big_message():
    for _ in range(4000):
        yield b"x" * 1000
    yield b"\n"


def many_small_messages():
    yield b"msg\n" * 100_000


for name, source in [("one 4 MB message", one_big_message), ("100k messages, 1 chunk", many_small_messages)]:
    timings = {}
    for parser in (naive, linear):
        start = time.perf_counter()
        count = sum(1 for _ in parser(source()))
        timings[parser.__name__] = time.perf_counter() - start
    ratio = timings["naive"] / timings["linear"]
    print(f"{name}: naive is more than 5x slower: {ratio > 5}")
# one 4 MB message: naive is more than 5x slower: True
# 100k messages, 1 chunk: naive is more than 5x slower: True

The naive version is correct and has two quadratic paths. With one large message in many small chunks, buffer += chunk on immutable bytes copies the whole buffer for every chunk, and delimiter in buffer rescans it from the start. With many messages in one chunk, buffer.split(delimiter, 1) copies the rest of the buffer once per message. Both inputs are ordinary: a large JSON body arriving over a slow connection, or a log file read in 64 KiB blocks. The exact ratio depends on your machine, so the snippet only asserts a lower bound. On the laptop this guide was tested on, the naive version was over 300 times slower on the first input and 20 to 50 times slower on the second.

Bounding message size

A stream with no delimiter, by accident or on purpose, makes the buffer grow forever. Production parsers cap the size of one message and fail loudly when it is exceeded. Check after appending each chunk.

def split_bounded(chunks, delimiter=b"\n", max_message=1024):
    buffer = bytearray()
    for chunk in chunks:
        searched = max(0, len(buffer) - len(delimiter) + 1)
        buffer += chunk
        start = 0
        while (end := buffer.find(delimiter, max(start, searched))) != -1:
            if end - start > max_message:
                raise ValueError(f"message of {end - start} bytes exceeds {max_message}")
            yield bytes(buffer[start:end])
            start = end + len(delimiter)
            searched = start
        del buffer[:start]
        if len(buffer) > max_message:
            raise ValueError(f"incomplete message exceeds {max_message} bytes")
    if buffer:
        yield bytes(buffer)


def endless():
    while True:
        yield b"no delimiter here "


try:
    for message in split_bounded(endless(), max_message=100):
        pass
except ValueError as exc:
    print(exc)  # incomplete message exceeds 100 bytes

asyncio's StreamReader does the same thing with its limit argument, raising LimitOverrunError from readuntil when the separator isn't found within the limit.

Text and UTF-8 boundaries

A chunk boundary can fall inside a multi-byte UTF-8 character, so decoding each chunk with chunk.decode() raises UnicodeDecodeError on perfectly valid input. Two fixes work. Split into messages first and decode each complete message, which is safe for newline-delimited text because the byte 0x0A never appears inside a multi-byte UTF-8 sequence. Or decode incrementally with a codec that holds back an incomplete character until the next chunk.

import codecs
import json

data = json.dumps({"city": "Zürich", "temp": "−3"}, ensure_ascii=False).encode() + b"\n"
chunks = [data[i : i + 3] for i in range(0, len(data), 3)]

try:
    "".join(chunk.decode() for chunk in chunks)
except UnicodeDecodeError:
    print("per-chunk decode failed")  # per-chunk decode failed

decoder = codecs.getincrementaldecoder("utf-8")()
text = "".join(decoder.decode(chunk) for chunk in chunks) + decoder.decode(b"", final=True)
print(json.loads(text))  # {'city': 'Zürich', 'temp': '−3'}

For JSON Lines, split on b"\n" as bytes, then call json.loads on each line. json.loads accepts bytes directly and handles the decoding. Decide per spec whether a malformed line is skipped, counted or fatal, and wrap only the json.loads call in try, so one bad line doesn't end the stream.

Length-prefixed framing

When messages can contain any byte, there is no safe delimiter. Binary protocols prefix each message with its length instead, often as a 4-byte big-endian integer. The parser reads the header, then waits until the whole body is buffered.

import struct

HEADER = struct.Struct(">I")


def frames(chunks):
    buffer = bytearray()
    for chunk in chunks:
        buffer += chunk
        start = 0
        while len(buffer) - start >= HEADER.size:
            (length,) = HEADER.unpack_from(buffer, start)
            end = start + HEADER.size + length
            if len(buffer) < end:
                break
            yield bytes(buffer[start + HEADER.size : end])
            start = end
        del buffer[:start]
    if buffer:
        raise ValueError(f"stream ended inside a frame ({len(buffer)} bytes left)")


def encode(*messages: bytes) -> bytes:
    return b"".join(HEADER.pack(len(m)) + m for m in messages)


stream = encode(b"hello", b"", b"\n\x00binary\n")
print(list(frames(stream[i : i + 2] for i in range(0, len(stream), 2))))
# [b'hello', b'', b'\n\x00binary\n']

Unlike the delimited parser, leftover bytes at the end are an error: a truncated frame is corruption, not a final message. A real implementation also rejects a declared length above a maximum before waiting for it, so a corrupted header can't make the parser buffer four gigabytes.

The same patterns in asyncio

With asyncio streams, StreamReader.readuntil(separator) and readexactly(n) implement the delimited and length-prefixed loops for you, including the size limit. When chunks come from somewhere else, such as an HTTP client's iter_chunked or a queue, write the parser as an async generator with the same buffer logic.

import asyncio


async def network_chunks():
    for chunk in [b"GET /a\r", b"\nGET /b\r\nGE", b"T /c\r\n"]:
        await asyncio.sleep(0.001)
        yield chunk


async def split_async(chunks, delimiter: bytes):
    buffer = bytearray()
    async for chunk in chunks:
        searched = max(0, len(buffer) - len(delimiter) + 1)
        buffer += chunk
        start = 0
        while (end := buffer.find(delimiter, max(start, searched))) != -1:
            yield bytes(buffer[start:end])
            start = end + len(delimiter)
            searched = start
        del buffer[:start]
    if buffer:
        yield bytes(buffer)


async def main() -> None:
    print([m async for m in split_async(network_chunks(), b"\r\n")])
    reader = asyncio.StreamReader()
    reader.feed_data(b"one\r\ntw")
    reader.feed_data(b"o\r\n")
    reader.feed_eof()
    print(await reader.readuntil(b"\r\n"), await reader.readuntil(b"\r\n"))


asyncio.run(main())
# [b'GET /a', b'GET /b', b'GET /c']
# b'one\r\n' b'two\r\n'

readuntil keeps the separator in its result, unlike the generator. That is the sort of difference worth stating when you switch between them.

Follow-ups interviewers ask

  • Rechunking. Turn arbitrary chunks into fixed-size blocks, for example to upload in 5 MiB parts. Same buffer, but cut at size instead of at a delimiter, and flush the short final block.
  • Stop sequences. Stream text until a stop string appears, without emitting any part of the stop string even when it is split across chunks. Hold back the last len(stop) - 1 characters until you know they are not the start of it.
  • Checksums while streaming. Feed each chunk to hashlib.sha256().update as it passes through, so you hash a file without a second read.
  • Backpressure. A generator is pull-based and gets backpressure for free. In asyncio, a bounded queue between reader and parser gives the same property.
  • Resuming. Track the byte offset of the last complete message so a reconnect can resume from there instead of from the start.

Common mistakes

  • f.read() or readlines() on unbounded input.
  • Splitting each chunk independently. Messages and delimiters that straddle chunks are lost or broken.
  • Rescanning or copying the whole buffer per chunk or per message. Correct on small tests, quadratic on real input.
  • Dropping the final message when the stream doesn't end with a delimiter, or emitting a spurious empty one when it does.
  • Decoding each chunk separately. Multi-byte characters split across chunks raise errors.
  • No maximum message size. A missing delimiter becomes unbounded memory.

Practise it

Two open problems cover this. Delimited Stream Parser asks for the generator above with multi-byte delimiters, empty messages, laziness and a linear-time bound that the hidden tests measure (20 minutes). Chunked File Copy with Bounded Memory asks for the bounded-memory copy with the input checks that stop it from destroying data (15 minutes).

  1. 01Inference Log Summaryeasy

    Parse pipe-delimited inference logs, skip malformed lines, and report request counts, successes and average latency per model.

  2. 31Chunked File Copy with Bounded Memoryeasy

    Copy a file of any size in fixed-size chunks so memory stays flat, and refuse inputs that would destroy data.

  3. 36Delimited Stream Parsermedium

    Turn an iterator of arbitrary byte chunks into delimited messages, handling messages and multi-byte delimiters split across chunks.

The streaming, file I/O and memory topic pages collect related problems. The practical coding interview guide explains why "now the file is 200 GB" is such a common follow-up.

Frequently asked questions

How do I read a large file in chunks in Python?

Open it in binary mode and loop over iter(lambda: f.read(chunk_size), b""), which calls read until it returns an empty bytes object. Memory stays at about one chunk regardless of file size. shutil.copyfileobj runs the same loop when you only need to copy.

How do I split a byte stream into messages when messages are split across chunks?

Keep a bytearray buffer of unconsumed bytes. Append each chunk, search for the delimiter starting a little before the old end of the buffer, yield each complete message, and keep the remainder for the next chunk. After the stream ends, yield any leftover bytes as the final message.

Why is my stream parser slow on large inputs?

Usually it rescans or copies the whole buffer on every chunk or every message, for example with bytes concatenation, delimiter in buffer, or buffer.split(delimiter, 1) in a loop. Search from where the last search stopped and compact the buffer once per chunk to keep total work linear.

How do I handle a delimiter that is split across two chunks?

When searching after appending a new chunk, start len(delimiter) - 1 bytes before where the previous chunk ended. That catches a delimiter whose first bytes arrived in the previous chunk and the rest in the new one, without rescanning older bytes.

How do I decode UTF-8 text that arrives in chunks?

Do not decode each chunk on its own, because a multi-byte character can be split between chunks. Either split into complete messages first and decode each one, or use codecs.getincrementaldecoder("utf-8")(), which holds back an incomplete character until the next chunk.

What is the difference between delimited and length-prefixed framing?

Delimited framing ends each message with a marker such as a newline, which is simple but requires that the marker never appears inside a message. Length-prefixed framing sends each message's length first, usually as a fixed-size integer, so messages can contain any byte.