DEV Community

Yu
Yu

Posted on

Preventing OOM Crashes in Python HTTP Workers with Streaming Byte Caps

When running high-concurrency Python HTTP workers against arbitrary third-party endpoints, one of the easiest ways to crash a container or VM is calling response.text without a size bound.

A single misconfigured endpoint serving a 500 MB log file or an infinite chunked response will spike memory usage and trigger the Linux OOM killer across your entire worker pool.

The Pattern That Causes Silent OOMs

Many teams write defensive slicing like this:

resp = requests.get(url, timeout=10)
snippet = resp.text[:100_000]  # Too late! Full body is already in RAM.
Enter fullscreen mode Exit fullscreen mode

Because requests.get defaults to stream=False, the entire response payload is downloaded and decoded into memory before [:100_000] ever runs.

Bounding Memory at the Socket Layer

Switching to stream=True with an explicit byte budget caps peak RAM per thread deterministically:

import requests

def fetch_capped(session: requests.Session, url: str, max_bytes: int = 262_144) -> str:
    chunks = []
    total = 0
    with session.get(url, timeout=(5, 10), stream=True) as resp:
        for chunk in resp.iter_content(chunk_size=16_384):
            if not chunk:
                continue
            chunks.append(chunk)
            total += len(chunk)
            if total >= max_bytes:
                break
    return b"".join(chunks).decode("utf-8", errors="ignore")
Enter fullscreen mode Exit fullscreen mode

Three Subtle Details That Matter in Production

  1. Always use iter_content(), not raw.read(): iter_content() transparently handles gzip and deflate decoding, whereas raw.read() returns raw compressed bytes unless decode_content=True is explicitly set.
  2. Use a context manager (with session.get(...)): Breaking out of the loop early without closing the response leaks TCP sockets and eventually exhausts file descriptors.
  3. Separate connect and read timeouts: Passing timeout=(5, 10) ensures dead hosts fail fast while slow-drip responses cannot hold worker threads indefinitely.

Applying a strict 256 KB streaming ceiling across a 64-thread worker pool keeps worst-case payload RAM under ~16 MB total, eliminating surprise OOM kills without sacrificing throughput.

Top comments (0)