How to set resource limits for a service with systemd
Limit CPU, memory, and I/O usage for a systemd service using cgroup directives in the unit file.
How to set resource limits for a service with systemd
Limit CPU, memory, and I/O usage for a systemd service using cgroup directives in the unit file.
Prerequisites
- Root or sudo access on a Linux system running systemd with cgroups v2 (default on Ubuntu 22.04+, Fedora 31+, Debian 11+).
Step-by-Step: Set Resource Limits for a systemd Service
Open a drop-in override for the service:
sudo systemctl edit myapp.serviceAdd resource limit directives under the
[Service]section. systemd enforces these limits through Linux control groups (cgroups):[Service] MemoryMax=512M MemoryHigh=400M CPUQuota=50% TasksMax=100 IOWeight=50MemoryMaxsets a hard memory ceiling — the kernel kills the process if it exceeds this limit.MemoryHighsets a soft limit — systemd throttles the process before reachingMemoryMax.CPUQuota=50%limits the service to 50% of one CPU core.TasksMaxlimits the number of processes and threads.Restart the service to apply the limits:
sudo systemctl restart myapp.service
How to Verify Resource Limits Are Active
systemd shows applied resource limits in the service properties:
systemctl show myapp.service | grep -E "MemoryMax|CPUQuota|TasksMax"Monitor actual resource usage with
systemd-cgtop:
systemd-cgtop