cgroups v2 limits by writing files
Relay’s job runner once ran an image-resize job that read a 40 MB upload into memory 30 times in parallel. The box
had no limit on it, so the kernel’s OOM killer picked a victim, and the victim was the database next to it. A
container CLI has to say “this process may use 256 MB, half a CPU and 64 processes”, and make the kernel enforce it.
--memory 256m on the command line is only a wish until something writes it where the kernel reads it.
On Linux that place is the cgroup filesystem, and writing to it is plain file I/O. This lesson follows functional core, imperative shell again: a pure function decides which files get which text, a pure parser reads what the kernel reports back, and a thin shell does the writes through a port. The tests need no Linux, because they never touch a real cgroup.
The cgroup v2 tree
Section titled “The cgroup v2 tree”A cgroup is a directory under /sys/fs/cgroup. Making a directory makes a group, and the files the kernel puts in
it are the controls. Every process belongs to exactly one group, and a group’s limits apply to the sum of everything
in it and below it.
/sys/fs/cgroup/ user.slice/ user-1000.slice/ user@1000.service/ <- systemd hands this subtree to user 1000 tsbox-web/ <- tsbox makes one group per container cgroup.procs write a pid here to move that process into the group memory.max hard memory limit in bytes, or "max" memory.swap.max swap limit in bytes memory.current what the group uses now (read only) memory.events counters, including oom_kill (read only) cpu.max "<quota> <period>" in microseconds, or "max <period>" pids.max most processes and threads, or "max"Rootless tsbox cannot write to /sys/fs/cgroup directly, because it is not root. systemd solves this with
delegation: it gives the whole user@1000.service subtree to user 1000, and the user may create groups there and
write their files. The controllers (memory, cpu, pids) must also be switched on for that subtree. Which controllers
systemd delegates depends on its version and configuration (cpu is often not delegated by default). cat the subtree’s cgroup.controllers to see what you were given. If a controller is missing, tsbox cannot
enforce that limit, and it must say so (lesson 8 returns to this).
The three limits
Section titled “The three limits”memory.maxis a byte count. Past it, the kernel reclaims memory from the group, and when that fails it kills a process in the group (the OOM kill). Writememory.swap.maxas0too. Without it, a “256 MB” container swaps to disk and the limit is soft in practice.cpu.maxis"<quota> <period>", both in microseconds. In every 100000 µs period the group may run forquotaµs of CPU time.50000 100000is half a CPU.max 100000means no limit. Keep the quota at 1000 µs (1 ms) or more: the kernel rejects very small quotas, though the cgroup-v2 document does not state the exact minimum.pids.maxcaps processes and threads together. It is what stops a fork bomb.
Each file is written as one short string. That is why the planner can be a plain function from limits to a list of
{ file, value } pairs:
interface CgroupWrite { readonly file: string readonly value: string}
const writes: readonly CgroupWrite[] = [ { file: "memory.max", value: "268435456" }, { file: "memory.swap.max", value: "0" }, { file: "cpu.max", value: "50000 100000" }, { file: "pids.max", value: "64" },]The planner is also where bad numbers must be caught. The kernel does reject -5 for memory.max, but the error
arrives as EINVAL from a write call, far from the flag that caused it. A planner that returns a
Result fails with memoryBytes must be a positive integer before anything is written.
Reading back what the kernel says
Section titled “Reading back what the kernel says”The state files are text too, and parsing them is the same job as parsing a webhook body (parse, don’t validate): the input is a string you do not control, and the output should be a typed value or an error that names the problem.
interface MemoryEvents { readonly oom: number readonly oomKill: number}
function parseCounters(text: string): ReadonlyMap<string, number> { const counters = new Map<string, number>() for (const line of text.split("\n")) { const [key, value] = line.split(" ") if (key !== undefined && value !== undefined) counters.set(key, Number(value)) } return counters}
const counters = parseCounters("low 0\nhigh 0\nmax 31\noom 1\noom_kill 1\n")const events: MemoryEvents = { oom: counters.get("oom") ?? 0, oomKill: counters.get("oom_kill") ?? 0 }memory.events is key value per line. A key the kernel adds in a later version must not break an old tsbox, so
unknown keys are ignored, and a missing key counts as 0. A line that is present but malformed is an error. The number
that matters is oom_kill: it is how tsbox knows a container exited with 137 because it hit its limit, and not
because someone sent SIGKILL. tsbox ps can then print OOMKilled instead of a bare exit code.
An fs port for the shell
Section titled “An fs port for the shell”The writes happen through a port with three methods. The real adapter is a few lines of node:fs/promises:
import { mkdir, readFile, writeFile } from "node:fs/promises"
interface FsPort { mkdir(path: string): Promise<void> write(path: string, text: string): Promise<void> read(path: string): Promise<string>}
const nodeFs: FsPort = { async mkdir(path) { await mkdir(path, { recursive: true }) }, write: (path, text) => writeFile(path, text), read: (path) => readFile(path, "utf8"),}applyLimits(dir, writes, fs) creates the directory and writes in order, and it stops at the first refusal. The order
matters twice. A limit written after the process is already inside the group lets it allocate in the gap, so the
limits come first and the cgroup.procs write comes last. And a refused write must stop everything: a cpu.max write
fails when the cpu controller was not delegated (the file does not exist, so the error is ENOENT), and continuing would start a container the caller thinks
is limited when it is not. The first draft in the exercise ignored the rejection, and that is the bug it is named for.
A test supplies the same port backed by a Map, records every call, and can be told to refuse one file. Nothing
touches the disk, which is the same idea as the fakes in fakes over monkey-patching.
Run it for real
Section titled “Run it for real”This part needs Linux with cgroups v2, so run it inside the Linux VM, not on macOS:
podman machine sshcat /proc/self/cgroupcat /sys/fs/cgroup/user.slice/user-$(id -u).slice/user@$(id -u).service/cgroup.controllersThe first line prints 0::/..., which says you are on cgroups v2. The second lists the delegated controllers. You
want memory, cpu and pids in it. Now do by hand what applyLimits does, and watch the OOM kill:
cg=/sys/fs/cgroup/user.slice/user-$(id -u).slice/user@$(id -u).service/tsbox-demomkdir "$cg"echo 67108864 > "$cg/memory.max"echo 0 > "$cg/memory.swap.max"echo "50000 100000" > "$cg/cpu.max"echo 64 > "$cg/pids.max"sh -c 'echo $$ > "$1/cgroup.procs"; exec bun -e "const keep = []; for (;;) keep.push(new Uint8Array(1 << 20).fill(1))"' sh "$cg"echo "exit code: $?"cat "$cg/memory.events"rmdir "$cg"The cgroup.procs write needs write access to that file in the common ancestor of the source and target groups. A shell
in an ssh session sits in session-N.scope under user-1000.slice, which is root-owned, so the write can fail with
EACCES. If it does, run the sh -c line through systemd-run --user --scope, or from a process already inside
user@1000.service.
Expect exit code 137 and oom_kill 1. If the echo ... > memory.max line says “No such file or directory”, the
memory controller is not enabled for that subtree, and the fix is on the systemd side, not in tsbox.
Exercise
Section titled “Exercise”Local, because the tests use the real bun:test API. Copy main.starter.ts into the Relay project from
tooling as main.ts, with the test file next to it, and run bun test.
The starter writes raw numbers (cpu.max without a period, no swap limit), lets bad values through, reads
memory.events carelessly (oom_kill is wrong), and applyLimits fires its writes without waiting and without
reporting a refusal. The tests check exact files and values, every error message, and that the write order and the
stop-at-first-failure behaviour hold against an in-memory fake.
// tsbox limits a container by writing small text files into its cgroup directory, for example// /sys/fs/cgroup/user.slice/.../user@1000.service/tsbox-<id>/. The first draft wrote the raw numbers// straight from the CLI flags: a negative --memory wrote "-5", a cpu limit of 0.5 wrote "0.5", and a failed// write was ignored, so the container ran with no limit at all and nobody noticed.// The functional core computes the writes and parses what the kernel reports; the shell does the I/O// through an injected FsPort, so tests use an in-memory fake and run on macOS.//// Rules:// - limitWrites(limits) returns Result, in this order, skipping limits that are absent:// memoryBytes -> { memory.max: "<n>" } then { memory.swap.max: "0" } (no swap: the limit must be hard)// cpuQuota -> { cpu.max: "<quota> 100000" } (quota in microseconds per 100 ms period)// pids -> { pids.max: "<n>" }// errors: "memoryBytes must be a positive integer", "cpuQuota must be an integer >= 1000",// "pids must be a positive integer". Checked in that order.// - procsWrite(pid) is { cgroup.procs: "<pid>" }.// - parseCpuMax("max 100000\n") -> { quotaUs: null, periodUs: 100000 }; "50000 100000" -> quotaUs 50000.// Anything else (wrong field count, non-numbers, zero) is the error `bad cpu.max: <trimmed text>`.// - parseMemoryEvents(text): lines "key value"; keys low, high, max, oom, oom_kill (a missing key is 0,// unknown keys are ignored). A malformed line is the error `bad memory.events line: <line>`.// - applyLimits(dir, writes, fs): mkdir dir, then write `${dir}/${file}` for each write in order. Stop at// the first failure and return { file, message } (file is the write's file name, or dir for mkdir).// - readUsage(dir, fs): memory.current (a number) and memory.events, as { memoryCurrent, events };// a bad memory.current is the error "bad memory.current".export type Result<T, E> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: E }
export interface Limits { readonly memoryBytes?: number readonly cpuQuota?: number readonly pids?: number}
export interface CgroupWrite { readonly file: string readonly value: string}
export const CPU_PERIOD_US = 100_000
export function limitWrites(limits: Limits): Result<readonly CgroupWrite[], string> { const writes: CgroupWrite[] = [] if (limits.memoryBytes !== undefined) writes.push({ file: "memory.max", value: String(limits.memoryBytes) }) if (limits.cpuQuota !== undefined) writes.push({ file: "cpu.max", value: String(limits.cpuQuota) }) if (limits.pids !== undefined) writes.push({ file: "pids.max", value: String(limits.pids) }) return { ok: true, value: writes }}
export const procsWrite = (pid: number): CgroupWrite => ({ file: "cgroup.procs", value: String(pid) })
export interface CpuMax { readonly quotaUs: number | null readonly periodUs: number}
export function parseCpuMax(text: string): Result<CpuMax, string> { const [quota, period] = text.trim().split(" ") return { ok: true, value: { quotaUs: Number(quota), periodUs: Number(period) } }}
export interface MemoryEvents { readonly low: number readonly high: number readonly max: number readonly oom: number readonly oomKill: number}
export function parseMemoryEvents(text: string): Result<MemoryEvents, string> { const counts = new Map<string, number>() for (const line of text.split("\n")) { const [key, raw] = line.split(" ") if (key !== undefined) counts.set(key, Number(raw)) } return { ok: true, value: { low: counts.get("low") ?? 0, high: counts.get("high") ?? 0, max: counts.get("max") ?? 0, oom: counts.get("oom") ?? 0, oomKill: counts.get("oom") ?? 0, }, }}
export interface FsPort { mkdir(path: string): Promise<void> write(path: string, text: string): Promise<void> read(path: string): Promise<string>}
export type ApplyError = { readonly file: string; readonly message: string }
export async function applyLimits( dir: string, writes: readonly CgroupWrite[], fs: FsPort,): Promise<Result<void, ApplyError>> { await fs.mkdir(dir) for (const write of writes) void fs.write(`${dir}/${write.file}`, write.value).catch(() => {}) return { ok: true, value: undefined }}
export interface Usage { readonly memoryCurrent: number readonly events: MemoryEvents}
export async function readUsage(dir: string, fs: FsPort): Promise<Result<Usage, string>> { const memoryCurrent = Number(await fs.read(`${dir}/memory.current`)) const events = parseMemoryEvents(await fs.read(`${dir}/memory.events`)) if (!events.ok) return events return { ok: true, value: { memoryCurrent, events: events.value } }}import { expect, test } from "bun:test"import { applyLimits, limitWrites, parseCpuMax, parseMemoryEvents, procsWrite, readUsage } from "./main.ts"import type { FsPort } from "./main.ts"
function fakeFs(files: Record<string, string> = {}, refuse: readonly string[] = []) { const calls: string[] = [] const store = new Map(Object.entries(files)) const fs: FsPort = { async mkdir(path) { calls.push(`mkdir ${path}`) }, async write(path, text) { calls.push(`write ${path} ${text}`) if (refuse.some((suffix) => path.endsWith(suffix))) throw new Error(`EACCES: ${path}`) store.set(path, text) }, async read(path) { const text = store.get(path) if (text === undefined) throw new Error(`ENOENT: ${path}`) return text }, } return { fs, calls, store }}
test("limitWrites turns limits into files, memory first, with swap off", () => { expect(limitWrites({ memoryBytes: 268435456, cpuQuota: 50000, pids: 64 })).toEqual({ ok: true, value: [ { file: "memory.max", value: "268435456" }, { file: "memory.swap.max", value: "0" }, { file: "cpu.max", value: "50000 100000" }, { file: "pids.max", value: "64" }, ], })})
test("limitWrites skips absent limits and accepts none", () => { expect(limitWrites({})).toEqual({ ok: true, value: [] }) expect(limitWrites({ pids: 8 })).toEqual({ ok: true, value: [{ file: "pids.max", value: "8" }] }) expect(limitWrites({ cpuQuota: 1000 })).toEqual({ ok: true, value: [{ file: "cpu.max", value: "1000 100000" }] })})
test("limitWrites rejects values the kernel would misread", () => { expect(limitWrites({ memoryBytes: -5 })).toEqual({ ok: false, error: "memoryBytes must be a positive integer" }) expect(limitWrites({ memoryBytes: 0 })).toEqual({ ok: false, error: "memoryBytes must be a positive integer" }) expect(limitWrites({ memoryBytes: 1.5 })).toEqual({ ok: false, error: "memoryBytes must be a positive integer" }) expect(limitWrites({ cpuQuota: 0.5 })).toEqual({ ok: false, error: "cpuQuota must be an integer >= 1000" }) expect(limitWrites({ cpuQuota: 999 })).toEqual({ ok: false, error: "cpuQuota must be an integer >= 1000" }) expect(limitWrites({ pids: 0 })).toEqual({ ok: false, error: "pids must be a positive integer" }) expect(limitWrites({ pids: Number.NaN })).toEqual({ ok: false, error: "pids must be a positive integer" }) expect(limitWrites({ memoryBytes: -1, pids: 0 })).toEqual({ ok: false, error: "memoryBytes must be a positive integer" })})
test("procsWrite names the pid file", () => { expect(procsWrite(4242)).toEqual({ file: "cgroup.procs", value: "4242" })})
test("parseCpuMax reads a quota or max", () => { expect(parseCpuMax("50000 100000\n")).toEqual({ ok: true, value: { quotaUs: 50000, periodUs: 100000 } }) expect(parseCpuMax("max 100000\n")).toEqual({ ok: true, value: { quotaUs: null, periodUs: 100000 } })})
test("parseCpuMax rejects anything else", () => { for (const bad of ["", "max", "50000", "1 2 3", "abc 100000", "50000 0", "0 100000", "-1 100000", "50000 1e5x"]) { expect(parseCpuMax(`${bad}\n`)).toEqual({ ok: false, error: `bad cpu.max: ${bad}` }) }})
test("parseMemoryEvents reads the counters, defaulting missing keys to 0", () => { const text = "low 0\nhigh 2\nmax 31\noom 1\noom_kill 1\n" expect(parseMemoryEvents(text)).toEqual({ ok: true, value: { low: 0, high: 2, max: 31, oom: 1, oomKill: 1 } }) expect(parseMemoryEvents("oom_kill 3\nfuture_counter 9\n")).toEqual({ ok: true, value: { low: 0, high: 0, max: 0, oom: 0, oomKill: 3 }, }) expect(parseMemoryEvents("")).toEqual({ ok: true, value: { low: 0, high: 0, max: 0, oom: 0, oomKill: 0 } })})
test("parseMemoryEvents rejects a malformed line", () => { expect(parseMemoryEvents("low 0\noom_kill x\n")).toEqual({ ok: false, error: "bad memory.events line: oom_kill x" }) expect(parseMemoryEvents("oom_kill\n")).toEqual({ ok: false, error: "bad memory.events line: oom_kill" }) expect(parseMemoryEvents("oom_kill -1\n")).toEqual({ ok: false, error: "bad memory.events line: oom_kill -1" })})
test("applyLimits creates the directory, then writes in order", async () => { const { fs, calls } = fakeFs() const writes = limitWrites({ memoryBytes: 1048576, pids: 16 }) if (!writes.ok) throw new Error(writes.error) const done = await applyLimits("/cg/tsbox-a", [...writes.value, procsWrite(77)], fs) expect(done).toEqual({ ok: true, value: undefined }) expect(calls).toEqual([ "mkdir /cg/tsbox-a", "write /cg/tsbox-a/memory.max 1048576", "write /cg/tsbox-a/memory.swap.max 0", "write /cg/tsbox-a/pids.max 16", "write /cg/tsbox-a/cgroup.procs 77", ])})
test("applyLimits stops at the first refused write and says which file", async () => { const { fs, calls } = fakeFs({}, ["cpu.max"]) const done = await applyLimits( "/cg/x", [ { file: "memory.max", value: "1048576" }, { file: "cpu.max", value: "50000 100000" }, { file: "pids.max", value: "8" }, ], fs, ) expect(done).toEqual({ ok: false, error: { file: "cpu.max", message: "EACCES: /cg/x/cpu.max" } }) expect(calls).toEqual(["mkdir /cg/x", "write /cg/x/memory.max 1048576", "write /cg/x/cpu.max 50000 100000"])})
test("applyLimits reports a failed mkdir with the directory", async () => { const fs: FsPort = { async mkdir() { throw new Error("EACCES: /cg") }, async write() {}, async read() { return "" }, } expect(await applyLimits("/cg", [{ file: "pids.max", value: "8" }], fs)).toEqual({ ok: false, error: { file: "/cg", message: "EACCES: /cg" }, })})
test("readUsage combines memory.current and memory.events", async () => { const { fs } = fakeFs({ "/cg/a/memory.current": "73728\n", "/cg/a/memory.events": "low 0\nhigh 0\nmax 4\noom 1\noom_kill 1\n", }) expect(await readUsage("/cg/a", fs)).toEqual({ ok: true, value: { memoryCurrent: 73728, events: { low: 0, high: 0, max: 4, oom: 1, oomKill: 1 } }, })})
test("readUsage reports bad input instead of NaN", async () => { const bad = fakeFs({ "/cg/a/memory.current": "lots\n", "/cg/a/memory.events": "" }) expect(await readUsage("/cg/a", bad.fs)).toEqual({ ok: false, error: "bad memory.current" }) const badEvents = fakeFs({ "/cg/a/memory.current": "1\n", "/cg/a/memory.events": "max x\n" }) expect(await readUsage("/cg/a", badEvents.fs)).toEqual({ ok: false, error: "bad memory.events line: max x" })})- A cgroup is a directory, and a limit is one short string written to one file. Rootless tsbox works inside the subtree systemd delegates.
memory.maxplusmemory.swap.max0,cpu.maxasquota period,pids.max: plan them as data with a function that returns aResult.- Parse
memory.eventsinto numbers, ignore unknown keys, and useoom_killto tell an OOM kill from a signal. - Write the limits first and
cgroup.procslast, stop at the first refused write, and never start a container whose limits failed. - Inject the filesystem so the whole thing is tested without Linux.
Further reading
Section titled “Further reading”- Control Group v2 (Linux kernel): controllers, delegation and the memory, cpu and pids files.