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

  1. Open a drop-in override for the service:

    sudo systemctl edit myapp.service
  2. Add 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=50

    MemoryMax sets a hard memory ceiling — the kernel kills the process if it exceeds this limit. MemoryHigh sets a soft limit — systemd throttles the process before reaching MemoryMax. CPUQuota=50% limits the service to 50% of one CPU core. TasksMax limits the number of processes and threads.

  3. 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