Lesson 8 of 9 · 26m
cgroups and Resource Control: systemd's Quiet Superpower
How systemd places every service in cgroups, and how to use CPU, memory, IO, and task limits for isolation instead of post-incident regret.
Even operators who dislike systemd benefit from one design decision: every service, scope, and user session lives in a cgroup. That gives consistent accounting and enforcement without handwritten wrappers. If one runaway process ate the box, the root cause was often that nobody wrote down resource expectations.
The tree is the accounting model
systemd-cgls
systemctl status metrics-api.servicesystemd organizes control groups under units:
system.slice/metrics-api.service
user.slice/user-1000.sliceA service cannot escape its cgroup by forking children. That is why systemd's CPU, memory, and task accounting are more trustworthy than ad hoc ps inspection.
Memory limits are failure design
[Service]
MemoryMax=1G
MemoryHigh=800M
MemorySwapMax=0MemoryHigh is a soft throttle: the kernel starts reclaiming aggressively when the cgroup crosses it. MemoryMax is hard: crossing it can trigger the cgroup OOM killer. A cache may tolerate pressure at MemoryHigh; a leaky worker should hit MemoryMax before the host OOM killer chooses victims randomly.
Check the evidence:
systemctl show metrics-api.service -p MemoryCurrent -p MemoryPeak -p ControlGroup
journalctl -k --since "1 hour ago" | grep -i "out of memory"A service being OOM-killed is a capacity signal. Restarting it without changing workload or limit schedules the next kill.
CPU, IO, tasks, and file descriptors
[Service]
CPUWeight=200
CPUQuota=150%
AllowedCPUs=0-3
TasksMax=500
LimitNOFILE=65536CPUWeight controls relative contention when CPU is scarce. CPUQuota=150% caps usage at one and a half cores even when capacity is idle. AllowedCPUs pins the service, which can help NUMA or licensing cases but can also create scheduling bottlenecks.
Block-device IO control depends on kernel, filesystem, device mapper, and writeback behavior. Test realistic load; limiting the device you merely think backs the filesystem is a classic LVM/cloud-volume mistake. TasksMax contains fork bombs and recursive worker bugs inside the service cgroup.
Scopes, slices, and batch work
Slices group policy. Put tenant workloads in a slice and constrain the slice rather than every service individually. For one-off jobs, systemd-run creates a supervised transient service:
systemd-run --unit=report-build --slice=batch.slice -p MemoryMax=4G -p CPUWeight=50 /opt/jobs/build-report nightlyField notes
- Restart units after changing resource directives; a running unit does not magically move into a new configuration.
- cgroup v1 and v2 differ; older kernels and container hosts can surprise you.
- CPU quota percentages are per-core:
200%means two cores. - Even generous limits are useful documentation that enforcement can read.
Was this lesson helpful?