Skip to main content

Linux and servers · Intermediate · 15 min

Limit a service's CPU, memory and processes with systemd

By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · systemd 259 · stress-ng 0.20

You will cap a running service at half a CPU, 256 MB of memory and 64 processes with one systemd drop-in file, watch the limits hold in systemctl status and systemd-cgtop, and run a one-off command inside its own memory limit.

On this page

One badly behaved service can take a whole server with it. A queue worker leaks memory until the kernel starts killing processes, and SSH goes with them. A report job pins every CPU core and the web app stops answering. A bug forks processes in a loop until nothing new can start. On a small 1 GB or 2 GB virtual server, the kind many teams run on a monthly prepaid plan, there is very little headroom to absorb any of this.

systemd can stop it. Every service it starts runs in its own control group (cgroup), and the kernel enforces limits on each cgroup: how much memory it may use, how much CPU time it gets, how many processes it may create. You set those limits with a few lines in a drop-in file, and the service cannot go past them however it misbehaves.

In this tutorial you will create a small demo service that burns CPU on purpose, cap it with a drop-in, watch the limits hold, change one while it runs, and put a memory cap on a one-off command. At the end you will see that Docker's --memory and Kubernetes limits write to the same kernel files. Ubuntu 26.04 ships systemd 259 and uses cgroup v2 only.

Step 1 · Confirm the server uses cgroup v2

The settings in this tutorial are for cgroup v2, the unified hierarchy. Check which one your server mounts:

Bash
stat -fc %T /sys/fs/cgroup
cat /sys/fs/cgroup/cgroup.controllers

The first line names the filesystem type. The second lists the controllers the kernel offers, the parts that each enforce one kind of limit.

Check it worked

The first command prints cgroup2fs. The controller list includes cpu, io, memory and pids, among others such as cpuset and hugetlb. If you see tmpfs instead of cgroup2fs, the server is on the old v1 layout (an older release, or a kernel option that forces it); upgrade to Ubuntu 26.04 before you continue, because the memory and CPU settings below behave differently there.

Step 2 · Create a demo service that uses too much CPU

To see limits work you need something that breaks them. stress-ng is a load generator in the Ubuntu archive. Install it:

Bash
sudo apt update
sudo apt install -y stress-ng

Now write a service that runs two CPU workers forever. DynamicUser=yes runs it as a throwaway unprivileged user, so the demo never runs as root:

Bash
sudo tee /etc/systemd/system/hog-demo.service > /dev/null <<'UNIT'
[Unit]
Description=Demo service that burns CPU

[Service]
ExecStart=/usr/bin/stress-ng --cpu 2
DynamicUser=yes

[Install]
WantedBy=multi-user.target
UNIT
Bash
sudo systemd-analyze verify /etc/systemd/system/hog-demo.service
sudo systemctl daemon-reload
sudo systemctl enable --now hog-demo

systemd-analyze verify prints nothing when the unit is valid.

Check it worked

Run top and press q to leave it. Two stress-ng-cpu processes sit at the top of the list, each near 100% CPU. On a two-core server that is the whole machine. Everything else on the server now competes with them.

Step 3 · Add the limits in a drop-in

Keep limits in a drop-in file rather than in the unit itself. For your own service either works, but for a packaged one (Nginx, PostgreSQL) a drop-in is the only place a package upgrade will not overwrite. Write one:

Bash
sudo mkdir -p /etc/systemd/system/hog-demo.service.d
sudo tee /etc/systemd/system/hog-demo.service.d/50-limits.conf > /dev/null <<'CONF'
[Service]
MemoryHigh=192M
MemoryMax=256M
MemorySwapMax=0
CPUQuota=50%
CPUWeight=50
TasksMax=64
IOWeight=50
CONF

What each line does:

  • MemoryHigh=192M is the soft limit. Above it the kernel slows the service down and reclaims its memory aggressively, but kills nothing. It is your early warning: a service that lives at its MemoryHigh is slow, and you notice before it is dead.
  • MemoryMax=256M is the hard limit. If the service cannot be brought back under it, the kernel's OOM killer kills a process inside this service only. The rest of the server is untouched. Set MemoryHigh around 75 to 90% of MemoryMax so throttling starts before the kill.
  • MemorySwapMax=0 stops the service using swap. Without it, a leaking service on a server with a swap file pushes itself into swap and becomes very slow instead of hitting MemoryMax. Leave it out if you would rather have slow than restarted.
  • CPUQuota=50% caps the service at half of one CPU's time, however many cores the server has. 200% would be two full cores. This is a ceiling that applies even when the server is otherwise idle.
  • CPUWeight=50 is a share, not a cap. The default is 100 (range 1 to 10000). When CPUs are busy, a service with weight 50 gets half as much time as one with the default. When they are idle it changes nothing. Use weights to say what matters most, and quotas only when you need a hard ceiling.
  • TasksMax=64 limits the number of processes and threads. A fork bomb or a runaway worker pool stops at 64 instead of exhausting the process table. Without this line systemd applies its default, 15% of the kernel's thread limit, which scales with RAM: about a thousand on a 1 GB server and far more on larger ones. Run systemctl show -p DefaultTasksMax (or look at the limit: next to Tasks: in systemctl status) to see yours.
  • IOWeight=50 gives the service a smaller share of disk time under contention, on the same 1 to 10000 scale. It only has an effect when the disk's I/O controller supports proportional weights (the BFQ scheduler or the kernel's io.cost model). Many cloud disks use neither, so treat it as a hint, and use IOReadBandwidthMax= or IOWriteBandwidthMax= when you need a hard disk cap.

Sizes take K, M, G and T suffixes, all in powers of 1024, so 256M is 268,435,456 bytes. MemoryMax= also accepts a percentage of the server's RAM, such as 25%.

Check it worked

Ask systemd to parse the unit together with its drop-in:

Bash
sudo systemd-analyze verify /etc/systemd/system/hog-demo.service

No output means every line was understood. This check matters, because systemd ignores a setting it cannot parse and starts the service anyway, without the limit. Try it: add two mistakes to a separate drop-in, a misspelt key and a quota without its % sign:

Bash
sudo tee /etc/systemd/system/hog-demo.service.d/60-typo.conf > /dev/null <<'CONF'
[Service]
MemoryMaximum=1G
CPUQuota=50
CONF
Bash
sudo systemd-analyze verify /etc/systemd/system/hog-demo.service

The output names the file and line of each problem: Unknown key 'MemoryMaximum' in section [Service], ignoring. and Invalid CPU quota '50', ignoring. Both end in "ignoring", which is exactly the danger. Delete the broken file before you go on:

Bash
sudo rm /etc/systemd/system/hog-demo.service.d/60-typo.conf

Step 4 · Apply the limits and watch them hold

Reload systemd's configuration and restart the service so it starts inside the new limits:

Bash
sudo systemctl daemon-reload
sudo systemctl restart hog-demo

Look at the service:

Bash
systemctl status hog-demo --no-pager

Under the Active: line you see the current usage next to each limit. The exact figures and sub-fields vary with the systemd version and the moment you look, but it reads something like this (an illustration, not captured output):

Text
     Tasks: 3 (limit: 64)
    Memory: 4.2M (high: 192M max: 256M swap max: 0B available: 251.7M peak: 4.6M)
       CPU: 31.877s

To see the values systemd is enforcing, without the usage:

Bash
systemctl show hog-demo -p MemoryHigh -p MemoryMax -p CPUQuotaPerSecUSec -p CPUWeight -p TasksMax

MemoryMax is shown in bytes (268435456) and the quota as CPU time per second (500ms).

For a live view of every service at once, run systemd-cgtop. It is top for cgroups:

Bash
sudo systemd-cgtop -m --depth=2

-m sorts by memory; press c to sort by CPU, t by tasks, and q to quit. --depth=2 stops it listing every nested group.

Check it worked

Run top again. The two stress-ng-cpu workers now share half a CPU, around 25% each, instead of 100% each. In systemd-cgtop, the hog-demo.service line shows about 50 in the %CPU column. The service is still running; it just cannot take more than it was given.

Step 5 · Change a limit while the service runs

When a service is in trouble at 2 a.m., you may want to tighten a limit without editing files or restarting it. systemctl set-property changes the running cgroup straight away:

Bash
sudo systemctl set-property hog-demo CPUQuota=20%

This also saves the change as a drop-in under /etc/systemd/system.control/hog-demo.service.d/, so it survives a reboot. Files there take priority over /etc/systemd/system/, which can confuse whoever reads your 50-limits.conf later.

There is also a temporary form, sudo systemctl set-property --runtime hog-demo CPUQuota=20%, which writes to /run/systemd/system.control/hog-demo.service.d/ instead and is lost at the next boot. You do not need to run it here; it is the one to reach for when you want a change that cannot outlive the incident. That directory also takes priority over your drop-in until the reboot, so remove it in the same way if you use it.

Once things are calm, put the permanent value in your own drop-in and remove the control files, so there is one place to look:

Bash
sudo rm -r /etc/systemd/system.control/hog-demo.service.d
sudo rm -rf /run/systemd/system.control/hog-demo.service.d
sudo systemctl daemon-reload
sudo systemctl restart hog-demo

Check it worked

Straight after set-property, systemd-cgtop shows hog-demo.service near 20 in the %CPU column, with no restart. After removing the control files and restarting, systemctl show hog-demo -p CPUQuotaPerSecUSec is back to 500ms.

Step 6 · Put a limit on a one-off command

Limits are not only for services. A database restore, a big rsync or a test script you do not fully trust can run inside a temporary cgroup with systemd-run --scope. The command runs in your terminal as usual, with the limits you pass as -p properties.

Ubuntu Server ships Python 3. This command tries to allocate 300 MB, inside a 200 MB limit with swap turned off:

Bash
sudo systemd-run --scope -p MemoryMax=200M -p MemorySwapMax=0 python3 -c 'b = bytearray(300 * 1024 * 1024); print("allocated")'
echo "exit code: $?"

Run it again with MemoryMax=400M and it prints allocated.

The same works for processes. This loop tries to start 40 background sleep processes under a limit of 20:

Bash
sudo systemd-run --scope -p TasksMax=20 bash -c 'for i in $(seq 40); do sleep 5 & done; wait'

Check it worked

The memory command first prints something like Running as unit: run-r3c1f9e2b.scope, then Killed, and the exit code is 137 (128 plus signal 9). It never prints allocated. Only the Python process died; your shell and everything else carried on. The process loop prints bash: fork: retry: Resource temporarily unavailable lines once it reaches the limit, then finishes when the first sleeps exit. The scope unit disappears when its command ends, so there is nothing to clean up.

Step 7 · See the same files Docker and Kubernetes use

systemd does not enforce anything itself. It writes numbers into files under /sys/fs/cgroup, and the kernel enforces them. Each service has a directory there. Read the demo service's limits from the source:

Bash
cd /sys/fs/cgroup/system.slice/hog-demo.service
cat memory.high memory.max cpu.max cpu.weight pids.max
cd

You get 201326592, 268435456, 50000 100000, 50 and 64. cpu.max reads as "50,000 microseconds of CPU time in every 100,000": half a CPU. Any group without a limit shows max.

Container tools use exactly these files. A container is a set of processes in its own cgroup, and the runtime fills in the same values:

  • docker run --memory 256m writes memory.max, --cpus 0.5 writes cpu.max as 50000 100000, and --pids-limit 64 writes pids.max.
  • In Kubernetes, a container's limits.memory becomes memory.max and limits.cpu becomes cpu.max. requests.cpu becomes a CPU weight, like CPUWeight=. The kubelet itself typically runs under systemd, which owns the cgroup tree it creates them in.

If Docker is installed, you can see it for yourself:

Bash
docker run --rm --memory 256m --cpus 0.5 --pids-limit 64 ubuntu:26.04 cat /sys/fs/cgroup/memory.max /sys/fs/cgroup/cpu.max /sys/fs/cgroup/pids.max

Check it worked

The service's files show the same numbers as your drop-in, translated to bytes and microseconds. The docker run line prints 268435456, 50000 100000 and 64: the values you set for hog-demo, reached by a different tool. When a container is OOM-killed or throttled, it is the same kernel mechanism you have just watched on a service.

Step 8 · Remove the demo

Stop and disable the service, then delete its unit and drop-in. These are the files you created above:

Bash
sudo systemctl disable --now hog-demo
Bash
sudo rm -r /etc/systemd/system/hog-demo.service.d
sudo rm /etc/systemd/system/hog-demo.service
Bash
sudo rm -rf /etc/systemd/system.control/hog-demo.service.d
sudo rm -rf /run/systemd/system.control/hog-demo.service.d
sudo systemctl daemon-reload

Keep stress-ng if it is useful for load testing; otherwise remove it with sudo apt remove stress-ng.

Check it worked

systemctl status hog-demo says Unit hog-demo.service could not be found., and top shows no stress-ng processes. To protect a real service, copy 50-limits.conf into its own drop-in directory, such as /etc/systemd/system/myapp.service.d/, and size each limit from what systemctl status shows the service using on a normal day plus headroom.

Next steps

  • Find out which process used the memory, and read the kernel's message when a MemoryMax= kill happens: /tutorials/find-what-is-using-memory-and-read-oom-killer-messages
  • Combine limits with sandboxing options so a compromised service can do less damage as well as use less: /tutorials/sandbox-a-systemd-service-with-security-options
  • Learn more about drop-ins for packaged services such as Nginx: /tutorials/change-a-packaged-service-with-systemd-drop-ins

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.