To put firm CPU and memory limits on a Linux service, set them with systemctl set-property, which applies the change right away and keeps it across reboots. Behind that command sits cgroup v2, version 2 of Linux control groups, the kernel feature that decides how much of each resource a process may take. This article is for anyone running services on a server that uses systemd. If you have had a week where one runaway process ate all the memory and the whole host stopped answering, a memory ceiling and a CPU quota on that service are what prevent the next one. The sections below show how to check that your system uses cgroup v2, read the limits a service has now, set new ones, and avoid the settings that look right but do not hold.
How to verify
Confirm cgroup v2 is the active hierarchy, find a service’s cgroup, and inspect its current limits and usage:
# Unified (v2) or hybrid?
mount | grep cgroup
stat -fc %T /sys/fs/cgroup/ # cgroup2fs = pure v2
# Where does a process live?
cat /proc/self/cgroup
# 0::/user.slice/user-1000.slice/session-2.scope
# Inspect a systemd service
systemctl status nginx | head -5
ls /sys/fs/cgroup/system.slice/nginx.service/
cat /sys/fs/cgroup/system.slice/nginx.service/memory.current
cat /sys/fs/cgroup/system.slice/nginx.service/cpu.stat
If stat -fc %T returns tmpfs, the host is on hybrid mode (v1 controllers mounted under v2). Modern Debian, Ubuntu 22.04+, Fedora 33+, and RHEL 9 all default to pure v2.
What’s happening
cgroup v1 had one hierarchy per controller — separate trees for cpu, memory, blkio, etc., and a process could land in different positions across them. The mismatch produced subtle bugs (CPU and memory limits stacked under different parents), and the implementation was a maintenance burden. cgroup v2 is a single unified hierarchy: every process has exactly one cgroup, and you enable individual controllers per subtree.
The interface is the cgroup filesystem (/sys/fs/cgroup/). Each directory is a cgroup; the files inside are the controllers’ knobs:
cgroup.procs— the PIDs in this cgroup (write a PID here to move it in)cgroup.subtree_control— which controllers are enabled for this cgroup’s childrencpu.max— CPU bandwidth limit (<quota> <period>)cpu.weight— relative share when there’s contention (default 100, range 1-10000)memory.max— hard memory limitmemory.high— soft pressure limit (kernel throttles allocation, doesn’t OOM)memory.swap.max— swap allowanceio.max— bytes-per-second and IOPS ceilings per devicepids.max— process count cap
systemd is the user-space agent that mostly drives this. Services live in <unit>.service cgroups under system.slice, user sessions under user.slice/user-<uid>.slice/session-<n>.scope, and the rules are set by unit files and systemd-cgls/systemd-cgtop.
A cgroup with memory.max=2G and memory.swap.max=0 will OOM-kill processes when they try to exceed 2 GiB. The kernel picks the victim using the same OOM logic described in why the OOM killer took out the wrong process, but the choice is constrained to that cgroup’s members — so a memory-bound service no longer takes down the host.
The procedure
- Put a memory limit on an existing systemd service. Use
systemctl set-propertyso the change persists across reboots:
sudo systemctl set-property nginx.service MemoryMax=512M MemorySwapMax=0
# verify
systemctl show nginx.service -p MemoryMax -p MemorySwapMax
cat /sys/fs/cgroup/system.slice/nginx.service/memory.max
set-property writes a drop-in unit under /etc/systemd/system.control/ and reloads.
- Put a CPU bandwidth limit on a service.
CPUQuota=50%means 50% of one CPU;200%means up to two full CPUs:
sudo systemctl set-property myworker.service CPUQuota=200% CPUWeight=300
# under the hood:
cat /sys/fs/cgroup/system.slice/myworker.service/cpu.max
# 200000 100000 (200ms per 100ms period)
CPUWeight=300 raises priority above the default 100 when there’s contention. Use CPUQuota for hard caps, CPUWeight for shaping under load.
- Build a cgroup by hand to constrain a long-running shell job — useful when you don’t want to create a systemd unit:
sudo mkdir /sys/fs/cgroup/batch-jobs
echo "+memory +cpu" | sudo tee /sys/fs/cgroup/cgroup.subtree_control
echo "1G" | sudo tee /sys/fs/cgroup/batch-jobs/memory.max
echo "100000 100000" | sudo tee /sys/fs/cgroup/batch-jobs/cpu.max
# move a running process into it
echo $PID | sudo tee /sys/fs/cgroup/batch-jobs/cgroup.procs
The subtree_control line is required — you must enable controllers in the parent before children can use them.
- Watch real-time pressure on a cgroup. cgroup v2 ships PSI (Pressure Stall Information) — a much better signal than load average:
cat /sys/fs/cgroup/system.slice/postgres.service/cpu.pressure
# some avg10=1.43 avg60=0.85 avg300=0.62 total=...
# full avg10=0.00 avg60=0.00 avg300=0.00 total=...
cat /sys/fs/cgroup/system.slice/postgres.service/memory.pressure
cat /sys/fs/cgroup/system.slice/postgres.service/io.pressure
some is “at least one task in the cgroup is stalled on this resource”; full is “all tasks are stalled”. The avg10 window is the most useful number for live triage. Anything sustained above 10 on some.avg60 is real pressure worth investigating.
- Limit I/O bandwidth per device. Find the major:minor of the device first:
lsblk -o NAME,MAJ:MIN
# nvme0n1 259:0
sudo systemctl set-property heavy-export.service \
IOReadBandwidthMax="/dev/nvme0n1 50M" \
IOWriteBandwidthMax="/dev/nvme0n1 20M"
cat /sys/fs/cgroup/system.slice/heavy-export.service/io.max
I/O caps in cgroup v2 are per-device — you can’t set a global limit across all block devices.
- Group related services into a custom slice to put a shared cap on the group:
# /etc/systemd/system/batch.slice
[Slice]
MemoryMax=8G
CPUQuota=400%
sudo systemctl daemon-reload
# put services under the slice
sudo systemctl edit worker-a.service
# add:
[Service]
Slice=batch.slice
Now the slice has a fixed 8 GiB ceiling and 4 CPUs to share across every service under it. This is how you give “the batch tier” a budget without setting per-service caps that interact in unexpected ways.
- Inspect the live cgroup tree with systemd’s two cgroup tools:
systemd-cgls # tree view
systemd-cgtop # top-style live view, CPU/Mem/I/O
systemd-cgtop --recursive --order=memory # sort by memory
systemd-cgls is the fastest way to “where is this process really running” when something looks misplaced.
Common pitfalls
- Forgetting
cgroup.subtree_control— controllers don’t propagate automatically. A child cgroup whose parent doesn’t enable+memorycannot setmemory.max, and writes silently fail. - Setting
MemoryMaxwithout settingMemorySwapMax=0on swap-enabled hosts. The process can swap to its heart’s content before OOMing, hiding the leak. CPUQuota=100%does NOT mean “use one CPU”; it means “100% of total available CPU time”. On a 4-core host this caps at 100% of one core. Use400%to allow four cores.systemctl set-propertywrites a drop-in. If you alsosystemctl editand add the same property, the edits collide — pick one approach per property.- cgroup v1 docs and tools are very common in older Stack Overflow answers. Anything in
/sys/fs/cgroup/<controller>/paths or that referencesmemory.kmem.limit_in_bytesis v1 — translate before applying. - Limits set on a running process via the cgroup filesystem don’t survive a reboot. Use systemd unit files or
set-propertyfor anything that should persist.
We bake cgroup limits into every systemd unit we manage — a memory ceiling, a sensible CPU quota, an I/O cap on services that touch disk hard. It turns the most common runaway-workload incidents from “the whole host is unresponsive” into “one service is throttled and we know which one”, and it’s a default in every host build pass under our managed operations practice.