TExcelTAD
Home › Linux Server Administration › cgroups v2 & Resource Limits

cgroups v2 & Resource Limits

Control groups (cgroups) are the kernel feature that groups processes and limits, prioritises and accounts their CPU, memory, I/O and process count. Every container runtime is built on them, and so is systemd: every service, every user session, every container lives in its own cgroup. Current distributions (Ubuntu since 21.10, RHEL 9, Debian 11+) use the unified cgroup v2 hierarchy, mounted at /sys/fs/cgroup. You rarely touch those files directly; you set limits in unit files and systemd writes them.

The tree

systemd arranges cgroups in slices: system.slice for services, user.slice for logins, machine.slice for VMs and containers. On a server (sample session):

bash
$ systemd-cgls --no-pager | head -12
Control group /:
-.slice
├─user.slice
│ └─user-1000.slice
│   ├─user@1000.service …
│   └─session-4.scope
│     ├─5120 sshd: ada [priv]
│     └─5133 -bash
└─system.slice
  ├─inventory.service
  │ └─4182 /opt/inventory/bin/inventory serve
  ├─nginx.service
$ systemd-cgtop -n 1 -b --depth=2 | head -5
Control Group                    Tasks   %CPU   Memory  Input/s Output/s
/                                  214   41.2     2.6G        -        -
system.slice                       118   38.7     2.1G        -        -
system.slice/inventory.service      14   31.0   712.4M        -        -
system.slice/postgresql@16-main.service   9    6.2   980.1M        -        -
$ cat /sys/fs/cgroup/system.slice/inventory.service/memory.max
2147483648

Inside a container you see a namespaced view: the container's own cgroup appears as the root. The sandbox is such a container:

bash · try it yourself
cat /proc/self/cgroup
echo "controllers: $(cat /sys/fs/cgroup/cgroup.controllers)"
0::/
controllers: cpuset cpu io memory hugetlb pids rdma misc

0::/ is the cgroup v2 format (hierarchy 0, no controller list, path / as seen from inside). The controllers listed are the ones available to this cgroup: CPU, memory, I/O, process count and a few more.

Limits in unit files

Setting Controller file Effect
CPUWeight=200 cpu.weight relative share under contention (default 100); no effect on an idle machine
CPUQuota=150% cpu.max hard cap: 1.5 CPUs worth of time per period, even if the machine is idle
MemoryHigh=1500M memory.high soft limit: above it, the service is throttled and reclaimed hard
MemoryMax=2G memory.max hard limit: the OOM killer acts inside the service (Memory & the OOM Killer)
MemorySwapMax=0 memory.swap.max no swap for this service
IOWeight=50 io.weight relative disk share (needs an I/O scheduler that supports it, e.g. BFQ)
IOReadBandwidthMax=/dev/nvme1n1 50M io.max cap on throughput per device
TasksMax=512 pids.max at most 512 processes/threads: stops fork bombs and thread leaks

Mistakes in these lines are silently ignored like any other bad unit setting, so verify them (systemd Units):

bash · try it yourself
cat > reports.service <<'EOF'
[Service]
ExecStart=/usr/bin/sleep infinity
CPUWeight=50
CPUQuota=150%
MemoryHigh=1500M
MemoryMax=2GB
MemoryLimit=2G
TasksMax=512
IOWeight=fast
EOF
systemd-analyze verify ./reports.service
/home/learner/reports.service:6: Invalid memory limit '2GB', ignoring: Invalid argument
/home/learner/reports.service:7: Unit uses MemoryLimit=; please use MemoryMax= instead. Support for MemoryLimit= will be removed soon.
/home/learner/reports.service:9: Invalid weight, ignoring: fast

2GB is not a unit systemd knows (it accepts K, M, G, T with base 1024, or a percentage of RAM such as MemoryMax=40%), MemoryLimit= is the old cgroup v1 name, and a weight must be a number from 1 to 10000.

Applying limits on a live system

Limits can be changed at run time, with or without a unit file (sample sessions):

bash
$ sudo systemctl set-property inventory.service MemoryMax=2G CPUQuota=150%   # persists as a drop-in
$ sudo systemctl set-property --runtime nginx.service CPUWeight=500           # until reboot
$ systemctl show inventory -p MemoryMax -p CPUQuotaPerSecUSec -p MemoryCurrent
MemoryMax=2147483648
CPUQuotaPerSecUSec=1.500000s
MemoryCurrent=747126784
$ sudo systemd-run --unit=reindex -p MemoryMax=1G -p CPUQuota=50% -p Nice=10 /opt/inventory/bin/reindex
Running as unit: reindex.service; invocation ID: 2bb7a11c41c94ef1a09f1a1f0e5a5c3c
$ systemd-run --user --scope -p MemoryMax=500M make -j8         # a limited shell command as your own user

systemd-run is the quickest way to run a one-off heavy job (a reindex, a large import, a backup) without letting it starve the services on the same machine.

How a CPU quota behaves

CPUQuota=50% becomes cpu.max = 50000 100000: in every 100 ms period the group may use 50 ms of CPU time (across all its threads), then it is throttled until the next period. A model of a request that needs 120 ms of CPU, under different quotas:

python · try it yourself
def run(cpu_needed_ms, quota_ms, period_ms=100, threads=1):
    """Wall-clock time to finish when the cgroup gets quota_ms of CPU per period."""
    done, wall, throttled = 0.0, 0, 0
    while done < cpu_needed_ms:
        budget = quota_ms if quota_ms else period_ms * threads
        use = min(budget, period_ms * threads, cpu_needed_ms - done)
        done += use
        if done < cpu_needed_ms:
            wall += period_ms
            if use == budget and quota_ms:
                throttled += 1
        else:
            wall += use / threads
    return wall, throttled

for label, quota, threads in [("no quota, 1 thread", None, 1), ("CPUQuota=200%, 1 thread", 200, 1),
                              ("CPUQuota=50%, 1 thread", 50, 1), ("CPUQuota=50%, 4 threads", 50, 4),
                              ("CPUQuota=200%, 4 threads", 200, 4)]:
    wall, thr = run(120, quota, threads=threads)
    print(f"{label:<26} -> {wall:6.1f} ms wall clock, throttled in {thr} period(s)")
no quota, 1 thread         ->  120.0 ms wall clock, throttled in 0 period(s)
CPUQuota=200%, 1 thread    ->  120.0 ms wall clock, throttled in 0 period(s)
CPUQuota=50%, 1 thread     ->  220.0 ms wall clock, throttled in 2 period(s)
CPUQuota=50%, 4 threads    ->  205.0 ms wall clock, throttled in 2 period(s)
CPUQuota=200%, 4 threads   ->   30.0 ms wall clock, throttled in 0 period(s)

A quota above what one thread can use (200% for a single-threaded request) costs nothing. A tight quota turns a 120 ms request into a 220 ms one, and a multi-threaded app burns its quota in the first milliseconds of each period and then waits: the latency cost of CPU limits that Kubernetes users meet as "CPU throttling". Weights (CPUWeight=) only act under contention and never add latency on an idle machine, which is why many teams prefer weights (or Kubernetes requests without limits) for latency-sensitive services. On a live system, cpu.stat shows nr_throttled and throttled_usec.

Test yourself

What is the difference between CPUWeight= and CPUQuota=?

  1. None
  2. Weight is a relative share that matters only under contention; Quota is a hard cap that applies even when the CPU is idle
  3. Quota is relative, Weight is absolute
  4. Weight only works with cgroups v1

Why is MemoryMax=2GB in a unit file a problem?

  1. 2 GB is too small
  2. systemd doesn't understand the suffix GB; the line is ignored with a warning, so the service has no limit
  3. MemoryMax needs bytes
  4. It needs MemoryHigh too

How do you run a one-off heavy job with a memory and CPU cap on a systemd server?

  1. nice -n 19
  2. systemd-run -p MemoryMax=1G -p CPUQuota=50% <command>
  3. ulimit -v
  4. taskset