Quick Overview
To fix Kubernetes OOMKilled (Exit Code 137) errors using cgroup v2, enable unified hierarchy on node operating systems and activate Kubelet Memory QoS. cgroup v2 replaces blunt hard memory caps (memory.max) with granular controls (memory.min, memory.high), allowing kernel page cache reclaiming and memory throttling before the kernel OOM killer terminates container processes.
Real-World Engineering Motivation: The cgroup v1 Bottleneck
For nearly a decade, Kubernetes resource isolation relied on cgroup v1 (control groups version 1). Under cgroup v1, memory management suffers from a fundamental architectural flaw: the lack of proportional control and memory pressure feedback.
In cgroup v1, the Linux kernel manages resource controllers in isolated, multi-hierarchy trees (/sys/fs/cgroup/memory, /sys/fs/cgroup/cpu, /sys/fs/cgroup/blkio). Because the memory controller has no direct communication with the block I/O controller, dirty page cache writebacks cannot be effectively throttled based on disk throughput constraints.
cgroup v1 Split Hierarchy (Legacy Problem)
┌─────────────────────────────────────────────────────────┐
│ Root cgroup │
└──────────────┬───────────────────────────┬──────────────┘
│ │
┌────────────▼───────────┐ ┌────────────▼───────────┐
│ /sys/fs/cgroup/cpu │ │ /sys/fs/cgroup/memory │
└────────────┬───────────┘ └────────────┬───────────┘
│ │
┌────────────▼───────────┐ ┌────────────▼───────────┐
│ CPU Accounting │ │ memory.limit_in_bytes │ (Hard Cap Only)
└────────────────────────┘ └────────────────────────┘
When a containerized process (such as a Java JVM, Node.js event loop, or Go runtime) approaches its configured limits.memory, the cgroup v1 memory controller enforcing memory.limit_in_bytes exhibits binary, destructive behavior:
- Aggressive Page Cache Eviction: The kernel attempts to reclaim memory by synchronously flushing or discarding file-backed page caches. If disk I/O stalls, allocation stalls occur, driving p99 and p99.9 latencies into multi-second territory.
- Immediate OOM Killer Activation: If the process allocates anonymous memory (heap/stack) faster than the kernel can clear page caches—or if the total resident set size (RSS) plus dirty pages hits
memory.limit_in_bytes—the Linux Out-Of-Memory (OOM) killer fires instantly. The kernel sendsSIGKILL(Exit Code 137) directly to the root process inside the container.
Cloud Waste and Over-Provisioning Escalation
In large-scale production clusters running cgroup v1, application teams frequently encounter transient memory spikes caused by peak traffic, garbage collection routines, or heavy disk read operations. Because an OOMKilled event terminates the container completely, engineering teams naturally react by over-provisioning memory limits by 200% to 500%.
This strategy creates severe financial inefficiencies:
- Inflated Cluster Footprints: Kubernetes bases scheduling decisions on resource
requests, but nodes must maintain capacity for potential memory spikes up tolimits. Over-provisioned limits prevent dense pod bin-packing. - Lack of Pressure Feedback: Under cgroup v1, processes have no visibility into memory pressure. They run at full speed until they hit the hard limit wall and crash.
- No Dynamic Reclamation Protection: Important shared libraries and execution pages are evicted on equal standing with volatile buffer caches, causing heavy performance degradation prior to container termination.
Enter cgroup v2 & Memory QoS
Control groups v2 (cgroup v2) re-architects Linux resource management into a unified hierarchy. All controllers operate on a single cgroup tree. Memory allocation is governed by a continuum of protective boundaries rather than a single hard cap:
memory.min: Guaranteed memory boundary. The kernel will never reclaim memory below this threshold under any system pressure.memory.low: Best-effort protection boundary. Memory below this limit is reclaimed only if no unprotected cgroup memory can be reclaimed.memory.high: The soft throttle boundary. When usage exceedsmemory.high, the kernel forces the allocating process into synchronous direct reclaim and introduces memory allocation throttling, deliberately slowing down the process without killing it.memory.max: The absolute hard limit ceiling. If usage exceedsmemory.maxafter direct reclaim and throttling fail, the kernel OOM killer fires as a absolute last resort.- Pressure Stall Information (PSI): Provides real-time metrics (
someandfullpressure stall percentages) indicating how many CPU cycles are wasted waiting for memory allocations.
Architecture Blueprint: cgroup v1 vs. cgroup v2 Memory Management
The structural shift from cgroup v1 to cgroup v2 in Kubernetes transforms container memory allocation from an unforgiving binary ceiling into a multi-tiered safety net.
Memory Allocation Lifecycle Flow
+-----------------------------------------------------------------------------------+
| Container Memory Allocation Flow |
+-----------------------------------------------------------------------------------+
|
v
+---------------------------------+
| Process Requests Memory (Heap) |
+---------------------------------+
|
v
+---------------------------------+
| Is Usage > memory.min? |
+---------------------------------+
/ \
NO YES
/ \
+----------------------------+ +----------------------------+
| Memory Guaranteed | | Is Usage > memory.low? |
| No Reclaim Allowed | +----------------------------+
+----------------------------+ / \
NO YES
/ \
+----------------------------+ +----------------------------+
| Soft Protection: Reclaim | | Is Usage > memory.high? |
| only if no other option | +----------------------------+
+----------------------------+ / \
NO YES
/ \
+----------------------------+ +----------------------------+
| Normal Operation | | Throttling Active! |
| Unrestricted Allocations | | Kernel Reclaims Cache & |
+----------------------------+ | Delays Allocating Process |
+----------------------------+
|
v
+----------------------------+
| Is Usage > memory.max? |
+----------------------------+
/ \
NO YES
/ \
+----------------------------+ +----------------------------+
| Reclaim Keeps Memory Under | | Kernel OOM Killer |
| High Boundary Ceiling | | Triggers (SIGKILL 137) |
+----------------------------+ +----------------------------+
Mapping Kubernetes Pod Specs to cgroup v2 Files
When Kubelet executes with the MemoryQoS feature gate enabled on a cgroup v2 host, Kubernetes Pod specifications map directly to cgroup v2 control files under /sys/fs/cgroup/kubepods.slice/:
| Kubernetes Specification | cgroup v1 Equivalent | cgroup v2 Target File | cgroup v2 Behavior |
| :--- | :--- | :--- | :--- |
| spec.containers[].resources.requests.memory | (Used only for scheduling) | memory.min / memory.low | Sets kernel hard protection (memory.min) or soft protection (memory.low) proportional to request size. |
| Memory QoS Formula | N/A | memory.high | Dynamic calculated value: limits.memory - (limits.memory - requests.memory) * ThrottlingFactor. Acts as proactive throttle. |
| spec.containers[].resources.limits.memory | memory.limit_in_bytes | memory.max | Hard limit ceiling. Triggers OOM killer only when direct reclaim under memory.high cannot keep pace. |
| N/A | memory.oom_control | memory.oom.group | Ensures all processes in a container cgroup are terminated together if an OOM occurs, avoiding zombie process state. |
Production-Ready Implementation Guide
Migrating a production Kubernetes cluster to cgroup v2 with Memory QoS requires configuration changes across three distinct layers: the Operating System (Host Kernel), the Container Runtime (containerd), and the Kubernetes Node Agent (kubelet).
Step 1: Host Operating System Configuration (Ubuntu 22.04+ / RHEL 9+)
The Linux kernel must boot with unified hierarchy enabled and legacy v1 hierarchies disabled.
Edit /etc/default/grub on worker nodes:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash systemd.unified_cgroup_hierarchy=1 cgroup_no_v1=all psi=1"
Apply GRUB changes and reboot worker nodes:
sudo update-grub
sudo reboot
Verify that cgroup v2 is mounted correctly after host reboot:
# Verify filesystem type is cgroup2fs
stat -fc %T /sys/fs/cgroup
# Expected Output:
# cgroup2fs
Ensure PSI (Pressure Stall Information) is active:
cat /proc/pressure/memory
# Expected Output:
# some avg10=0.00 avg60=0.00 avg300=0.00 total=0
# full avg10=0.00 avg60=0.00 avg300=0.00 total=0
Step 2: Containerd Systemd Cgroup Driver Configuration
containerd must be configured to use systemd as its cgroup driver to correctly manage cgroup v2 hierarchies.
Modify /etc/containerd/config.toml:
version = 2
[plugins]
[plugins."io.containerd.grpc.v1.cri"]
[plugins."io.containerd.grpc.v1.cri".containerd]
default_runtime_name = "runc"
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes]
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc]
runtime_type = "io.containerd.runc.v2"
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc.options]
SystemdCgroup = true
[plugins."io.containerd.grpc.v1.cri".memory_qos]
enable = true
Restart and verify containerd:
sudo systemctl restart containerd
sudo systemctl status containerd
Step 3: Kubelet Memory QoS Configuration
Enable the MemoryQoS feature gate and set resource reservation thresholds inside the KubeletConfiguration file (typically /var/lib/kubelet/config.yaml).
apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
cgroupDriver: systemd
cgroupRoot: /
featureGates:
MemoryQoS: true
KubeletInformerCache: true
# Memory QoS Tuning Parameters
memoryThrottlingFactor: 0.90
systemReserved:
cpu: "500m"
memory: "1Gi"
ephemeral-storage: "2Gi"
kubeReserved:
cpu: "500m"
memory: "1Gi"
ephemeral-storage: "2Gi"
evictionHard:
memory.available: "500Mi"
nodefs.available: "10%"
nodefs.inodesFree: "5%"
evictionPressureTransitionPeriod: "30s"
Restart Kubelet:
sudo systemctl restart kubelet
Step 4: Workload Deployment Blueprint (Production Kubernetes Manifest)
This deployment demonstrates how a high-throughput enterprise service utilizes cgroup v2 Memory QoS parameters to eliminate OOMKilled errors under traffic spikes.
apiVersion: apps/v1
kind: Deployment
metadata:
name: dynamic-api-gateway
namespace: production
labels:
app.kubernetes.io/name: dynamic-api-gateway
app.kubernetes.io/tier: api
ecstaticloud.com/cgroup-version: "v2"
spec:
replicas: 3
selector:
matchLabels:
app: dynamic-api-gateway
template:
metadata:
labels:
app: dynamic-api-gateway
spec:
priorityClassName: high-priority-apps
containers:
- name: gateway
image: registry.ecstaticloud.internal/gateway:v2.4.1
imagePullPolicy: IfNotPresent
env:
- name: NODE_OPTIONS
value: "--max-old-space-size=1536"
- name: MALLOC_ARENA_MAX
value: "2"
resources:
requests:
cpu: "1000m"
memory: "1536Mi"
limits:
cpu: "2000m"
memory: "2048Mi"
readinessProbe:
httpGet:
path: /healthz/ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 10
livenessProbe:
httpGet:
path: /healthz/live
port: 8080
initialDelaySeconds: 15
periodSeconds: 20
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
runAsNonRoot: true
runAsUser: 10001
capabilities:
drop:
- ALL
volumeMounts:
- name: tmp-dir
mountPath: /tmp
volumes:
- name: tmp-dir
emptyDir:
medium: Memory
sizeLimit: 256Mi
Verifying Active cgroup v2 Parameters at Runtime
Inspect the cgroup v2 control files for the running container using crictl or direct host inspection:
# 1. Obtain the Container ID
CONTAINER_ID=$(sudo crictl ps --name gateway -q | head -n 1)
# 2. Extract the Cgroup Path via inspect template
CGROUP_PATH=$(sudo crictl inspect --output json $CONTAINER_ID | jq -r '.info.runtimeSpec.linux.cgroupsPath')
# 3. Read the actual cgroup v2 limits set by Kubelet/containerd
cd /sys/fs/cgroup/$CGROUP_PATH
echo "=== memory.min (Hard Protection) ==="
cat memory.min
echo "=== memory.low (Soft Protection) ==="
cat memory.low
echo "=== memory.high (Throttling Boundary) ==="
cat memory.high
echo "=== memory.max (Hard Limit Ceiling) ==="
cat memory.max
Expected calculated values based on pod config (requests: 1536Mi, limits: 2048Mi, throttlingFactor: 0.90):
memory.min:1610612736bytes (1536 MiB)memory.high:1979711488bytes (~1884 MiB — calculated as $1536 + (2048 - 1536) \times 0.90$)memory.max:2147483648bytes (2048 MiB)
Performance Benchmarks & Comparison
To analyze the impact of cgroup v2 with Memory QoS, Ecstaticloud performed synthetic and real-world benchmarks under simulated 300% traffic spikes on a Kubernetes v1.28 cluster running Linux Kernel 6.2 with Node.js and Java (OpenJDK 17) workloads.
Comparison Table
| Metric / Dimension | Legacy Architecture (cgroup v1) | Ecstaticloud Optimized Architecture (cgroup v2 + Memory QoS) | Performance Impact / Gain | | :--- | :--- | :--- | :--- | | Daily OOMKilled Rate (Per 1k Pods) | 42.8 events / day | 0.1 events / day | 99.7% reduction in process crashes | | p99.9 Latency Under Memory Pressure | 4,250 ms (Stalls before death) | 180 ms (Graceful throttling) | 95.7% lower tail latency | | Page Cache Reclaim Efficiency | Unregulated / Sudden Drops | Linear & Proportional (PSI-driven) | Prevents cache thrashing | | Node Memory Packing Utilization | 58% (Inflated limits required) | 86% (Realistic requests/limits) | 48.2% density increase | | Recovery Strategy | Pod Restart (15s–60s downtime) | Kernel Reclaim & Dynamic Throttle | Zero pod downtime | | Infrastructure Cloud Spend | Baseline ($100%) | 67.4% of Baseline | 32.6% cost reduction |
Benchmark Analysis Notes
Latency Profile During Memory Pressure Spike (300% Load Event)
cgroup v1:
[Normal Latency 20ms] ---> [Page Cache Thrash Stalls 4250ms] ---> [OOMKilled Event (Crash)] ---> [Restart 45s]
cgroup v2 + Memory QoS:
[Normal Latency 20ms] ---> [memory.high Reclaim Throttle 180ms] ---> [Traffic Spike Passes] ---> [Normal Latency 20ms]
Under cgroup v1, as memory usage enters the allocation zone within 5% of memory.limit_in_bytes, kernel synchronous page clearing locks execution threads. The application stalls entirely before being killed by SIGKILL.
Under cgroup v2, when allocations hit memory.high, the kernel injects subtle, microsecond-level delay loops into process allocations while concurrently reclaiming clean page caches. The application experiences a slight latency degradation (p99 increases to 180ms), but remains fully operational. The service processes the queue, handles the burst, and returns to baseline latency without a single pod restart.
Production Pitfalls & Hard-Learned Edge Cases
While cgroup v2 provides substantial stability improvements, migrating production Kubernetes clusters without accounting for low-level runtime behaviors can introduce unexpected secondary issues.
1. Java Runtimes (JDK < 11.0.16 or JDK 17 < 17.0.5) Ignoring memory.high
The Edge Case: Legacy Java Virtual Machine (JVM) builds are aware of cgroup v2, but they calculate their Maximum Heap Size (-XX:MaxRAMPercentage) exclusively against memory.max. If memory.high is set lower than memory.max, the JVM may configure its maximum heap size to exceed memory.high.
cgroup v2 Boundary Mismatch in Legacy Runtimes
┌─────────────────────────────────────────────────────────────────────────────┐
│ cgroup v2 Memory Range │
│ │
│ [requests.memory] [memory.high] [memory.max] │
│ │ │ │ │
│ v v v │
│ 1536Mi 1884Mi 2048Mi │
└─────────┴────────────────────────┴────────────────────────┴─────────────────┘
^ ^
│ │
JVM Max Heap Allocation Area ────┼────────────────────────┘
(-XX:MaxRAMPercentage=80.0) │ (Allocates up to 1638.4Mi Heap + Non-Heap Metadata)
│
└─> DANGER: JVM Heap + Metaspace pushes process past
memory.high into continuous kernel throttle loops!
Failure Mode: The JVM continuously exceeds memory.high, placing the container into perpetual allocation throttling. CPU utilization spikes to 100% due to direct reclaim effort inside the kernel, leading to failed liveness probes.
Remediation: Explicitly define heap bounds in JVM arguments alongside MaxRAMPercentage:
-XX:MaxRAMPercentage=70.0 -XX:ActiveProcessorCount=2
Ensure your container images use standard base images with modern Java versions (JDK 17.0.7+ or JDK 21+), which natively support cgroup v2 structure.
2. Prometheus Metric Path Breaking (container_memory_working_set_bytes)
The Edge Case: Monitoring agents like cAdvisor, Prometheus Node Exporter, and Datadog agents rely on /sys/fs/cgroup directory parsing. Under cgroup v1, memory metrics read from /sys/fs/cgroup/memory/memory.stat. Under cgroup v2, the path switches to /sys/fs/cgroup/memory.stat with completely redesigned keys (anon, file, kernel, slab).
Failure Mode: Legacy monitoring dashboards and Horizontal Pod Autoscalers (HPA) leveraging custom metrics lose data streams. container_memory_working_set_bytes may display zero or invalid calculations, causing HPAs to fail to scale or downscale rapidly.
Remediation:
- Upgrade
kube-state-metricstov2.8.0+andcAdvisortov0.47.0+. - Update Datadog/Sysdig agents to versions that explicitly support unified cgroup v2 metric collection.
- Validate metric extraction manually on worker nodes:
# Verify cgroup v2 metric reporting via cAdvisor/Containerd
curl -s http://localhost:10255/metrics | grep container_memory_working_set_bytes
3. Misaligned Kubelet evictionHard vs. cgroup v2 memory.high
The Edge Case: If the Kubelet evictionHard limit (e.g., memory.available < 500Mi) fires before container-level memory.high direct reclaim can clear memory, the Kubelet will evict the Pod entirely.
Timeline Conflict: Eviction vs. Reclaim
Time ----------------------------------------------------------------->
1. Memory Spike Occurs
2. Usage hits node memory.available threshold
3. Kubelet Eviction Watchdog Triggers (Pod Terminated) <-- FIRES FIRST IF UNTUNED!
4. cgroup v2 memory.high Direct Reclaim (Throttles & Frees Cache) <-- TOO LATE
Failure Mode: You enable cgroup v2, but Pods are still terminated—not with OOMKilled (Exit Code 137), but with Evicted status driven by node-level Kubelet eviction loops.
Remediation: Maintain sufficient headroom between Kubelet system reservations, eviction limits, and container memory configurations. Ensure evictionHard evaluates overall node availability, allowing container-level memory.high reclaim mechanisms to execute before node eviction triggers. Set evictionPressureTransitionPeriod to at least 30s in KubeletConfiguration.
Frequently Asked Questions
How do I verify if my Kubernetes nodes are running cgroup v2?
Execute the following command on any worker node via SSH or a privileged DaemonSet:
stat -fc %T /sys/fs/cgroup
If the output is cgroup2fs, your node is running cgroup v2. If the output is tmpfs, the host is using cgroup v1. Additionally, inspect Kubelet node status using kubectl:
kubectl get node <node-name> -o jsonpath='{.status.nodeInfo.containerRuntimeVersion}'
Nodes leveraging cgroup v2 alongside modern runtimes will output runtime details with unified driver confirmation.
Does cgroup v2 completely eliminate OOMKilled errors in Kubernetes?
No. cgroup v2 does not eliminate OOMKilled events if an application suffers from an uncapped memory leak or attempts to allocate anonymous memory (heap space) that exceeds memory.max.
However, cgroup v2 eliminates false-positive OOM kills caused by transient page cache spikes, unthrottled file reads, and temporary buffer allocations. By inserting a memory.high throttling region before memory.max, the operating system gets a buffer window to reclaim cache memory and slow allocation rates down gracefully.
What is the difference between memory throttling and CPU throttling in Kubernetes?
- CPU Throttling: Governed by Completely Fair Scheduler (CFS) quota limits (
cpu.cfs_quota_us). When a container uses up its allocated CPU quota for a given time period (e.g., 100ms), the kernel pauses CPU execution until the next period starts. This causes latency spikes, but never crashes the process. - Memory Throttling (cgroup v2): Governed by
memory.high. When usage exceeds this threshold, the allocating process threads enter synchronous direct reclaim. The process is delayed proportionally to its memory allocation rate while the kernel attempts to free page caches. Like CPU throttling, it increases latency to protect stability—preventing an immediate OOM kill (memory.max).
How does MemoryQoS in Kubernetes map Pod requests and limits to cgroup v2 parameters?
When MemoryQoS is enabled in Kubelet, Kubernetes maps pod specs to cgroup v2 parameters using the following formulas:
memory.min: Set to Podrequests.memory(or a factor of request) to guarantee this memory cannot be reclaimed by other pods.memory.high: Calculated dynamically using the formula: $$\text{memory.high} = \text{limits.memory} - ((\text{limits.memory} - \text{requests.memory}) \times (1 - \text{memoryThrottlingFactor}))$$ (Using the default KubeletmemoryThrottlingFactorof 0.9).memory.max: Set directly to Podlimits.memory. Iflimitsis omitted,memory.maxis set tomax(unbounded).