FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Linux Control Groups & Namespaces

cgroups v2 resource controllers, Linux namespaces (pid, net, mnt), and container runtime isolation.

Freshness: current•15 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Restrict container CPU and memory budgets using cgroups v2
  • ✓Isolate process environments with Linux kernel namespaces
Full Technical Reference Document

Mental model

Linux containers are standard Linux host processes, NOT lightweight virtual machines: every container shares the exact same host Linux kernel, differing only in kernel-enforced visibility boundaries and resource budgets. Namespaces virtualize what a process can see (its own process tree pid, network stack net, filesystem mounts mnt, IPC ipc, hostname uts, and mapped user IDs user), while Control Groups v2 (cgroups v2) enforce a single unified hierarchy dictating how much physical resource a process tree can consume (CPU quotas cpu.max, soft/hard RAM limits memory.high / memory.max, disk I/O bandwidth, and fork-bomb protection pids.max).

clone() / unshare() Assigns Namespaces
pivot_root Isolates Container Filesystem
Attach Process to cgroups v2 Slice
Kernel Enforces cpu.max, memory.max & pids.max
PSI & OOM Controllers Guard Host Stability
Conceptual teaching model synthesized from:linux-kernel-docs,sre-book

Theory

Unlike legacy cgroups v1—where independent subsystem trees (memory, cpu, blkio) drifted out of sync and made page-cache writeback accounting unreliable—cgroups v2 enforces a strict unified single tree under /sys/fs/cgroup/, enabling coordinated Memory-to-IO attribution and Pressure Stall Information (PSI) telemetry (cpu.pressure, memory.pressure, io.pressure).

Kernel Isolation LayerSpecific PrimitiveResource / Visibility ControlledProduction Trap Without Proper Configuration
Namespaces (7 types)pid, net, mnt, ipc, uts, user, cgroupIsolated PID 1, eth0/veth, overlayfs mounts, UID 0 -> 100000 host mappingWithout user NS or non-root USER, container UID 0 equals host root on kernel/mount leaks!
cgroups v2 Memorymemory.high (throttling) + memory.max (hard OOM ceiling) + memory.swap.maxAnonymous RSS plus filesystem page cache inside the container!Uncapped page cache or absent memory.max starves sibling containers & triggers global host OOM
cgroups v2 CPU (CFS)cpu.max ("$QUOTA $PERIOD", e.g. 200000 100000 = 2 cores) + cpu.weightHard bandwidth ceiling per 100 ms period + contention shareMulti-threaded runtimes (JVM/Node/Go) unaware of cgroup quotas or burst spikes hit severe CFS throttling!
cgroups v2 PIDspids.max (e.g., 512)Maximum process + OS thread count (clone())Runaway while(1) fork() inside container locks entire host kernel PID table (EAGAIN)

CFS Throttling Latency Traps, Page-Cache Accounting, and Kubernetes Runtime Awareness

Two classic surprises catch production teams running Node.js, Python, or Go containers under strict cgroups v2:

  1. CPU CFS Quota Throttling Tail-Latency Spikes: Setting cpu.max to 100000 100000 (1.0 core per 100 ms window) allows a 16-thread worker runtime to burn all 100 ms of quota across 8 threads in just 12.5 ms—forcing the kernel Completely Fair Scheduler (CFS) to freeze the entire container dead for the remaining 87.5 ms! Always align language concurrency settings (e.g., GOMAXPROCS, Uvicorn --workers, Node worker pools) with cgroup CPU quota rather than host physical nproc, and consider omitting hard CPU limits on latency-critical web pods when using cpu.weight (K8s requests) vs strict limits carefully.
  2. Page Cache (file) + Anonymous Heap (anon) Count Toward memory.max: Reading or writing huge Parquet datasets or Docker layer tarballs fills Linux kernel page cache billed directly to your container's memory.current. When memory.current reaches memory.max, Linux tries reclaiming clean page cache first, then kills the biggest process via cgroup OOM killer (oom_kill) (memory.events counter)—leaving host systemd and neighbor containers completely healthy! Use memory.high slightly below memory.max (85%) so memory reclaim triggers gracefully before sudden SIGKILL OOM kills.
bash
# Inspect and configure a cgroups v2 unified hierarchy slice on modern Linux:
mkdir -p /sys/fs/cgroup/ai_sandbox.slice
​
# Enforce memory throttle threshold (768 MiB) + hard ceiling (1 GiB) + no swap
echo "805306368" > /sys/fs/cgroup/ai_sandbox.slice/memory.high
echo "1073741824" > /sys/fs/cgroup/ai_sandbox.slice/memory.max
echo "0" > /sys/fs/cgroup/ai_sandbox.slice/memory.swap.max
​
# Enforce 1.5 CPU cores (150ms quota per 100ms period) and block fork bombs at 256 tasks
echo "150000 100000" > /sys/fs/cgroup/ai_sandbox.slice/cpu.max
echo "256" > /sys/fs/cgroup/ai_sandbox.slice/pids.max
​
# Inspect live Pressure Stall Information (PSI) for CPU & memory contention:
cat /sys/fs/cgroup/ai_sandbox.slice/memory.pressure

Alternatives and trade-offs

  • Standard Linux Containers (Namespaces + cgroups v2 via containerd/Docker): Near-native bare-metal execution speed (0% hypervisor tax), sub-second startup, dense bin-packing; shares one host Linux kernel cleanly across containers—meaning kernel syscall vulnerabilities affect all co-located workloads on that host.
  • MicroVMs (Firecracker / Kata Containers): Wraps each untrusted workload (e.g., running arbitrary AI-generated Python code!) inside a dedicated hardware-virtualized guest kernel (KVM) booting in ~125 ms, eliminating shared-kernel container escapes at slight memory/KVM virtualization overhead (~5–15 MB per microVM).
  • Userspace Syscall Sandboxes (gVisor): Re-implements Linux syscalls in a userspace Go sentry binary, hardening multi-tenant container escapes cleanly without requiring nested KVM hardware virtualization in cloud VMs—trading slower heavy syscall/filesystem throughput.

Failure modes and misconceptions

  1. Expecting Unprivileged cgroup / /proc/meminfo Inside Containers to Match Container Limits: Standard Linux /proc/cpuinfo and /proc/meminfo still show the host server's total RAM/CPUs (unless running LXCFS)! Tools sizing buffers from /proc/meminfo or os.cpu_count() accidentally over-allocate 64 worker threads inside a 1-CPU / 512MB container and immediately OOM or suffer severe CFS throttling—always read /sys/fs/cgroup/memory.max and cpu.max (cgroups v2) cleanly!
  2. Running Multi-Tenant / Untrusted AI User Code in Plain Namespaced Containers Alone: Even with cgroups v2 and namespaces enabled, executing arbitrary LLM-generated code shares thousands of host kernel attack vectors (io_uring, nftables, kernel eBPF bugs). Pair cgroups v2 + User Namespaces + Seccomp OR move untrusted code execution into Firecracker MicroVMs or gVisor.
  3. Omitting pids.max and --init / PID 1 Signal Reaping: Running an app binary directly as container PID 1 skips Unix zombie process reaping unless an explicit tini/init shim or runtime signal handler reaps dead child PIDs—and without pids.max, a single fork bug exhausts the host kernel process table (max_pids) across all containers.
  4. Assuming memory.max Prevents Swapping Latency Stalls: When host swap is enabled and memory.swap.max stays max (unbounded), a leaky container pushes anonymous memory into slow NVMe/SSD swap, turning API latency from 2 ms to 4,000 ms instead of failing cleanly! Explicitly set memory.swap.max = 0 on latency-sensitive microservice containers.
Reflect before revealing the guide

Decision scenario

Your SaaS hosts two distinct workloads on Linux VMs: (1) trusted internal Node/Python API microservices running under Docker/containerd, and (2) an untrusted Python AI code-execution runner executing user-submitted scripts. For internal microservices, enforce cgroups v2 memory.high (85%), memory.max, memory.swap.max=0, pids.max, user namespace UID mapping (UID 1001), --init PID 1 zombie reaping, and runtime reads from /sys/fs/cgroup/cpu.max so Node/Python worker counts match container cores rather than host nproc; for untrusted AI code execution, refuse to rely on namespaces alone and isolate sandboxes inside Firecracker MicroVMs or gVisor bounded by strict cgroup slices and PSI alerts.

Learning outcomes

  • Map the seven Linux Namespaces cleanly to what each isolates (pid, net, mnt, user, ipc, uts, cgroup).
  • Explain why cgroups v2 unified memory + page-cache + PSI accounting supersedes fragmented cgroups v1 controllers.
  • Diagnose and fix CFS CPU throttling spikes, swap stalls (memory.swap.max=0), and /proc/meminfo host-reading bugs.
  • Know the security boundary where shared-kernel Linux containers stop and Firecracker MicroVMs / gVisor must take over.

Trade-offs

Linux Namespaces and cgroups v2 enable ultra-dense, zero-virtualization-tax service deployment across Linux clusters, balanced against careful cpu.max / memory.max awareness inside container runtimes and inherent shared-kernel risk for untrusted code.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next