Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Understanding the Linux OOM
Killer in Containers.

Linux oom_badness() scores individual processes by RSS + swap, often killing a long-lived parent supervisor, database, or sidecar instead of the leaking child worker.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If latency budgets leave no room for synchronous retries, protect critical parent/supervisor processes with `oom_score_adj = -500..-1000`, isolate workers in dedicated cgroup v2 slices (`memory.high` + `memory.oom.group`), and enforce per-worker RSS limits.

TL;DR30-second simplified summary
▾

Core Mechanics: A Python ML inference pod on Kubernetes (16 GiB memory.max, Linux 5.15, cgroup v2) runs a Gunicorn master (preload_app=True, 1.5 GB CoW model), 8 workers, and a 2.2 GB Redis sidecar.

Visual & Structural Flow: Depicts Collateral Master/Redis Kill vs. Protected Supervisor + Worker Guard (Leaking Worker -> cgroup v2 (16G) -> OOM Killer -> Master / Redis); Per-Container Cgroups + oom_score_adj Protection (Gunicorn Master -> Worker Cgroup -> Redis Container -> OOM Events).

Trade-Offs & Production: Setting memory.oom.group = 1 on the whole pod kills every process (master, healthy workers, and Redis) on any single worker leak, causing a full pod outage. Isolate blast radius inside cgroup v2 containers: Protect Supervisor & Sidecars: Set oom_score_adj = -500 on Gunicorn master and the Redis sidecar (separate container in K8s.

Failure Modes & Application: Cgroup v2 memory isolation is critical in multi-process and ML serving workloads: Python / Gunicorn ML Inference: Preserves CoW model weights and isolates runaway payload allocations.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why Container OOM Killer Behavior Matters.

Why this matters: The mechanism: understand how Why Container OOM Killer Behavior Matters works from first principles.

Think of Why Container OOM Killer Behavior Matters as the intuition layer for Understanding the Linux OOM Killer in Containers: The mechanism: understand how Why Container OOM Killer Behavior Matters works from first principles.

A Python ML inference pod on Kubernetes (16 GiB memory.max, Linux 5.15, cgroup v2) runs a Gunicorn master (preload_app=True, 1.5 GB CoW model), 8 workers, and a 2.2 GB Redis sidecar. When one worker leaks 9 GB on an oversized payload, the Linux OOM killer scores and SIGKILLs the Redis sidecar or Gunicorn master—or triggers a pod-wide exit 137!

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Real-World Impact of Unprotected OOM Scoring.

Why this matters: The problem: see what breaks without Real-World Impact of Unprotected OOM Scoring under real concurrency or scale.

When cgroup v2 memory.max is breached without per-process protection:

  1. Collateral Sidecar Kill: The OOM killer picks the highest oom_score (rss + swap + oom_score_adj), often killing the 2.2 GB Redis sidecar or Gunicorn master instead of the leaking worker.
  2. Copy-on-Write Explosion: Mutating shared tensors/caches in forked workers breaks the 1.5 GB CoW pages, multiplying RSS by 8x.
  3. Slow-Burn Thrashing: Without memory.high throttling, page-cache eviction stalls inference p99 before OOM even fires.
cgroup v2 OOM Kill Selection

Collateral Master/Redis Kill vs. Protected Supervisor + Worker Guard

Leaking Workercgroup v2 (16G)OOM KillerMaster / Redis1. Oversized payload -> +9 GB RSS2. memory.max (16G) exceeded3. Naive: kills Redis/Master (highRSS)4. Fixed: Masteroom_score_adj=-500 -> kills worker

Negative oom_score_adj on the supervisor and sidecar forces the OOM killer to target only the runaway worker.

Engineering Decision Framework
Problem
How to implement Understanding the Linux OOM Killer in Containers without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
If latency budgets leave no room for synchronous retries, protect critical parent/supervisor processes with oom_score_adj = -500..-1000, isolate workers in dedicated cgroup v2 slices (memory.high + memory.oom.group), and enforce per-worker RSS limits.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Understanding the Linux OOM Killer in Containers experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive Solution (and Why It Breaks).

Why this matters: The problem: see what breaks without Naive Solution under real concurrency or scale.

Think of Naive Solution (and Why It Breaks) as the intuition layer for Understanding the Linux OOM Killer in Containers: The problem: see what breaks without Naive Solution under real concurrency or scale.

Setting memory.oom.group = 1 on the whole pod kills every process (master, healthy workers, and Redis) on any single worker leak, causing a full pod outage. Setting oom_score_adj = -1000 on workers makes them unkillable inside the cgroup, forcing the kernel to kill the master or crash the pod.

Design Trade-Off

Naive Solution (and Why It Breaks)

Before · Unbounded Coupling
  • No backpressure on spikes
  • Implicit shared state
  • Cascading tail latency
After · Bounded & Observable
  • Explicit capacity budgets
  • Isolated failure domains
  • Predictable p99 latency
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise Solution: `oom_score_adj` Hierarchy + `RLIMIT_AS` + Worker Recycling.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Isolate blast radius inside cgroup v2 containers:

  • Protect Supervisor & Sidecars: Set oom_score_adj = -500 on Gunicorn master and the Redis sidecar (separate container in K8s with its own resources.limits.memory), while workers keep oom_score_adj >= 0.
  • Pre-OOM Guardrails: Configure memory.high (~85% of memory.max) for kernel memory-reclaim pressure, enforce Gunicorn --max-requests + RLIMIT_AS / gc.freeze() (to preserve the 1.5 GB CoW model), and validate request payload sizes at ingress.
  • Separate Pod Containers: Move Redis into its own Kubernetes container cgroup so a Python worker leak can never trigger an OOM inside Redis's cgroup.
cgroup v2 Memory Isolation

Per-Container Cgroups + oom_score_adj Protection

Gunicorn Masteroom_score_adj: -500…Worker Cgroupmemory.high: 85% |…Redis ContainerOwn cgroup limit: 3…OOM EventsWatch memory.events…Isolated cgroups

1.Separate Cgroups: Each K8s container gets its own cgroup v2 memory.max.

2.CoW Preservation: Call gc.freeze() before fork() so Python refcounts don't dirty 1.5 GB pages.

3.Score Hierarchy: Master -500, Workers +100 -> only leaking worker dies.

4.Telemetry: Alert on cgroup memory.events (high, oom, oom_kill).

Combining separate container cgroups, gc.freeze(), and oom_score_adj prevents collateral OOM kills.

def oom_score(rss_gb: float, limit_gb: float, adj: int) -> int:
    base = int((rss_gb / limit_gb) * 1000)
    return max(0, min(1000, base + adj))

print("Master:", oom_score(1.5, 16.0, 0))
print("Worker (with +300 adj):", oom_score(4.0, 16.0, 300))

import gc, os, signal

preload_app = True
workers = 8
MAX_WORKER_RSS_BYTES = 1800 * 1024 * 1024

def when_ready(server):
    gc.freeze()

def post_fork(server, worker):
    with open("/proc/self/oom_score_adj", "w") as f:
        f.write("300")

def post_request(worker, req, environ, resp):
    with open("/proc/self/statm") as f:
        rss_pages = int(f.read().split()[1])
    if rss_pages * os.sysconf("SC_PAGE_SIZE") > MAX_WORKER_RSS_BYTES:
        os.kill(os.getpid(), signal.SIGTERM)
resources:
  requests:
    memory: "4Gi"
    cpu: "2"
  limits:
    memory: "4Gi"
    cpu: "2"
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Container OOM Isolation Applies in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Cgroup v2 memory isolation is critical in multi-process and ML serving workloads:

  • Python / Gunicorn ML Inference: Preserves CoW model weights and isolates runaway payload allocations.
  • Sidecar Architectures (Envoy / Redis / FluentBit): Separate container cgroup limits prevent app leaks from killing telemetry or proxy sidecars.
  • Kubernetes QoS Classes: Guaranteed QoS (requests == limits) prevents node-level kubelet eviction.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does calling `gc.freeze()` in a Gunicorn master before `fork()` reduce memory usage for a 1.5 GB preloaded Python model?

Recommended Learning Flow