Skip to content
systemcoding.dev
Virtualization

Limit Memory and CPU With cgroups v2

Create a cgroup v2 directory, write memory.max and cpu.max, move a shell into it and watch the kernel cap memory and CPU time. Commands and output included.

6 min read
Summarize in AI
Flat illustration of guest machines running on a hypervisor over hardware, with the QEMU, Linux and Docker logos.

Control groups are the half of a container that says how much, where namespaces say what you can see. On a modern distribution, the version you get is cgroup v2: a single hierarchy mounted at /sys/fs/cgroup, controlled by writing numbers into files. This post creates a group by hand, caps its memory at 100 MiB, caps its CPU at half a core, moves a shell into it and watches both limits bite. It assumes Linux 6.12 with systemd 256 and the unified hierarchy, which is the default on current Debian, Ubuntu, Fedora and Arch. You need root for the file edits, and nothing here survives a reboot.

Check that you are on cgroup v2

The filesystem type of /sys/fs/cgroup tells you which version the machine runs.

Shell
stat -fc %T /sys/fs/cgroup
cat /sys/fs/cgroup/cgroup.controllers
Text
cgroup2fs
cpuset cpu io memory hugetlb pids rdma misc

cgroup2fs means v2. A machine on the old layout prints tmpfs, with a directory per controller below it. The second line lists the controllers the kernel makes available at the root; yours may have a few more or fewer entries. We need cpu and memory.

Create a group and enable the controllers

A cgroup is a directory. Make one under the root, and the kernel fills it with control files.

Shell
sudo mkdir /sys/fs/cgroup/demo
ls /sys/fs/cgroup/demo | head -n 8
Text
cgroup.controllers
cgroup.events
cgroup.freeze
cgroup.kill
cgroup.max.depth
cgroup.max.descendants
cgroup.procs
cgroup.stat

A new group only gets the memory.* and cpu.* files when its parent has enabled those controllers for its children through cgroup.subtree_control. On a systemd machine the root already delegates the common ones, but it is cheap to be explicit.

Shell
echo "+cpu +memory" | sudo tee /sys/fs/cgroup/cgroup.subtree_control
cat /sys/fs/cgroup/demo/cgroup.controllers
Text
+cpu +memory
cpu memory

The + prefix enables a controller and - disables it. Changing the root's subtree_control on a live system is fine for an experiment, but on a host where systemd manages everything, prefer a transient unit (see the end of this post) because systemd may rewrite what you set.

Cap memory at 100 MiB

The memory limits live in memory.max (a hard limit that triggers reclaim and eventually the OOM killer) and memory.high (a soft throttle point). Set the hard limit to 100 MiB, which is 104,857,600 bytes.

Shell
echo 104857600 | sudo tee /sys/fs/cgroup/demo/memory.max
echo 0 | sudo tee /sys/fs/cgroup/demo/memory.swap.max
cat /sys/fs/cgroup/demo/memory.max
Text
104857600
0
104857600

Setting memory.swap.max to 0 stops the group from escaping into swap, which would hide the limit. The value max means no limit, and it is the default.

Cap CPU at half a core

The cpu.max file takes two numbers, a quota and a period, both in microseconds. A group may run for quota microseconds in every period. Half a core is 50,000 out of 100,000.

Shell
echo "50000 100000" | sudo tee /sys/fs/cgroup/demo/cpu.max
cat /sys/fs/cgroup/demo/cpu.max
Text
50000 100000
50000 100000

The kernel throttles the group when it spends its quota early in the period, so a busy process in the group shows about 50 percent of one CPU instead of 100 percent. The related file cpu.weight is not a limit: it sets a relative share, from 1 to 10000, that only matters when the CPUs are contended.

Move a shell into the group

A process joins a cgroup when its PID is written to cgroup.procs. Start a shell that moves itself.

Shell
sudo bash -c 'echo $$ > /sys/fs/cgroup/demo/cgroup.procs; cat /proc/self/cgroup'
Text
0::/demo

The line has the form hierarchy-ID:controller-list:path. On v2 the ID is always 0 and the controller list is empty. Everything the shell forks from now on inherits the group, so you can run test programs from inside it.

Watch the memory limit bite

This C program allocates and touches memory in 10 MiB steps and reports how far it got before the kernel stopped it.

hog.cc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    const size_t step = 10u * 1024 * 1024;
    for (int i = 1; ; i++) {
        char *p = malloc(step);
        if (!p) { printf("malloc failed at %d MiB\n", (i - 1) * 10); return 1; }
        memset(p, 1, step);
        printf("touched %d MiB\n", i * 10);
        fflush(stdout);
    }
}

Compile it with gcc -O2 hog.c -o hog and run it from inside the group.

Shell
sudo bash -c 'echo $$ > /sys/fs/cgroup/demo/cgroup.procs; ./hog'
Text
touched 10 MiB
touched 20 MiB
touched 30 MiB
touched 40 MiB
touched 50 MiB
touched 60 MiB
touched 70 MiB
touched 80 MiB
touched 90 MiB
Killed

The program is killed by the kernel's OOM killer, not by malloc returning NULL: Linux overcommits virtual memory, so malloc succeeds and the limit is enforced when pages are touched. The kill happens somewhere near the 100 MiB mark, a little before it, because the group also pays for the program's own pages and the page cache it used to load the binary. Your last printed number may differ by one step. Confirm what happened.

Shell
cat /sys/fs/cgroup/demo/memory.events
Text
low 0
high 0
max 28
oom 1
oom_kill 1
oom_group 0

max 28 counts the times the group hit its limit and reclaim had to run, and oom_kill 1 says one process was killed. The exact max count varies from run to run.

Watch the CPU limit bite

Burn CPU inside the group and look at it from outside.

Shell
sudo bash -c 'echo $$ > /sys/fs/cgroup/demo/cgroup.procs; timeout 10 sh -c "while :; do :; done"' &
sleep 5
top -b -n 1 | grep -m 1 sh
Text
 8421 root      20   0    2892   1024    924 R  50.0   0.0   0:02.51 sh

A busy loop alone would show 100 percent. The group's quota holds it near 50. The PID will differ. cpu.stat in the group directory accumulates nr_throttled and throttled_usec, which tell you how often and how long the kernel held it back.

The systemd way, and cleanup

Writing into /sys/fs/cgroup by hand is right for learning and wrong for services. On a systemd host, ask systemd to create the group, which also keeps it from being overwritten.

Shell
sudo systemd-run --scope -p MemoryMax=100M -p CPUQuota=50% ./hog

MemoryMax maps to memory.max and CPUQuota maps to cpu.max. To remove the manual group, make sure it is empty and delete the directory: sudo rmdir /sys/fs/cgroup/demo. A cgroup with live processes refuses removal with "Device or resource busy".

Common mistakes with the limit files

A few failures account for most confusion when you write these files by hand. Writing a value above what the parent allows does not fail: the child's limit is simply never reached, because the parent's limit applies to the whole subtree, so check the ancestors with cat ../memory.max when a limit seems to have no effect. Writing +memory to a group that already holds processes fails with Device or resource busy, a rule the cgroup v2 hierarchy post in this series explains. Reading memory.current after the program exits shows a smaller number than at its peak, so use memory.peak, available since Linux 5.19, to see the high-water mark.

Shell
cat /sys/fs/cgroup/demo/memory.peak
cat /sys/fs/cgroup/demo/memory.stat | head -n 4
Text
104857600
anon 98304000
file 5242880
kernel 1310720

The peak sits at the limit, because the program hit it, and the breakdown shows the group's usage split into anonymous memory, file cache and kernel structures. Your numbers will differ. To lift a limit, write the word max to memory.max or cpu.max. To use memory.high as a gentler brake, set it a little below memory.max: the kernel then throttles and reclaims once the group crosses it instead of killing anything, which suits services that you would rather slow down than lose.

Also inKernels
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.