9.6. Applying Resource Limits

Nice values, I/O priorities, and policies all change how a scarce resource is shared. Limits are different: they draw a line that, when crossed, makes something fail - a file cannot be opened, a fork refused, a process killed. Linux has three limit mechanisms with different scopes, and using the wrong one for the job is a classic mistake: shell limits evaporate with the shell, PAM limits never reach services, and only the cgroup limits apply to everything systemd runs.

9.6.1. Shell Limits, PAM Limits, and Service Limits

Every process carries a set of rlimits, inherited from its parent. The ulimit builtin reads and sets them in the current shell - and they are per-process values, so a change affects only that shell and what it starts afterwards:

$ ulimit -a
real-time non-blocking time  (microseconds, -R) unlimited
core file size              (blocks, -c) 0
data seg size               (kbytes, -d) unlimited
scheduling priority                 (-e) 0
file size                   (blocks, -f) unlimited
pending signals                     (-i) 5704
max locked memory           (kbytes, -l) 8192
max memory size             (kbytes, -m) unlimited
open files                          (-n) 1024
pipe size                (512 bytes, -p) 8
POSIX message queues         (bytes, -q) 819200
real-time priority                  (-r) 0
stack size                  (kbytes, -s) 8192
cpu time                   (seconds, -t) unlimited
max user processes                  (-u) 5704
virtual memory              (kbytes, -v) unlimited
file locks                          (-x) unlimited

The lines that matter most in practice:

Flag Limit Default here
-n Open files per process. 1024
-u Processes for this user (threads and processes). 5704
-t CPU seconds; the kernel sends SIGXCPU at the soft limit, SIGKILL at the hard. unlimited
-v Address space - virtual memory size. unlimited
-s Stack size per thread. 8192 kB
-l Memory lockable with mlock. 8192 kB
-r / -R RT priority ceiling and RT CPU time (Section 9.3.7). 0 / unlimited

One entry is a fossil: -m (max memory size, RLIMIT_RSS) appears in the list but the Linux kernel does not enforce it - memory caps are done with cgroups, as Section 9.6.2 demonstrates. Each limit has a soft and a hard value: a process may raise its soft limit up to the hard one, and only root may raise the hard limit. Watch the soft limit move:

$ ulimit -n 64
$ ulimit -n
64

The first command lowers the open-files soft limit to 64; the second prints it. This shell and its children can now open 64 files each; the hard limit still allows raising it back. That is the whole mechanism - and also its weakness: the setting lives in one shell's memory.

For limits that apply to every login of a user, the PAM stack is the carrier. pam_limits reads /etc/security/limits.conf and the fragments in /etc/security/limits.d/ when a new session opens (Chapter 5 introduced PAM). Create a fragment for john - in the root shell, /etc/security/limits.d/09-handbook-limits.conf with this content:

john soft nproc 64
john hard nproc 128
john soft nofile 512
john hard nofile 1024

Each line is domain, type, item, value: for user john, soft 64 / hard 128 processes, and soft 512 / hard 1024 open files. The new limits appear in every new login session - su - starts one, so as root:

# su - john -c "ulimit -u; ulimit -Sn; ulimit -Hn"
64
512
1024

Three answers for three questions: the process limit (64), the soft open-files limit (512), and the hard one (1024). An SSH login passes through the same pam_limits stack, so john's remote sessions get the same values; the already-running shell from before does not change, because PAM limits are applied at session start, not continuously. Remove the fragment afterwards with rm /etc/security/limits.d/09-handbook-limits.conf and the next session returns to the defaults.

Services are the third case, and the trap: they do not log in through PAM, so limits.conf does nothing for them. A systemd unit sets limits directly through unit properties, and the kernel records them in /proc/<pid>/limits:

# systemd-run --unit=handbook-limits --slice=handbook.slice -p LimitNOFILE=256 -p LimitNPROC=64 sleep 60
Running as unit: handbook-limits.service; invocation ID: ba680b3628704152be1ab642f5805eb5

The unit runs with 256 open files and 64 processes. Check both views - first the kernel's, by way of the service's main PID:

# p=$(systemctl show handbook-limits -p MainPID --value)
# grep -E "open files|processes" /proc/$p/limits
Max processes             64                   64                   processes 
Max open files            256                  256                  files     

The assignment on the first line stores the PID and prints nothing; the grep selects the two interesting rows, each showing the soft limit, the hard limit (equal here because a single value sets both), and the unit of measurement. Then systemd's own view:

# systemctl show handbook-limits -p LimitNOFILE -p LimitNPROC
LimitNOFILE=256
LimitNPROC=64

For a persistent service these properties belong in its unit file or a drop-in - the same /etc/systemd/system/<unit>.d/*.conf mechanism used for the CPU settings of Section 9.3.6. Collected, the three mechanisms:

Mechanism Scope Set where Weakness
ulimit One shell and its children. The shell itself. Gone when the shell exits.
PAM limits Every new login session of a user. /etc/security/limits.d/. Does not reach services or cron-less daemons.
systemd limits A unit and everything it forks. Unit properties / drop-ins. Per-unit configuration, not per-user.

9.6.2. Cgroups, Slices, Inheritance, and Effective Limits

All the systemd limits of this chapter - CPU, memory, tasks, I/O - are one mechanism underneath: control groups, version 2, mounted at /sys/fs/cgroup. Every unit the manager starts is placed in a cgroup shaped like its slice hierarchy (handbook.slice containing handbook-mem.service, and so on), and the kernel enforces each controller's rules at the cgroup that carries them. The rule that surprises people is inheritance: a cgroup cannot give itself more than its ancestors allow. A limit is enforced at the nearest ancestor that sets one, and systemd reports the computed result with Effective properties. Figure 9.5 shows the experiment that follows.

Effective limits along a cgroup hierarchy

Figure 9.5. Conceptual view of the recorded slice experiment: the service sets no limits of its own, yet its processes cannot exceed the slice's 200 MiB and 50 tasks.

Set a memory and task limit on the slice itself - the runtime form, which writes a drop-in under /run and disappears at reboot:

# systemctl set-property --runtime handbook.slice MemoryMax=200M TasksMax=50

Silent as ever. Start a service under the slice and look at both levels:

# systemd-run --unit=handbook-mem --slice=handbook.slice sleep 60
Running as unit: handbook-mem.service; invocation ID: 8faf08b2d37a45efb5355aaa99bd9414
# systemctl show handbook.slice -p MemoryMax -p TasksMax
MemoryMax=209715200
TasksMax=50

The slice reports the settings just applied - 209715200 bytes is the normalized form of 200 MiB. The service, asked about itself, sets nothing:

# systemctl show handbook-mem -p MemoryMax -p EffectiveMemoryMax -p TasksMax -p EffectiveTasksMax
EffectiveMemoryMax=209715200
EffectiveTasksMax=50
MemoryMax=infinity
TasksMax=1711

MemoryMax=infinity and TasksMax=1711 are the service's own settings - none, and systemd's default task ceiling (15% of the kernel's thread limit, /proc/sys/kernel/threads-max here being 11408). The Effective lines are what the kernel will actually enforce: the slice's limits, inherited. The kernel's own files tell the same story from the other side - the slice carries the limits, the service carries defaults:

# cat /sys/fs/cgroup/handbook.slice/memory.max /sys/fs/cgroup/handbook.slice/pids.max
209715200
50
# cat /sys/fs/cgroup/handbook.slice/handbook-mem.service/memory.max /sys/fs/cgroup/handbook.slice/handbook-mem.service/pids.max
max
1711

memory.max is max (no limit) in the service's cgroup and 209715200 in its parent; pids.max is 1711 in the child and 50 in the parent. When the service's processes fill memory, the kernel charges the service's cgroup, finds no local limit, and throttles or kills at the ancestor's line. This is why limits belong on the highest grouping that matches the responsibility: a slice for "everything in this project", a service for "this one program".

Removing the runtime limits is one command, and it is not "stop the slice" - stopping a slice stops its units but leaves its configuration in place:

# systemctl stop handbook-mem
# systemctl revert handbook.slice
Removed '/run/systemd/system.control/handbook.slice.d/50-TasksMax.conf'.
Removed '/run/systemd/system.control/handbook.slice.d/50-MemoryMax.conf'.
Removed '/run/systemd/system.control/handbook.slice.d'.

systemctl revert deletes the drop-ins set-property --runtime created and prints each removal. Verify the slice is back to defaults:

# systemctl show handbook.slice -p MemoryMax -p TasksMax
MemoryMax=infinity
TasksMax=infinity

Both unbounded again. Without --runtime, set-property writes the same drop-ins under /etc/systemd/system.control/, where they survive reboots and must be removed by hand or by revert; choose the runtime form for experiments and the persistent form for standing policy.

9.6.3. Memory Pressure, Task Limits, and Resource Accounting

Between "no limit" and "kill at the line" there is a middle setting worth knowing: MemoryHigh. Unlike MemoryMax, crossing it kills nothing - the kernel throttles the cgroup, forcing reclaim and delaying its tasks, and counts the events. Run a memory worker between two boundaries: 100 MiB of MemoryHigh, 200 MiB of MemoryMax, and a demand of 180 MiB - in the root shell:

# systemd-run --unit=handbook-memhigh --slice=handbook.slice -p MemoryHigh=100M -p MemoryMax=200M stress-ng --vm 1 --vm-bytes 180M --timeout 8s
Running as unit: handbook-memhigh.service; invocation ID: a0684ca414e64737a33fca94ce776c3

stress-ng --vm 1 --vm-bytes 180M is one worker touching 180 MiB. Let it run four seconds and inspect:

# systemctl show handbook-memhigh -p MemoryHigh -p MemoryMax -p MemoryCurrent
MemoryCurrent=111861760
MemoryHigh=104857600
MemoryMax=209715200

The boundaries are 100 MiB (104857600) and 200 MiB. MemoryCurrent - 111861760 bytes, about 106 MiB - sits just above the High boundary: the kernel is holding the worker at the throttle line rather than letting it grab all 180 MiB. The event counters tell what that cost the workload:

# cat /sys/fs/cgroup/handbook.slice/handbook-memhigh.service/memory.events
low 0
high 102
max 0
oom 0
oom_kill 0
oom_group_kill 0

high 102 counts the times the cgroup crossed the High line - a busy throttle. max 0 and oom 0 mean the worker never touched the kill boundary: nothing died. The pressure file quantifies the stall:

# cat /sys/fs/cgroup/handbook.slice/handbook-memhigh.service/memory.pressure
some avg10=32.32 avg60=6.30 avg300=1.33 total=3966088
full avg10=32.32 avg60=6.30 avg300=1.33 total=3966088

This is the per-cgroup version of /proc/pressure from Section 9.5.1: the worker's tasks were stalled about 32% of the recent ten-second window (avg10=32.32) - working, but running at about two-thirds speed. That is the intended effect of MemoryHigh: a workload that would otherwise squeeze its neighbours is squeezed first, and the pressure numbers make the slowdown visible and measurable instead of mysterious.

Task limits have the same layered design, and the same evidence trail. This fixture tries to keep more background children than a limit allows; save it as fork_children.sh:

#!/bin/bash
# Try to keep more background children than a task limit allows.
count=${1:-50}
i=1
while [ "$i" -le "$count" ]; do
    sleep 30 &
    i=$((i + 1))
done
sleep 30
wait

It launches fifty sleep 30 children, then waits. Run it capped at 30 tasks:

# systemd-run --unit=handbook-tasks --slice=handbook.slice -p TasksMax=30 /bin/bash /home/john/debian-handbook/processes/fork_children.sh 50
Running as unit: handbook-tasks.service; invocation ID: 3ea81cb603bb404baf1ca94ce776c3

Two seconds in:

# systemctl show handbook-tasks -p TasksMax -p TasksCurrent -p Result
Result=success
TasksCurrent=30
TasksMax=30

The service reached exactly 30 tasks (the script itself plus twenty-nine sleeps) - the remaining forks failed, their error messages going to the unit's stderr in the journal (Chapter 8 covers where that lands). The kernel counted the refusals:

# cat /sys/fs/cgroup/handbook.slice/handbook-tasks.service/pids.events
max 2
# cat /sys/fs/cgroup/handbook.slice/handbook-tasks.service/pids.current
30

pids.current is the live count, pinned at the ceiling, and pids.events counted the limit hits. Because the script has no error handling, it simply waits out its sleeps and exits 0 - hence Result=success in the capture; the enforcement evidence is the pair of counters, not the unit's fate. This is precisely the control that stops a fork bomb at thirty processes instead of five thousand.

The last piece of the limits story is accounting - reading back what a process or cgroup actually consumed. Per process, the kernel keeps I/O counters in /proc/<pid>/io - the files pidstat -d samples, as Section 9.4.8 noted. Here a single direct writer is inspected half a second in:

$ dd if=/dev/zero of=w.bin bs=1M count=256 oflag=direct status=none &
$ d=$!
$ sleep 0.5
$ echo ddpid=$d
ddpid=11485
$ cat /proc/$d/io | head -4
rchar: 260053992
wchar: 258998272
syscr: 258
syscw: 247
$ echo shell-io:
shell-io:
$ cat /proc/$$/io | head -4
rchar: 49792
wchar: 276
syscr: 75
syscw: 6
$ ps -o pid,ppid,comm -p $d $$
    PID    PPID COMMAND
 11482   11478 bash
 11485   11482 dd
$ wait $d
$ rm -f w.bin

rchar and wchar are bytes moved through read and write syscalls - dd has already pushed about 259 MB of writes in half a second, read from /dev/zero as input; syscr/syscw count the calls. The shell that forked it has moved almost nothing - the counters are per process, not per user or per session. pidstat -d from the sysstat package samples exactly these files and prints them per second, which is how per-process I/O attribution is normally done.

Per cgroup, the accounting is what systemd surfaces as unit properties: MemoryPeak (used in Section 9.5.3), CPUUsageNSec (total CPU time; the systemd-run --wait summary in Section 9.3.8 printed its human-readable form), TasksCurrent (used above), and the kernel's own io.stat/cpu.stat/memory.stat files in the cgroup directory, which accumulate bytes, operations, and time per controller. Chapter 28 turns these counters into continuous monitoring; the point of this chapter is that every limit discussed here leaves a matching trail of evidence.