Reliability and resources

Control CPU, memory, and tasks

Use cgroup-backed unit controls to contain one service without confusing a limit with capacity planning.

8 minute lesson

~~~

systemd places every service in its own control group. That is what makes resource limits practical: unit properties constrain the whole process tree, including children and anything they spawn. A worker pool cannot escape the limit by forking.

The four controls

[Service]
MemoryHigh=400M
MemoryMax=512M
CPUQuota=50%
TasksMax=64

Use MemoryHigh= for pressure: above it, the kernel throttles and reclaims memory from the service aggressively, but the process survives. Use MemoryMax= as a hard boundary: above it, processes in the group get killed. Setting both gives the service a warning zone before the cliff.

CPUQuota= limits CPU time — 50% means half of one CPU. TasksMax= bounds process and thread creation, which is your defense against fork bombs and runaway worker pools.

Put these in a drop-in (systemctl edit demo-api.service) rather than the vendor unit, then restart the service.

Verify the limit and the current use

systemctl show --property=ControlGroup,MemoryCurrent,TasksCurrent demo-api.service
ControlGroup=/system.slice/demo-api.service
MemoryCurrent=61128704
TasksCurrent=11

That is roughly 58 MB and 11 tasks right now. systemd-cgtop gives you the same numbers live, across all services, sorted by usage.

A limit is not capacity planning

Limits need monitoring because hitting them is still a failure. If the service breaches MemoryMax=, the journal shows the kill:

demo-api.service: A process of this unit has been killed by the OOM killer.
demo-api.service: Main process exited, code=killed, status=9/KILL

and systemctl show demo-api.service -p Result reports oom-kill. The service did not get slower. It died. If that keeps happening, the answer is a bigger budget or a smaller workload, not deleting the limit — the limit is what kept the rest of the machine alive.

Inspect one real service with the systemctl show command above. Propose one limit based on measured use and expected peaks, with MemoryHigh= around the peak and MemoryMax= comfortably above it.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →