LINUXMIND.DEVTHE GNU/LINUX WORLD

cgroups v2 on Linux: cap CPU, memory and I/O for real

Ilustracion editorial plana de contenedores anidados con cajas abstractas y medidores que marcan un limite de recursos

Sooner or later every Linux user meets the same problem: one process decides it wants the whole machine. A browser with too many tabs, a build job that spawns twenty compilers, a container that quietly grows until the kernel’s out-of-memory killer steps in and takes down something you cared about. For years the answer was a pile of ulimit and nice tricks that controlled a process, not a group. On any modern distribution the real answer is cgroups v2, and you almost never touch it directly — you reach it through systemd, which speaks it fluently.

This guide is the practical tour: what cgroups v2 is, the two kinds of limit it offers, and how to cap CPU, memory and I/O for a service, a slice or a whole user session without writing anything to /sys by hand.

What cgroups v2 actually is

A control group is a named set of processes that the kernel treats as a unit for resource accounting and enforcement. Every process on your system belongs to exactly one cgroup, and the groups form a single tree that starts at the root. When you put a limit on a group, the kernel applies it to the sum of everything inside it — so the natural unit of control is “this service and all the processes it spawns”, not “this one PID”.

The “v2” matters. The first version, cgroup v1, exposed a separate hierarchy per controller — one tree for CPU, another for memory, another for I/O — which made the rules inconsistent and the accounting impossible to reason about. cgroups v2 puts every controller in a single unified hierarchy, so a process has one place in the tree and every limit lives on the same node. Modern systemd requires it, and on any distribution from the last few years it is what you already have. Check with one command:

mount | grep cgroup2
stat -fc %T /sys/fs/cgroup

If the first line shows a cgroup2 mount and the second prints cgroup2fs, you are on the unified hierarchy and everything below applies.

The two kinds of limit: caps and weights

Every controller offers two distinct kinds of control, and confusing them is the most common mistake.

Kind What it does systemd property
Hard cap An absolute ceiling. The group never exceeds it, no matter how idle the rest of the system is. CPUQuota, MemoryMax, IOReadBandwidthMax
Weight A relative share. Only matters when there is contention; an idle system gives the group all the spare capacity. CPUWeight, IOWeight

Use a cap when a process must never be allowed to take more than a fixed amount. Use a weight when you want to say “this matters more than that” without starving anything. Most real configurations use both: a weight to prioritise, and a cap to draw a line the kernel will not cross.

The systemd way: set properties, not files

You can write directly to files like /sys/fs/cgroup/.../memory.max, and it works, but the settings vanish on reboot and systemd will overwrite them the next time it reconfigures the unit. The supported path is to let systemd own the cgroup and set the limit on the unit. There are two ways to do it.

The quick way changes a running unit immediately and remembers it in a drop-in:

sudo systemctl set-property nginx.service CPUQuota=50% MemoryMax=512M

The durable way is to edit the unit and add a drop-in override, which is what you want for anything permanent:

sudo systemctl edit nginx.service

That opens an editor with an empty [Service] section. Add your limits there, save, then reload and restart:

[Service]
CPUQuota=50%
MemoryHigh=384M
MemoryMax=512M
IOWeight=50
sudo systemctl daemon-reload
sudo systemctl restart nginx.service
systemctl show nginx.service --property=CPUQuota,MemoryMax,IOWeight

systemctl show prints the effective values, which is how you confirm the kernel actually took them and you did not fat-finger a unit name.

Capping the CPU

CPU control is where the two kinds of limit are easiest to see. CPUQuota is a hard cap expressed as a percentage of one core: 50% is half a core, 200% is two full cores’ worth of time. CPUWeight is the relative share, a number from 1 to 10000 where the default is 100.

[Service]
CPUQuota=200%          # never more than two cores
CPUWeight=200          # twice the default share under contention
AllowedCPUs=0-3        # pin the service to cores 0 through 3

A build service that must not freeze your desktop gets a CPUQuota of, say, 300% on a machine with more cores than that, so it can burst but never monopolise. AllowedCPUs goes further and pins the group to a set of cores, which is the blunt but effective way to keep a batch job off the cores your interactive work runs on.

Capping memory, and why the pair matters

Memory has two levers, and the difference between them is the difference between slowing a process and killing it. MemoryHigh is a soft limit: past it, the kernel throttles the group hard and pushes it into reclaim, but nothing dies. MemoryMax is the hard limit: past it, the kernel reclaims, then the OOM killer fires inside the group, so it takes out the offending service instead of whatever it happens to be sharing the machine with.

[Service]
MemoryHigh=384M        # throttle here
MemoryMax=512M         # kill here
MemorySwapMax=0        # do not let it escape into swap

MemorySwapMax=0 is the setting that makes the cap real. Without it a group can push its memory into swap and sail past MemoryMax in spirit while staying under it on paper, trading a crash for a slow, thrashing machine. For a service you would rather see fail fast than drag the system down, zero swap is the honest choice.

Limiting I/O

The I/O controller mirrors the CPU one: IOWeight is the relative share, and the bandwidth and IOPS properties are hard caps — but unlike CPU and memory, I/O limits are per block device, named by its path.

[Service]
IOWeight=50
IOReadBandwidthMax=/dev/nvme0n1 50M
IOWriteBandwidthMax=/dev/nvme0n1 30M
IOReadIOPSMax=/dev/nvme0n1 1000
IOWriteIOPSMax=/dev/nvme0n1 500

This is how you stop a backup or a database from saturating your only SSD and making everything else wait. Set IOWeight low on the heavy job, or cap its bandwidth, and your interactive work keeps its I/O responsiveness.

Capping processes, not resources

One more limit belongs in the same toolkit, because it protects against a different failure: a fork bomb. TasksMax caps the number of processes and threads a group may contain, and once the group is at the limit, further fork() calls simply fail.

[Service]
TasksMax=512

A runaway service that would otherwise fill the process table and lock out logins hits the ceiling and stops multiplying. It is a one-line insurance policy on anything that spawns children.

Slices: limits for a whole family of services

Setting limits per service is fine, but sometimes you want to cap a group of services together — everything belonging to a workload, or to a user. That is what a slice is: a cgroup that holds other units. systemd already arranges units into slices (system.slice, user.slice), and you can define your own:

# /etc/systemd/system/batch.slice
[Unit]
Description=Slice for batch workloads
Before=slices.target

[Slice]
CPUQuota=400%
MemoryHigh=6G
MemoryMax=8G
IOWeight=50
sudo systemctl daemon-reload
sudo systemctl start batch.slice

Then point a service at it by name in its unit file:

[Service]
Slice=batch.slice

The service inherits every limit from the slice, and the slice’s totals are enforced across all of them. This is the clean way to say “all my background jobs together may use at most eight gigabytes”, which is the limit you actually want when the jobs are many and individually modest.

Limiting a user session

The same machinery protects a shared machine. Every logged-in user runs under a user-<uid>.slice, and you can put limits on it through the drop-in at /etc/systemd/system/user-.slice.d/:

# /etc/systemd/system/user-1000.slice.d/limits.conf
[Slice]
MemoryMax=4G
CPUQuota=200%
sudo systemctl daemon-reload

This is a quiet superpower on a multi-user box or a remote workstation: no single account, however careless, can starve the others. The rules follow the account, not a particular process, so a runaway editor is contained the same way a runaway script is.

Watching what the kernel is doing

Once limits are set, two systemd tools let you see the tree and the live usage. systemd-cgls prints the hierarchy as a tree so you can see which process ended up in which group; systemd-cgtop is a live view, like top, but sorted by cgroup instead of by process:

systemd-cgls /system.slice
systemd-cgtop

When a group hits MemoryMax, the kernel records it, and that record is the first place to look when a service dies unexpectedly:

cat /sys/fs/cgroup/system.slice/nginx.service/memory.events
cat /sys/fs/cgroup/system.slice/nginx.service/memory.current

memory.events counts how many times the group crossed high, hit max and triggered the OOM killer. If that number is climbing, the limit is too tight — or the service has a leak, and the limit is doing exactly its job.

The mistakes that catch everyone once

  • Writing to /sys/fs/cgroup directly. It works until the next reload or reboot. Set limits through systemd, always.
  • Confusing MemoryHigh with MemoryMax. One throttles, the other kills. Set both if you want a warning zone before the wall.
  • Forgetting daemon-reload. A new or edited slice is invisible to systemd until you run it.
  • Reading CPUQuota as a share of the whole machine. It is a share of one core, so 100% is one core no matter how many the box has.
  • Leaving swap unbounded. Without MemorySwapMax a memory cap is a suggestion the group can defer by swapping.

What changes for you

You do not need to become a kernel engineer to use cgroups v2. The practical version is three properties — CPUQuota, MemoryMax, IOWeight — set on the right unit, plus systemd-cgtop to watch them. That is enough to stop a build job from freezing your desktop, to stop one service from OOM-killing its neighbours, and to keep a shared machine fair. The kernel was always capable of this; systemd just gave it a syntax you can remember. Once you have written your first drop-in, a runaway process stops being an emergency and becomes a line you set once.

Sources




Leave a Reply

Your email address will not be published. Required fields are marked *