cgroups v2 and namespaces: how a container is assembled and limited

A container is a normal process with namespaces for what it can see and cgroups for what it can use. There is no container object in the kernel — which is why every container problem is a Linux problem.

Read the briefing
About 9 min to read 9 drills

What to remember

  1. Namespaces = what you can see. Cgroups = what you can use. Two independent mechanisms. Most 'container' questions are really about one or the other.
  2. cgroup v2 has one unified hierarchy. memory.max, cpu.max, pids.max, io.max, plus per-cgroup PSI — which is what exposes a throttled container.
  3. CPU limits are a quota per 100 ms period. Exceed it and every thread is stopped until the next period. That is why a low limit destroys p99.
  4. A container's memory limit counts page cache too. So heavy file I/O can OOM-kill a process whose RSS looks fine. Read memory.stat.
  5. Root in a container is root on the host if it escapes. Drop capabilities, run non-root, read-only filesystem — the namespace is not a security boundary by itself.

The big picture

Control groups decide how much of the machine a group of processes may use; namespaces decide what those processes can see. A container is nothing more than an ordinary process started inside a fresh set of namespaces, placed in a cgroup, given a private root filesystem, and stripped of most capabilities. Every "my container is slow but the node is idle", "it was OOM-killed with free memory", and "root inside the container cannot do X" question is answered by knowing which of those two mechanisms is involved.

The mental model

Two orthogonal axes. Namespaces are views: PID numbering, network stack, mount table, hostname, IPC, user ids. cgroups are budgets: CPU time per period, bytes of memory, I/O bandwidth, task count, each enforced by a controller that either throttles (cpu, io, memory.high) or kills (memory.max, pids.max returns EAGAIN). The kernel has no "container" object; the runtime composes one from these parts, and you debug one by reading the files under /sys/fs/cgroup and /proc//ns.

In depth

The unified tree and who owns it

cgroup v2 is a single hierarchy mounted at /sys/fs/cgroup. Every directory is a cgroup; creating a directory creates a group, and writing a PID to its cgroup.procs moves a process in. A group's cgroup.controllers lists the controllers it may use, and its cgroup.subtree_control enables them for its children (+cpu +memory +io +pids). A controller that is not enabled at a level does not exist below it, which is why a freshly created group sometimes has no cpu.max file at all.

On a systemd host, systemd owns the top of the tree: system.slice for services, user.slice for logins, machine.slice for VMs and containers; the kubelet with the systemd cgroup driver hangs kubepods.slice off the root and puts each pod in its own .slice and each container in a .scope. Ask a process where it lives with cat /proc/<pid>/cgroup, which in v2 prints one line:

$ cat /proc/41822/cgroup
0::/system.slice/nginx.service

That path is relative to /sys/fs/cgroup, so the limits and counters for that process are in /sys/fs/cgroup/system.slice/nginx.service/. systemd-cgls prints the whole tree with processes and systemd-cgtop shows live usage per group. v1 mounted one hierarchy per controller under /sys/fs/cgroup/<controller>/; if you see memory/ and cpu/ directories the host is on v1 or hybrid mode and the file names differ (memory.limit_in_bytes, cpu.cfs_quota_us).

CPU: quota is throttling, weight is sharing

cpu.max holds two numbers, $QUOTA $PERIOD in microseconds; 200000 100000 means the group may consume 200 ms of CPU time in every 100 ms window, i.e. two CPUs' worth. The accounting is per period and across all threads: a service with sixteen runnable threads on a sixteen-core node burns a 2-CPU quota in about 12 ms of wall time, then every thread in the group is descheduled until the next period starts. The average utilization graph shows a calm 2 CPUs while p99 latency shows ~90 ms stalls. cpu.stat tells the truth:

nr_periods 3120442
nr_throttled 1873201
throttled_usec 71218844112

nr_throttled / nr_periods is the share of periods in which the group hit its quota; anything above a few percent on a latency-sensitive service is a problem. Kubernetes limits.cpu is exactly this quota; requests.cpu becomes cpu.weight.

cpu.weight (1–10000, default 100) is proportional sharing. It only matters when the CPU is contended: a group with weight 200 gets twice the CPU of one with weight 100 when both want it, and an idle machine gives everyone everything. Weight never throttles, which is why many teams set CPU requests but no CPU limits for latency-critical services and rely on weight for fairness. Newer kernels add cpu.max.burst to let a group bank unused quota, and cpu.pressure gives PSI for the group so you can alert on stall time rather than on utilization.

Memory: the charge, the reclaim, the kill

Memory is charged to the cgroup whose process first touched the page. That includes anonymous memory (heap, stacks), page cache from files the group reads or writes, and kernel memory such as slab and socket buffers. memory.current is therefore not "the application's RSS": a container that streams a 3 GB file has 3 GB of page cache charged and looks nearly full. memory.stat splits the number (anon, file, kernel, shmem, file_dirty), and the working set that Kubernetes reports is memory.current minus inactive_file.

As memory.current approaches memory.max the kernel reclaims within the group: it drops clean cache, writes back dirty pages, swaps anonymous pages if memory.swap.max allows. Only when reclaim cannot free enough does the cgroup-scoped OOM killer run, choosing the largest task in the group and incrementing oom_kill in memory.events. The host may have 200 GB free; the group's ceiling is what matters. memory.high is the softer knob: exceeding it throttles the allocating tasks with reclaim stalls rather than killing, which turns a would-be kill into latency and gives a user-space agent time to act (systemd-oomd itself acts on the resulting memory pressure and swap use, not on memory.high).

The protection knobs go the other way. memory.low tells the kernel to prefer reclaiming siblings before touching this group's memory below the threshold; memory.min makes that guarantee hard. Use them for the process that must not thrash when a noisy neighbour on the same host fills the cache. memory.peak records the high-water mark, the right input for sizing a limit, and memory.events (low, high, max, oom, oom_kill) is the first file to read when a container restarted for no visible reason.

io and pids: the two controllers people forget

The io controller works per block device, identified as MAJ:MIN (from lsblk or ls -l /dev). io.max sets absolute caps, for example 259:0 rbps=104857600 wiops=2000, and io.weight shares bandwidth proportionally between siblings when the device is busy. Weight-based sharing needs an I/O scheduler or cost model that supports it (BFQ, or io.cost on newer kernels); io.max works anywhere. io.stat shows bytes and operations per device per group and io.pressure shows stall time. A useful sanity check when a host is "slow on disk": systemd-cgtop -m or reading io.stat for the top-level slices tells you which group is generating the I/O, which iostat cannot.

pids.max caps the number of tasks (processes and threads) in the group. When the cap is reached fork() and pthread_create() fail with EAGAIN ("Resource temporarily unavailable"), pids.events increments max, and nothing is killed. systemd exposes it as TasksMax= with a default of 15% of pid_max for services (systemctl show -p TasksMax nginx), Docker as --pids-limit, and the kubelet as podPidsLimit. The classic incident is a fork bomb or a thread leak that fails harmlessly inside its group instead of taking the host, which is the whole point; the confusing incident is a legitimately large thread pool tripping a default TasksMax and logging "cannot allocate memory" from a runtime that mis-reports the errno.

Namespaces: eight views of one kernel

A namespace wraps one global resource so that a set of processes sees its own instance. pid gives the group its own numbering starting at 1, and processes cannot see or signal PIDs outside it; the first process is the namespace's init, and when it exits the kernel SIGKILLs every other process in the namespace. net gives a private network stack: interfaces, addresses, routes, sockets, netfilter rules and most net.* sysctls, so port 80 inside a container and port 80 on the host do not collide. mnt gives a private mount table, which is what lets the runtime pivot_root into an image without the host noticing. uts is the hostname and domain name, ipc is System V IPC and POSIX message queues, cgroup virtualizes the cgroup root, time offsets CLOCK_MONOTONIC and CLOCK_BOOTTIME.

user is the important one for security: it maps a range of uids inside the namespace to a range outside, written in /proc/<pid>/uid_map. Uid 0 inside can be uid 100000 outside, holding full capabilities over resources owned by the namespace and none over the host. That is the basis of rootless containers and of why root in a user-namespaced container cannot read a host file owned by real uid 0.

Namespaces are created by clone() or unshare() with CLONE_NEW* flags and joined with setns(); nsenter -t <pid> -n ss -ltnp runs a host binary inside a container's network namespace, which is the standard way to inspect a distroless container. ls -l /proc/<pid>/ns/ shows one symlink per namespace with an inode number; two processes with the same inode share that namespace, and lsns lists them all. A namespace lives as long as a process is in it or a bind mount pins it (ip netns add keeps one alive under /run/netns/), and it vanishes when the last reference goes.

Assembling a container, and reading one back

When you run docker run or a pod starts, containerd calls runc with an OCI bundle: a config.json and a root filesystem. runc forks a child with clone(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWNET | CLONE_NEWUTS | CLONE_NEWIPC ...), moves that child into the target cgroup by writing its PID to cgroup.procs, and in the child: mounts the image layers as overlayfs (lowerdir = read-only layers, upperdir = the writable layer), mounts /proc, /sys, /dev and the requested volumes, pivot_roots so the image becomes /, sets the hostname, applies the seccomp filter, drops capabilities to the allowed bounding set, sets no_new_privs, and finally execves the entrypoint. The entrypoint becomes PID 1 of the new pid namespace, though from the host it is an ordinary PID (grep NSpid /proc/<host-pid>/status shows both numbers). docker exec is setns() into every namespace and the cgroup of that process followed by execve, which is why an exec'd shell shares the container's memory limit.

Reading a container back is reading those parts. Which cgroup: /proc/<pid>/cgroup. Is it throttled: cpu.stat. Was it OOM-killed: memory.events and dmesg ("Memory cgroup out of memory"). How many tasks: pids.current against pids.max. What can it see: /proc/<pid>/ns, nsenter, and /proc/<pid>/mountinfo. What may it do: CapEff in /proc/<pid>/status decoded with capsh --decode, Seccomp: 2, and NoNewPrivs: 1. None of this needs the container runtime to be healthy, which matters precisely when it is not.

Myths and facts

Myth: A container is a lightweight VM with its own kernel.

Fact: It is a process on the host kernel inside namespaces and a cgroup. ps on the host shows its processes, uname -r inside shows the host kernel, and a kernel bug or sysctl affects every container.

Myth: If a cgroup shows low average CPU usage it cannot be CPU-bound.

Fact: Quota is enforced per 100 ms period across all threads. A group can use 2 CPUs on average and still be throttled in most periods; cpu.stat nr_throttled is the signal, not utilization.

Myth: memory.current is the application's RSS.

Fact: It includes page cache, shmem and kernel memory charged to the group. A container streaming files looks nearly full but the cache is reclaimable; memory.stat anon vs file tells them apart.

Myth: cpu.weight (a CPU request) reserves CPU for the group.

Fact: Weight only arbitrates contention. On an idle host everyone gets what they ask for; under contention shares are proportional; nothing is held back for a group that is idle.

Myth: root inside a container is root on the host.

Fact: It may be uid 0 with a small capability set and no CAP_SYS_ADMIN, or uid 0 in a user namespace mapped to an unprivileged host uid. Both fail on things real root can do, and the error is EPERM, not 'access denied by Docker'.

Myth: Namespaces isolate resources like memory and CPU.

Fact: Namespaces isolate visibility and naming; cgroups isolate resource usage. A container with namespaces but no cgroup limits can consume the whole host.

How pros do it

  • Read cpu.stat nr_throttled and throttled_usec before believing a CPU utilization graph; alert on the throttled-period ratio for latency-critical groups.
  • Size memory.max from memory.peak plus headroom, and read memory.events oom_kill and memory.stat anon vs file before raising a limit.
  • Prefer cpu.weight (requests) without cpu.max (limits) for latency-critical services, and match thread-pool sizes (GOMAXPROCS, worker counts) to the quota when a limit exists.
  • Set pids.max / TasksMax on every service so a fork or thread leak fails inside its group instead of exhausting the host's pid_max.
  • Use memory.low or memory.min to protect the one process that must not thrash when a noisy neighbour fills the page cache.
  • Debug containers with host tools through nsenter (-n for the network namespace, -m for mounts) rather than adding debugging binaries to images.
  • Run containers with user namespaces or at least a non-root uid and a dropped bounding set; treat CAP_SYS_ADMIN as equivalent to root.

Questions people ask

What actually is a container?

An ordinary process on the host kernel, started inside a fresh set of namespaces (what it can see: PIDs, network, mounts, hostname, users) and placed in a cgroup (what it may use: CPU, memory, I/O, task count), with an overlay root filesystem, a seccomp filter and most capabilities dropped. 'There is no container object in the kernel' is the sentence interviewers wait for; the caveat is what stays shared: the kernel, the page cache, conntrack, and most non-network sysctls.

The container was OOM-killed but free on the node showed 200 GB available. How?

The killer that ran was scoped to the cgroup: memory.current reached memory.max, reclaim inside the group could not free enough, and the kernel killed the largest task in the group; dmesg says 'Memory cgroup out of memory' and memory.events oom_kill increments. Host memory was never the question. The caveat: memory.current includes the page cache the container caused, so read memory.stat anon versus file before deciding the limit is wrong.

Why is my container throttled when the node has 60 idle cores?

Because cpu.max is a budget per 100 ms period, not a share of the node: once its threads spend the quota inside a period they wait for the next one however idle the node is. Prove it with nr_throttled in cpu.stat, then raise or remove the limit or match parallelism to it. The caveat: cpu.weight (a request) never throttles, which is why latency-critical services often carry requests and no limits.

How does a container get its own PID 1, and why does killing it end everything?

The runtime clones the entrypoint into a new pid namespace, so it is PID 1 there, and the kernel treats a namespace's init specially: signals from inside without a handler are ignored, and when it exits every other process in the namespace is SIGKILLed and the namespace is gone. That is why entrypoints must handle SIGTERM, and why docker stop, which signals from the parent namespace, can always finish the job with SIGKILL.

What is the difference between memory.high and memory.max?

memory.max is a hard ceiling that ends in an OOM kill when reclaim fails; memory.high is a throttling threshold that slows allocations with forced reclaim instead, turning a would-be kill into latency and giving an external agent time to act. Use high for batch you want slowed, max for anything that must not take the host.

Is cgroup memory usage including page cache a bug?

No; cache is charged to whoever caused it so one tenant cannot fill the host cache at another's expense, and it is reclaimable. A group at 95% of memory.max with mostly file pages is fine; one at 95% with mostly anon pages is about to be killed. memory.stat tells you which, so never quote memory.current without it.

How do I see what a distroless container is listening on when it has no ss or netstat?

Find its host PID (crictl inspect or docker inspect --format '{{.State.Pid}}'), then nsenter -t <pid> -n ss -ltnp: the host's ss runs inside the container's network namespace and sees its sockets. The same trick with -m gives you its mount table, and none of it needs the runtime to be healthy.

Do I need cgroup v1 knowledge?

Enough to recognise it: per-controller directories under /sys/fs/cgroup and file names like memory.limit_in_bytes and cpu.cfs_quota_us. Modern distributions and Kubernetes default to v2; the concepts map one-to-one, so say that and move on.

Further reading

Drills · 9

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

A developer pings you: "the node is idle, so this cannot be CPU." Their service runs in a cgroup whose cpu.max reads 100000 100000 on a 64-core host that is 20% busy. It has 16 worker threads. Its CPU utilization graph is flat and far below the quota, but p99 latency shows stalls of up to 90 ms and cpu.stat shows nr_throttled climbing at roughly the rate of nr_periods. What is happening?

  1. cpu.max applies per thread, so each of the 16 threads gets only a fraction of the quota. The quota is a single pool for the whole group; threads share it, which is exactly why parallelism drains it fast.
  2. The 16 threads spend the whole quota in the first few milliseconds of each 100 ms period; the kernel then throttles every thread in the group until the next period, so average usage looks low while wall-clock stalls are long. CFS bandwidth control accounts quota per period across all threads; parallel bursts exhaust it early and the rest of the period is dead time.
  3. The stalls are memory reclaim; CPU throttling never affects latency because the scheduler is work-conserving. Throttling forcibly deschedules runnable threads; it is the definition of added latency, and cpu.stat is pointing at it.
  4. The host is CPU-saturated and the group is losing the fight for cores; raise cpu.weight. The host is 20% busy. nr_throttled counts quota exhaustion, which happens on an idle host; weight only matters under contention.
In short

The threads use up the whole CPU quota early in each 100 ms period, so the kernel stops every thread until the next period; average use looks low while stalls are long.

Why

cpu.max is quota period: the group may run quota microseconds of CPU time per period, summed across every thread. With many runnable threads the quota is consumed in a few milliseconds of wall time and the group sleeps for the remainder of the period, so utilization averaged over seconds looks fine while each request that lands in the throttled window waits tens of milliseconds. The interview signal is reaching for cpu.stat rather than a utilization graph, and knowing the fix is the ratio of parallelism to quota, not host capacity.

The common mistake

Reaching for cpu.weight or 'more cores'. Neither touches quota exhaustion, which happens on an idle host by design.

Read the docs

2 Answer out loud

Walk me through what a container is from the kernel's point of view: what the runtime does, in order, to turn docker run into a running process, and which mechanism provides isolation of visibility versus limits on resource use. Four to six sentences.

In short

A strong answer lists the steps in order (clone into namespaces, join a cgroup, overlayfs and pivot_root, seccomp and capability drop, execve) and says namespaces limit what a process sees while cgroups limit what it uses.

What a strong answer does
  • mechanism: Clone into new namespaces (pid, net, mnt, uts, ipc, optionally user), join a cgroup, overlayfs rootfs with pivot_root, mount /proc and /dev, seccomp and capability drop, then execve; states that there is no container object in the kernel.
  • precision: Also names what is shared regardless (kernel, page cache, most non-net sysctls), what user namespaces change about root, and that exec joins namespaces plus cgroup with setns.
  • communication: Ordered sequence, then the visibility/limits split, then one sharp implication, no filler.
Why

Interviewers listen for the ordered sequence of primitives, the clean split between namespaces (visibility) and cgroups (limits), and the acknowledgement that a container shares the kernel. Candidates who say "lightweight VM" or attribute resource limits to namespaces lose the round on the first sentence.

The common mistake

'A lightweight VM', or crediting namespaces with resource limits. Either one loses the round before the second sentence.

Read the docs

3 Pick the strongest answer

A container with memory.max = 4G runs a job that reads a 6 GB dataset sequentially. memory.current sits within 2% of the limit for the whole run, but the job finishes, nothing is killed, and memory.events shows oom_kill 0. A teammate wants to double the limit "because it is clearly at capacity". What is the right read?

  1. The kernel does not charge page cache to cgroups, so this must be a memory leak in the job. It does charge cache, which is the whole reason the number sits at the limit while the job streams a file.
  2. The container is swapping to stay under the limit; disable swap to expose the real usage. Nothing here shows swap activity; memory.swap.current would, and clean file pages are dropped, never swapped.
  3. The charge is mostly page cache from the dataset, which the kernel reclaims inside the group as needed; memory.stat file vs anon will show it, and the limit is only wrong if anon plus unreclaimable memory approaches it. cgroup v2 charges file cache to the group that touched it and reclaims it before considering an OOM kill; a full-looking group with mostly file pages is healthy.
  4. The job is about to be OOM-killed on the next run; memory.current at the limit means no headroom. memory.current includes reclaimable cache; the kill only happens when reclaim fails, and memory.events records it when it does.
In short

The memory is mostly page cache from the dataset, which the kernel reclaims inside the cgroup, so the limit is fine; check anon versus file in memory.stat.

Why

Memory in cgroup v2 is charged to the group that first touched the page, cache included, and reclaim happens within the group as it approaches memory.max. A group whose memory.stat shows a large file component and a small anon component is using the kernel's cache the way it is meant to. Doubling the limit would only let it cache more. The strong answer separates reclaimable from unreclaimable memory before deciding a limit is wrong.

Read the docs

4 Read the output

The service in this container has bad p99 latency and its pod shows three restarts. Walk me through what these files say happened.

$ cat /proc/41822/cgroup
0::/kubepods.slice/kubepods-burstable.slice/kubepods-burstable-pod7c1e.slice/cri-containerd-9f3a.scope
$ cd /sys/fs/cgroup/kubepods.slice/kubepods-burstable.slice/kubepods-burstable-pod7c1e.slice/cri-containerd-9f3a.scope
$ cat cpu.max
200000 100000
$ cat cpu.stat
usage_usec 374452800000
user_usec 351000000000
system_usec 23452800000
nr_periods 3120442
nr_throttled 1873201
throttled_usec 71218844112
$ cat memory.max memory.current memory.peak
4294967296
3187654656
4294967296
$ cat memory.events
low 0
high 0
max 5124
oom 3
oom_kill 3
  1. The node is CPU-saturated; the throttling numbers show contention with other pods. cpu.stat throttling counts quota exhaustion within this group only; contention shows in cpu.pressure and node metrics, not here.
  2. Memory is fine because memory.current is below memory.max; only the CPU quota explains the restarts. The current value is a snapshot after the kills; memory.peak equals the limit and oom_kill is 3.
  3. oom 3 means the host ran out of memory three times and this container was collateral damage. memory.events in a cgroup directory counts events scoped to that group; a host OOM would appear in dmesg without 'Memory cgroup'.
  4. Two problems with two evidences: the 2-CPU quota was exhausted in about 60% of periods (1.87M of 3.12M) so the service was throttled for ~71,000 s in total, and memory hit its 4 GiB ceiling 5,124 times with three cgroup OOM kills, which are the three restarts. nr_throttled/nr_periods is the throttled share; memory.events max counts limit hits and oom_kill counts kills, and memory.peak equal to memory.max confirms the ceiling was reached.
In short

The CPU quota was exhausted in about 60% of periods, and memory hit its 4 GiB ceiling with three cgroup OOM kills, which are the three restarts.

Why

The cgroup directory is the primary source for both symptoms. nr_throttled / nr_periods gives the fraction of 100 ms periods in which the group hit its quota; 60% on a latency-sensitive service is severe. memory.events counts how often reclaim was forced at the limit (max) and how often the group's OOM killer ran (oom_kill); memory.peak equal to memory.max shows the ceiling was reached. Reading these two files before touching kubectl describe is the habit interviewers look for.

Read the docs

5 Find what's broken

On a 32-core host this service shows latency stalls of up to 100 ms under load, and after a few minutes its log fills with pthread_create: Resource temporarily unavailable. Which two lines cause this?

[Unit]
Description=payments API
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/opt/payments/bin/api --workers 16
User=payments
CPUQuota=100%
MemoryMax=2G
MemorySwapMax=0
TasksMax=64
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
In short

Line 9 gives 16 workers only one CPU of quota, so they stall every period, and line 12 caps the group at 64 tasks, so thread creation fails with EAGAIN.

What's broken
  • Line 9: CPUQuota=100% is one CPU's worth of quota (cpu.max 100000 100000) for a service with 16 workers; the workers exhaust the quota early in every period and the whole group is throttled for the rest of it.
  • Line 12: TasksMax=64 is pids.max for the group; 16 workers each spawning helper threads exceed 64 tasks, so pthread_create fails with EAGAIN and nothing is killed.
Why

CPUQuota= maps to cpu.max and is an absolute budget per period, so 100% is exactly one CPU regardless of host size; sixteen workers burn it in a few milliseconds and stall. TasksMax= maps to pids.max, which fails thread creation with EAGAIN when reached. MemoryMax=2G (line 10) and MemorySwapMax=0 (line 11) are deliberate choices that produce OOM kills, not EAGAIN, and LimitNOFILE (line 14) governs file descriptors, whose exhaustion reads "Too many open files". The signal is mapping each systemd directive to its cgroup file and each errno to the controller that produces it.

Read the docs

6 Scenario: what do you do next?

A Go service that fronts checkout has p99 latency of 400 ms against a 120 ms SLO since it was moved to a new 96-core node pool this morning. The node dashboards show 15% CPU utilization. The container has requests.cpu: 2, limits.cpu: 2. The on-call developer says "the node is idle, this must be the network".

Step 1. You have console access to the node. What do you check first?

  1. Restart the pod to see whether latency recovers. It destroys the counters you need and the problem is structural, so it will come back.
  2. Run a packet capture on the node to look for retransmits. Nothing yet implicates the network, and the change this morning was CPU topology (a 96-core pool), which is a strong prior for a quota interaction.
  3. Find the container's cgroup from /proc//cgroup and read cpu.stat (nr_periods, nr_throttled, throttled_usec) and cpu.pressure. A limit-bound container stalls on an idle node; the throttling counters confirm or rule that out in one command before anyone touches the network.
  4. Look at load average on the node. Load average is node-wide and cannot see a cgroup that is throttled inside an idle machine.

Step 2. cpu.stat shows nr_throttled at 72% of nr_periods and throttled_usec growing by 700 ms every second. Inside the container, GOMAXPROCS is 96 because the Go runtime read the node's core count. What is your mitigation?

  1. Change the CFS period from 100 ms to 10 ms in the kubelet. A shorter period makes stalls shorter but more frequent, and it is a node-wide knob for a single container's problem.
  2. Set GOMAXPROCS to the quota (2, via env or automaxprocs) so the runtime stops spreading work across 96 threads that drain the quota in milliseconds; if the service genuinely needs more, raise or remove the CPU limit while keeping the request. Matching parallelism to the quota removes the burst-then-stall pattern immediately and is reversible; adjusting the limit is the second lever.
  3. Scale the deployment to three times the replicas. Each replica would still throttle; you would triple the cost of a misconfiguration.
  4. Raise cpu.weight for the container so it wins contention on the node. There is no contention on a 15%-busy node; weight changes nothing about quota exhaustion.

Step 3. After the change p99 drops to 90 ms. What is the systemic fix you propose in the retrospective?

  1. Ask developers to set GOMAXPROCS manually in each Dockerfile. A reminder that will be wrong the next time a limit changes; encode it in the platform.
  2. Remove CPU limits from every workload in the cluster. Defensible for latency-critical tiers, reckless as a blanket rule; batch and untrusted workloads need a ceiling.
  3. Make runtime parallelism follow the quota fleet-wide (automaxprocs, thread-pool sizing from cpu.max, or the CPU limit exposed via the downward API), alert on the throttled-period ratio per container, and set a policy on when CPU limits are used at all for latency-critical services. Mechanisms: the runtime reads the real budget, the alert catches the next mismatch, and the policy decides whether quotas belong on this class of service.
In short

Read cpu.stat in the container's cgroup first, set GOMAXPROCS to match the 2-CPU quota, then make runtime parallelism follow the quota fleet-wide and alert on throttling.

Why

The shape interviewers score: read the cgroup counters before believing a node-level graph, because a quota-bound group stalls inside an idle machine; mitigate by matching parallelism to the budget (reversible, immediate) before changing limits; then propose mechanisms that make the runtime and the alerting aware of the budget. The specific mechanism is CFS bandwidth control: quota is consumed by all threads per 100 ms period, so a runtime that sizes its thread pool from the host's core count drains a small quota in milliseconds.

Read the docs

7 Pick the strongest answer

You docker exec -it app sh into a container and, as root, run kill -9 1. The command returns without error, but PID 1 keeps running. From the host, kill -9 <host pid of that process> stops it immediately. Why the difference?

  1. The kernel protects a pid namespace's init: signals sent from inside the namespace are ignored unless the process installed a handler for them, and SIGKILL cannot have a handler; from the parent namespace SIGKILL is delivered, which is what docker stop relies on. pid_namespaces(7): the init of a namespace only receives signals from within for which it has a handler, so SIGKILL and SIGSTOP from inside are silently dropped; the parent namespace can still kill it.
  2. PID 1 always ignores SIGKILL, on the host too; only a reboot stops an init process. The host's PID 1 is immune to SIGKILL from anywhere, but a namespace init is only shielded from signals originating inside its own namespace; the parent can kill it.
  3. Inside the container you are not really root, so kill fails silently. Permission failures return EPERM ('Operation not permitted'); this kill returned success because the signal was accepted and then dropped by the init rule.
  4. kill inside a container targets the exec'd shell's own pid namespace, which is different from the app's. docker exec joins the container's existing pid namespace with setns; PID 1 there is the app, and that is exactly the process the signal was aimed at.
In short

A pid namespace's init ignores signals sent from inside its namespace unless it has a handler, but SIGKILL from the parent namespace is always delivered.

Why

A pid namespace's init has the same special status the host's PID 1 has, but scoped: the kernel drops signals from inside the namespace unless the init has a handler for them, so an entrypoint that does not handle SIGTERM cannot be stopped from within either. Signals from the parent namespace are not subject to that rule, which is how the runtime stops containers, and when the init exits the kernel SIGKILLs everything else in the namespace. The interview signal is knowing that PID 1 semantics are per namespace, and connecting it to why entrypoints must handle SIGTERM.

Read the docs

8 Quick recall

A pod restarted with nothing useful in its logs. Which file in its cgroup directory tells you whether the kernel OOM-killed it, and how many times?

In short

memory.events, in its oom_kill line.

Accepted

memory.events · memory.events oom_kill · oom_kill

Why

memory.events counts low, high, max (limit hits that forced reclaim), oom (OOM situations) and oom_kill (tasks killed); memory.events.local excludes descendants. It is the first file to read when a container restarted without an obvious cause.

9 Design round

You operate 200 bare-metal hosts (64 cores, 256 GB, NVMe) that each run one latency-critical service and a rotating set of batch jobs under systemd, no Kubernetes. Batch periodically ruins the service's p99 through CPU contention, page-cache eviction, and disk saturation. Design the cgroup layout and resource policy that protects the service, keeps batch productive, and say how you would prove it works.

  • No new hardware and no separate batch fleet; colocation is a business requirement.
  • Batch throughput may drop at most 20% versus today.
  • Everything must be expressible as systemd unit properties so config management can apply it.
In short

A strong answer puts the service and batch in separate slices, gives the service CPUWeight and MemoryLow with quotas and MemoryMax on batch, enforces I/O with a mechanism the NVMe device honours, and proves it with per-slice PSI.

A strong answer covers
  • Separates the two classes into slices (for example latency.slice and batch.slice) so limits and weights apply to the class, not to individual units.
  • Uses CPUWeight for the service (no CPUQuota on the latency-critical path) and a CPUQuota or lower weight on batch; explains why a quota on the service would add stalls.
  • Protects the service's memory with MemoryLow or MemoryMin and bounds batch with MemoryMax or MemoryHigh so batch's page cache is reclaimed first.
  • Applies IOWeight (with a scheduler or io.cost that honours it) or IOReadBandwidthMax/IOWriteBandwidthMax on batch for the NVMe device.
  • Sets TasksMax on batch so a fork or thread leak fails inside its slice.
  • Verification: per-slice cpu.pressure, memory.pressure, io.pressure and cpu.stat throttling exported; a load test that runs batch at full tilt while measuring service p99; batch completion time compared with the 20% budget; a named tradeoff and a decision.
What a strong answer does
  • design quality: Slices; weight for the service, quota or low weight for batch; MemoryLow/Min on the service with MemoryHigh/Max on batch; IOWeight or io.max; TasksMax; PSI-based verification.
  • tradeoffs: Two or more with decisions: weights vs quotas for batch predictability, MemoryMin hard guarantee vs host flexibility, IO bandwidth caps vs weights.
  • communication: Restates constraints and the 20% budget, walks through one contention event under the design, ends with the measurements and the decision.
Why

Staff-level answers treat the cgroup tree as the design surface: slices for classes, weights where predictability of the protected workload matters, quotas and ceilings on the untrusted class, memory protection in both directions, I/O enforcement that actually works on the device, and PSI as the proof. The tradeoff interviewers wait for is weights versus quotas, and MemoryLow versus MemoryMin.

Read the docs

Next lesson Performance method: USE, load average, steal time, the toolkit, profiling, and strace pitfalls
Drill · cgroups v2 and namespaces
0:00

Loading…