Resource limits
Without limits, every process on the machine is allowed to take all of it. One memory leak is then an outage rather than a restart.
The four that matter
In the [Service] section of a unit:
MemoryMax=4G
CPUQuota=200%
TasksMax=512
IOWeight=50
CPUQuota=200% means two cores' worth, not 200% of one. TasksMax
caps processes and threads, which is what stops a fork bomb.
Apply with systemctl daemon-reload and a restart. See
running your application as a service.
MemoryMax versus MemoryHigh
- MemoryHigh
- A soft limit. The service is throttled and pushed to reclaim, but not killed. Good for something you would rather see slow down than die.
- MemoryMax
- A hard limit. Exceed it and the OOM killer takes that service — and only that service, which is the entire point. See swap and the OOM killer.
Set both: MemoryHigh a little under MemoryMax, so you get
a warning phase before the execution.
See what is actually being used
systemd-cgtop
Like top, but per service rather than per process — which is the
view you want when a machine is busy and you do not yet know who is responsible.
systemctl status myapp shows the current memory and task counts for a
single unit, and systemctl show myapp -p MemoryMax confirms a limit is
really in effect.
Where this pays off
- A PHP-FPM pool that occasionally runs away — cap it and the rest of the machine survives. See tuning PHP-FPM.
- A JVM whose heap setting and the machine's memory disagree — see running a JVM application.
- Backup and batch jobs: give them a low
IOWeightso a nightly dump does not make the site unusable. - Anything a customer of yours controls, if you resell or host for others.
Containers do this already
Docker's --memory, --cpus and --pids-limit are
the same mechanism with a different front end. If you run containers, set them
— an unlimited container is exactly as dangerous as an unlimited service. See
running containers safely.
Leave the system room
Do not allocate every byte. The kernel needs page cache, and a machine with no cache left is slow in a way that looks like a disk problem. A quarter of memory unallocated is a reasonable floor on a busy box — see how much server do you actually need.
Still stuck? Mail support@novogara.com — an engineer answers, at any hour. Back to the knowledge base