← All posts

Memory Guards in Python Workers: Fix or Smell?

A worker that runs out of memory in a container does not raise an exception. The kernel sends SIGKILL, which no handler can catch, and every task sharing that process dies with it. The logs end mid-line and the only clue is exit code 137. That is how our first memory incident looked on a document-processing platform I worked on: container memory climbed for hours, the worker vanished, and nothing named the file or the step responsible.

The obvious response is a memory guard: watch usage and fail cleanly before the kernel steps in. We built one and it helped. It also raises a fair question: is a memory guard good engineering, or a smell that hides a design that allocates too much? To answer with measurements, I built a small Docker lab with a 512 MiB limit and ran each failure mode, trap and fix. Every number below comes from those runs, on invented workloads, except one reading from a Mac that is marked as such.

In short

  • Inside a container, the usual ways of reading memory lie: psutil reported the machine's 16.7 GB instead of the 512 MiB limit, and ru_maxrss stayed at its 311 MiB peak after the memory was freed.
  • A guard that reads the cgroup's memory.current turned an uncatchable SIGKILL into a named, attributable failure at 85 per cent of the limit, with the process still alive and able to report it.
  • The kernel's own soft limit, memory.high, does not kill: it throttles. In the lab, one 20 MiB step went from milliseconds to 88 seconds, and a pressure reading during the stall showed tasks stalled 64 per cent of the time.
  • A guard is a smell when it is the only control. As the fifth of six layers, after input admission, memory-aware concurrency, process isolation and recycling, it is cheap insurance.

How a container runs out of memory

On Linux, container memory is enforced by the cgroup v2 memory controller. The files that matter are in the container's cgroup directory, usually /sys/fs/cgroup from the inside:

FileWhat the kernel documentation saysWhat it means for a worker
memory.max"If a cgroup's memory usage reaches this limit and can't be reduced, the OOM killer is invoked in the cgroup."The hard wall. Crossing it means SIGKILL.
memory.high"The processes of the cgroup are throttled and put under heavy reclaim pressure. Going over the high limit never invokes the OOM killer."A soft limit that slows the worker down instead of killing it.
memory.currentThe memory currently charged to the cgroup; tracked usage includes "page cache and anonymous memory"The number the kernel compares with the limit. It includes page cache, which the kernel reclaims before it kills, so a guard should subtract inactive_file from memory.stat.
memory.eventsCounters including high, max, oom and oom_kill, "the number of processes belonging to this cgroup killed by any kind of OOM killer"Evidence after the fact, worth exporting as metrics.
memory.pressurePressure stall information: "the share of time in which at least some tasks are stalled"The earliest signal that memory is hurting performance.
A vertical memory scale for a 512 MiB container: memory.max at the top kills, the guard threshold at 85 per cent fails by name, memory.high at 75 per cent throttles; memory.current, made of anonymous memory and page cache, rises from the bottom 512 MiB memory.max (512 MiB): the kernel OOM-kills a process 435 MiB guard threshold (85%): fail by name 384 MiB memory.high (75%): throttle and reclaim, never kill memory.current anon + page cache memory charged to the cgroup One 512 MiB container in this post's lab. The guard sits between the throttle and the kill.
Figure 1. Three thresholds on one container, and what each does.

Orchestrators add their own layer. Kubernetes states the asymmetry: "cpu limits are enforced by CPU throttling", while "memory limits are enforced by the kernel with out of memory (OOM) kills". A CPU-hungry worker gets slower; a memory-hungry one gets killed. Google Cloud Run adds a subtlety for anyone writing temporary files: "files written to the local file system count towards the available memory".

The lab

Every experiment runs in a python:3.13-slim container started with --memory=512m --memory-swap=512m --cpus=2, so there is no swap. A sampling thread reads the process's resident memory and the cgroup's memory.current every 50 ms. The workloads are invented: byte arrays touched page by page, many small objects, a synthetic spreadsheet. Each run records the exit code and Docker's OOMKilled flag. These are single runs on one machine, so read them as demonstrations of mechanisms, not benchmarks.

Trap one: the limit you read is not your limit

A guard first needs the limit, and the familiar APIs give the wrong answer inside a container:

QuestionFamiliar API and its answer in the labThe truth
How much memory may I use?psutil.virtual_memory().total: 16.7 GB, the Docker VM's RAMmemory.max: 512 MiB
How many CPUs may I use?os.cpu_count(): 8cpu.max: 200000 100000, two CPUs

A worker that sizes itself from the familiar API plans for about 31 times the memory it has. One of our early guards took its threshold from a ceiling in configuration, far above the container's real limit, so the kernel won every race. Read the cgroup first and fall back to configuration only where no cgroup exists. The same applies to concurrency: Celery's worker guide warns that inside a container with a CPU limit, "the host CPU count overstates what the worker may use".

Trap two: the peak is not the present

A guard also needs current usage. Python's resource.getrusage() looks convenient, but its ru_maxrss is the process's lifetime peak, and its unit depends on the operating system: the Linux man page says "maximum resident set size used (in KiB)", while the macOS one says "(in bytes)". On my Mac, a 200 MiB allocation read as 224,133,120.

Two groups of bars. Latch test: current resident memory 311 MiB after allocating and 11 MiB after freeing, while ru_maxrss stays at 311 MiB in both. Fragmentation test: 328 MiB after allocating, still 327 MiB after freeing 63 of every 64 objects, and 21 MiB after malloc_trim Two measurements that mislead a guard (MiB, measured) Latch test current RSS after alloc 311 ru_maxrss after alloc 311 current RSS after free 11 ru_maxrss after free 311 Fragmentation test RSS after alloc 328 after freeing 63 of 64 327 after malloc_trim(0) 21
Figure 2. A peak reading latches; freed memory need not leave the process.

In the latch test, a 300 MiB buffer was allocated and freed. Current resident memory, read from /proc/self/statm, fell from 311 MiB to 11 MiB; ru_maxrss stayed at 311 MiB. A guard built on the peak fires once and then fires on every later task until the process restarts. We shipped that bug once and caught it on staging.

What a guard buys

With the right inputs, the guard is small. This version reads the cgroup limit and the container's working set (charged memory minus inactive page cache, as the kubelet computes it before evicting a pod). It races a watcher against the work, and whichever finishes first decides the outcome:

"""A last-line memory guard for async workers: read the real limit, watch current usage, fail by name."""
import asyncio
import logging
import os
from pathlib import Path

CGROUP = Path("/sys/fs/cgroup")
log = logging.getLogger(__name__)


def container_limit() -> int | None:
    """The cgroup v2 memory limit in bytes; None when unlimited, on cgroup v1, or outside Linux."""
    try:
        value = (CGROUP / "memory.max").read_text().strip()
    except OSError:
        return None
    return None if value == "max" else int(value)


def container_usage() -> int:
    """The container's working set: memory.current minus inactive page cache, which reclaim frees before a kill.

    Without cgroup v2 files it falls back to this process's resident memory (Linux only).
    """
    try:
        current = int((CGROUP / "memory.current").read_text())
        stat = dict(line.split() for line in (CGROUP / "memory.stat").read_text().splitlines())
        return current - int(stat.get("inactive_file", 0))
    except OSError:
        with open("/proc/self/statm") as f:  # current resident pages, never the lifetime peak
            return int(f.read().split()[1]) * os.sysconf("SC_PAGE_SIZE")


class MemoryPressureError(RuntimeError):
    """Raised instead of waiting for the kernel's SIGKILL."""


async def run_guarded(work, *, fraction=0.85, every=0.1, limit=None):
    """Await `work`, but stop waiting if usage passes `fraction` of the limit first.

    A finished result wins a tie: its side effects are done, and failing it would waste them.
    The guard stops the waiting, not the work: memory held by a thread is freed only when it ends.
    The watcher shares the event loop, so blocking code must run in an executor to be watched at all.
    """
    limit = container_limit() if limit is None else limit
    if limit is None:
        log.warning("no cgroup v2 memory limit found: running unguarded")
        return await work
    threshold = int(limit * fraction)

    async def watch():
        while True:
            used = container_usage()
            if used > threshold:
                raise MemoryPressureError(f"{used >> 20} MiB used, threshold {threshold >> 20} MiB of {limit >> 20} MiB")
            await asyncio.sleep(every)

    task, watcher = asyncio.ensure_future(work), asyncio.ensure_future(watch())
    try:
        done, _ = await asyncio.wait({task, watcher}, return_when=asyncio.FIRST_COMPLETED)
        if task in done:                  # finished work wins, even if the watcher also fired
            return task.result()
        watcher.result()                  # raises MemoryPressureError
    finally:                              # on every exit, including our own cancellation, leave nothing running
        for t in (task, watcher):
            t.cancel()
        await asyncio.gather(task, watcher, return_exceptions=True)

Three choices in it matter. A completed result wins a tie: if the work and the watcher finish in the same wake-up, the work's side effects are already committed, and failing it would waste them. The guard stops the waiting, not the work: Python cannot kill a thread, so memory held by blocking code in an executor is freed only when that code ends. And the watcher needs the event loop, so blocking code must run in an executor to be watched at all. Whatever ends the wait, including the caller's own cancellation, both tasks are cancelled, so nothing keeps running behind the guard.

Then the same growing task, with no guard and with a guard check after every 20 MiB step:

Two lines of container memory over one second. Without a guard, memory climbs in steps to 508 MiB and the process is killed with exit 137. With the guard, memory climbs past 420 MiB, the check fires at 448 MiB and the process stops with a named error and exit code 3 Container memory while a task grows in 20 MiB steps (MiB, measured) 0 128 256 384 512 0 s 0.25 s 0.5 s 0.75 s 1 s limit 85% no guard: SIGKILL, exit 137 guard: MemoryPressureError, exit 3
Figure 3. Same task, two endings: a kill, or a named failure.
RunHow it endedExit code, OOMKilledWhat the logs could say
No guardKilled by the kernel at the limit137, trueNothing: the process had no chance to write
Guard at 85 per centMemoryPressureError at 448 MiB3 (set by the program), falseUsage, threshold, limit and which task was running

The async version above, polling every 0.1 s, fired at 458, 459 and 479 MiB in three runs against a 435 MiB threshold. In each the process carried on and reported its usage afterwards. A guard overshoots by roughly the allocation rate times the polling interval, so the threshold needs headroom for the fastest allocation you expect. A single allocation larger than the headroom cannot be caught: no polling guard sees it coming.

Why memory does not come back

Long-running workers often show a staircase: memory rises with each task and barely falls. Allocators are part of the reason. CPython's pymalloc serves objects of 512 bytes or less from arenas of 1 MiB on 64-bit platforms, and an arena is returned to the system only when every object in it is free. Larger objects go to the C library's malloc. glibc serves big blocks by mmap (above 128 KiB by default) and returns them as soon as they are freed. It also trims free space at the top of the heap, but free chunks inside the heap stay resident for reuse.

The fragmentation test allocated about 310 MiB of 4 KiB objects, kept one in every 64, and freed the rest. Resident memory barely moved, from 328 MiB to 327 MiB. The survivors were spread through the heap, so almost none of the freed space sat at its top, and glibc kept the rest for reuse. One call to malloc_trim(0) brought it down to 21 MiB in 9 milliseconds. The man page says why: "Since glibc 2.8 this function frees memory in all arenas and in all chunks with whole free pages."

That is the best case. In production, the curve that killed our worker was a steady climb over hours, not a sawtooth per task, and calling malloc_trim after every task did not stop it. Native libraries for PDF parsing and machine learning keep long-lived allocations of their own, and a page holding even one live object cannot be returned. Trimming lowers the slope; it does not set a ceiling.

glibc also gives threads their own arenas, tunable with MALLOC_ARENA_MAX. My two tests disagree. In the first, where live data grew with the thread count, eight threads with default arenas were killed, while MALLOC_ARENA_MAX=2 survived at 472 MiB, close to the limit. In the second, with fixed live data, capping arenas changed resident memory by under 1 MiB. One run of each cannot settle it: measure the setting on your own workload before relying on it.

The reliable way to return everything is to end the process. Celery's worker_max_memory_per_child and worker_max_tasks_per_child, Gunicorn's max_requests and Python's own ProcessPoolExecutor(max_tasks_per_child=...) all recycle workers for this reason. Gunicorn's documentation calls it "a simple method to help limit the damage of memory leaks".

The kernel's alternative: throttle instead of kill

If killing is the problem, the kernel can slow the worker down instead. That is what memory.high does. I set it to 75 per cent of the limit (384 MiB) and ran the same growing task.

MeasurementBelow memory.highAbove memory.high
Time for one 20 MiB step15 to 42 ms88 seconds, for the step from 380 to 400 MiB
Throttling events (high in memory.events)07,845 by the end of that step
Memory pressure, some avg100.0064.40 per cent of time stalled, read from the host during an earlier run of the same test
OOM kills00

The worker never died. It stalled: the sampling thread stopped reporting, and even docker exec into the container hung, because everything in the cgroup is throttled with it. Anonymous memory without swap has nowhere to go, so reclaim cannot help much. For a task that eventually fits, memory.high trades a crash for a long pause. For one that does not, it turns a quick, visible failure into a slow, invisible one. Either way something must detect it: pressure metrics (systemd-oomd uses them to decide what to kill) or heartbeats.

It combines badly with a guard if the order is wrong. With memory.high below the guard's threshold, as in the ladder above, the worker stalls before the guard sees the usage it is waiting for. Put the guard's threshold below memory.high, or leave memory.high unset and let the guard and the hard limit do the work.

Both signals can be read from inside the container and exported as metrics. This reads memory.events and memory.pressure into plain numbers. In the lab, a child killed for allocating 576 MiB moved oom_kill from 0 to 1, and in the stall above high reached 7,845:

"""Read cgroup v2 memory.events and memory.pressure as plain numbers, ready to export as metrics."""
from pathlib import Path

CGROUP = Path("/sys/fs/cgroup")


def read_events(cgroup: Path = CGROUP) -> dict[str, int]:
    """Counters from memory.events (low, high, max, oom, oom_kill, ...). They only ever increase."""
    lines = (cgroup / "memory.events").read_text().splitlines()
    return {key: int(value) for key, value in (line.split() for line in lines)}


def read_pressure(cgroup: Path = CGROUP) -> dict[str, float]:
    """avg10 for 'some' and 'full' from memory.pressure: the percentage of the last 10 s spent stalled."""
    out: dict[str, float] = {}
    for line in (cgroup / "memory.pressure").read_text().splitlines():
        kind, *fields = line.split()  # e.g. "some avg10=0.00 avg60=0.00 avg300=0.00 total=0"
        out[kind] = float(dict(f.split("=") for f in fields)["avg10"])
    return out

Alert on any increase in oom_kill or high, and on some avg10 staying above a few per cent. The kernel's PSI documentation defines the fields.

Heartbeats: noticing a dead or stuck worker

Workflow engines detect a lost worker through timeouts. In Temporal, "a Heartbeat Timeout is the maximum time between Activity Heartbeats". A long activity calls a heartbeat function periodically, and the server marks the attempt failed when the beats stop. Without them, a dead worker is noticed only when the whole start-to-close timeout expires. One long model call in our system sent none: a worker killed mid-call was discovered only when its long overall timeout ran out, and every later step of the job waited behind it. Adding heartbeats and a short heartbeat timeout cut that wait to minutes. The guard and the heartbeat complement each other: the guard names a failure it sees coming, and the heartbeat catches the ones it does not.

Isolation: let one process die alone

No in-process mechanism survives some failures. A malformed PDF can drive a native parser into std::terminate, which aborts the process before any Python code runs again, and a single huge allocation can cross the limit between two polls. Only another process survives a process dying, so risky steps can run in a child.

A worker process asks a single-threaded fork server for a child; the child parses one file and returns plain data. Three outcomes: a result; a signal or overrun, treated as a permanent verdict on the file; a host SIGKILL from the OOM killer, treated as a retryable fault Worker process threads, event loop, heartbeats Fork server single-threaded, forks children Child parses one file, returns plain data result: done signal / overrun: bad file, permanent host SIGKILL (OOM): fault, retryable Measured: a child that asked for more than the container had was killed (exit -9); the parent carried on.
Figure 4. A child process turns a fatal crash into a verdict the parent can classify.

In the lab, a child asked for 576 MiB in the 512 MiB container. The kernel killed the child (exit code -9 as seen by the parent) and the parent carried on. Two details matter:

  • Start children from a fork server, not by forking a threaded worker. fork() copies only the calling thread but every lock in whatever state it was in, so a child can block forever on a lock nobody will release. Python 3.14 changed the default start method on Linux and other POSIX platforms (macOS already used spawn) "from fork to forkserver", for this reason.
  • Classify by outcome. A child that died on a signal or overran its time bound says something about the input and can be a permanent verdict. A child killed by the host's OOM killer says nothing about the input, because an unrelated process may have filled the container. Treating that as "bad file" would permanently reject good documents.

A trap for monitoring: Docker marked the container OOMKilled: true although it exited normally, because the cgroup recorded an OOM kill of the child. Alerting on that flag alone would page someone for a run that succeeded.

Admission: do not allocate what you will refuse

The cheapest memory is memory never allocated. One spreadsheet in the lab was 12.7 KB on disk: 300 rows of five numbers, plus one empty but formatted cell in the last column, XFD. Its declared box is 300 rows by 16,384 columns, 4,915,200 cells. Loading it took 27 MiB; walking every cell of that box, as code that loops over max_row and max_column does, was killed at the 512 MiB limit. Reading only the stored values, in openpyxl's read-only mode, also took 27 MiB and 0.27 seconds.

The defence is a check before the load: read each sheet's declared size from the file's XML and refuse anything past a budget.

"""Refuse a spreadsheet before loading it: read each sheet's declared box from the XML, not from a load."""
import re
import zipfile

MAX_CELLS = 2_000_000
DIMENSION = re.compile(r'<(?:\w+:)?dimension ref="([A-Z]+)(\d+)(?::([A-Z]+)(\d+))?"')


def column_number(letters: str) -> int:
    n = 0
    for ch in letters:
        n = n * 26 + ord(ch) - 64
    return n


def declared_boxes(path: str) -> dict[str, int | None]:
    """Cells in each sheet's <dimension ref="A1:XFD300">, from the first 4 KiB of its XML; None if not declared."""
    boxes = {}
    with zipfile.ZipFile(path) as z:
        for name in z.namelist():
            if not (name.startswith("xl/worksheets/") and name.endswith(".xml")):
                continue
            with z.open(name) as f:
                head = f.read(4096).decode("utf-8", "replace")
            m = DIMENSION.search(head)
            if m is None:
                boxes[name] = None
                continue
            c1, r1, c2, r2 = m.group(1), int(m.group(2)), m.group(3) or m.group(1), int(m.group(4) or m.group(2))
            boxes[name] = (r2 - r1 + 1) * (column_number(c2) - column_number(c1) + 1)
    return boxes


def admit(path: str) -> list[str]:
    """Raise for a declared box past the budget; return the sheets that declare none, to be bounded after loading."""
    unknown = []
    for sheet, cells in declared_boxes(path).items():
        if cells is None:
            unknown.append(sheet)
        elif cells > MAX_CELLS:
            raise ValueError(f"{sheet}: declared box of {cells:,} cells exceeds {MAX_CELLS:,}")
    return unknown

It refused the 4.9 million-cell sheet and admitted the normal one. But the declared box is written by whatever produced the file and can be missing or wrong. A copy of the normal file with its dimension element removed was admitted, because it declared no size, and the check returned it in its list of sheets to bound after the load. So this is a cheap first filter, not a proof: keep a bound after the load as a backstop, and read only the cells that hold values.

So, is a memory guard a smell?

First, what each control catches and what it costs:

ControlCatchesMissesCost
Kernel OOM kill (memory.max)Everything, in the endNothing, but it names no cause and kills every task in the processNone to set up, a lot to diagnose
memory.highSlow growth, by throttlingDoes not end a task that will never fitStalls that look like hangs, up to 88 s per step in the lab
In-process guardGradual growth, with a named failureOne large allocation between polls, native aborts, memory held by threadsPolling overhead and headroom below the limit
Child processNative crashes and runaway allocations in one stepPressure from the parent itselfProcess start-up and copying data across the boundary
RecyclingSlow leaks and fragmentationA single task that is too bigRestarts and cold caches

Then the arguments on each side:

A guard is a smell whenA guard is good engineering when
It is the only control, compensating for unbounded inputs or unbounded concurrencyIt is a late layer among several, catching what prevention missed
It fires routinely, so failures become normal and nobody fixes the causeIt fires rarely, and each firing is investigated like an incident
It reads the wrong number: a peak, the host's memory, or a configured ceilingIt reads the working set against memory.max, with headroom for its own polling
Its failures are retried immediately onto the same pressured workerIts failures are classified, and retried later or elsewhere, if at all
It hides which task caused the pressureIt records usage, threshold, limit and the running task, which SIGKILL never can

My conclusion: the smell is a system where the guard does the main work, not the guard itself. Prevention belongs earlier:

Six stacked layers: refuse oversized input; bound concurrency by memory; isolate risky native code; give memory back; watch and fail by name; let the platform restart, detected by heartbeats. The guard is the fifth 1. Refuse oversized input check the declared size before loading 2. Bound concurrency by memory tasks x peak per task fits the limit 3. Isolate risky native code a child process dies alone 4. Give memory back malloc_trim, recycle processes, jobs 5. Watch and fail by name the guard: last line, not first 6. Let the platform restart detected fast by heartbeats Prevention first, containment next, the guard near the end. Each layer catches what the one above misses.
Figure 5. Six layers of defence, from prevention to recovery.

Retrying a guard failure is a judgement call. When the guard fires, the memory is not free yet, because a thread may still hold it. With few worker instances, an immediate retry probably lands on the same worker and pushes it into the real SIGKILL, taking every co-running task with it. We made the failure non-retryable and accepted the cost: a document can fail because of pressure its own size did not cause, and has to be resubmitted. If that cost is too high, use a retry policy with a long first interval and few attempts, so transient pressure clears while structural pressure still ends in a failure. Also, when a retry reattaches to a previous attempt that already reported a permanent failure, raise that failure instead of running the job again.

Platforms are moving the same way. Temporal's resource-based tuner hands out task slots "based on real-time CPU and memory usage" and accounts for container limits. Its tuning guide also says auto-tuning "may sometimes exceed your requested system limits for CPU and memory", and recommends fixed slots for tasks with "variable, or very high, per-task resource needs". Even a good scheduler needs a last line behind it. Sizing concurrency by memory is the subject of the next post.

A checklist

  • Read limits from the cgroup (memory.max, cpu.max), never from the host's totals.
  • Measure current usage as memory.current minus inactive page cache, or /proc/self/statm for one process, never the lifetime peak.
  • Refuse oversized inputs before loading them, using sizes declared in the file.
  • Size concurrency so that tasks times peak memory per task fits the limit with headroom.
  • Run native parsers that can crash in a child process started from a fork server, and classify how it ended.
  • Recycle long-lived workers, or run heavy work as run-to-completion jobs.
  • Add a guard behind the other layers: a threshold below memory.high with headroom for its polling, a named error, the task recorded, no immediate retry.
  • Export memory.events and memory.pressure, set heartbeat timeouts, and do not alert on OOMKilled alone.

Sources