Performance and resource limits
"The server is slow" can mean four different things: the CPU is busy, memory has run out, the disk can't keep up, or the network is the bottleneck. Each has its own tools. This lesson shows how to tell them apart in a minute or two, and how to put limits on programs so one greedy process can't take the whole machine down.
The 60-second check
Run these first, in this order, whenever a server feels slow:
uptime
nproc
free -h
df -h / | tail -1 10:48:03 up 9 days, 9:30, 0 user, load average: 0.97, 0.65, 0.61
10
total used free shared buff/cache available
Mem: 7.7Gi 1.6Gi 335Mi 28Mi 6.0Gi 6.1Gi
Swap: 1.0Gi 1.5Mi 1.0Gi
overlay 224G 15G 199G 7% /| Command | What to look at |
|---|---|
uptime |
Load average for 1, 5 and 15 minutes. Compare it with nproc (number of CPU cores): load above the core count means work is waiting |
free -h |
The available column: memory programs can still get. Low free is normal: Linux uses spare RAM as disk cache |
df -h |
A full disk makes everything fail in strange ways |
top / htop |
Which processes use the CPU and memory |
vmstat 1 |
CPU, memory, swap and I/O every second |
iostat -xz 1 |
Per-disk load (package sysstat) |
CPU
Let's create some load and find it, the way you would on a real server:
stress-ng --cpu 2 --timeout 8s --quiet &
sleep 3
ps -eo pcpu,comm,user --sort=-pcpu | head -3
echo "--- vmstat (r = processes waiting for a CPU, us = user CPU %, id = idle %):"
vmstat 1 2 | tail -1 | awk '{ print "r=" $1, "us=" $13, "sy=" $14, "id=" $15 }'
wait%CPU COMMAND USER 99.6 stress-ng-cpu you 99.6 stress-ng-cpu you --- vmstat (r = processes waiting for a CPU, us = user CPU %, id = idle %): r=2 us=20 sy=0 id=80
%CPUper process can go above 100% on multi-core machines: 200% means two full cores.- In
top, CPU time is split into us (user programs), sy (kernel), wa (waiting for disk) and id (idle). Highwameans the disk, not the CPU, is the problem. - When the CPU really is the bottleneck: find the hot process, look at its logs (a retry loop? a runaway query?), lower its priority with
nice, or limit it (below).
Memory
free -m | awk 'NR == 1 || NR == 2'
echo "--- top memory users (RSS = real memory in KB):"
ps -eo rss,comm --sort=-rss | head -4total used free shared buff/cache available Mem: 7836 1615 340 28 6108 6221 --- top memory users (RSS = real memory in KB): RSS COMMAND 15496 systemd-journal 11476 systemd 3968 dbus-daemon
- used + buff/cache + free = total. Cache is given back instantly when programs need it, so only available matters.
- Swap is disk space used as overflow memory. A little is fine; a lot of active swapping (
si/socolumns invmstat) makes everything crawl. - When memory truly runs out, the kernel's OOM killer kills the biggest process to save the system. Check for it after any mysterious crash:
journalctl -k --no-pager -q | grep -i "out of memory" | wc -l0
(0 here. On a real victim you'd see lines like Out of memory: Killed process 1234 (node) total-vm:….)
Disk I/O
iostat -xz 1 # per-disk statistics every second (package sysstat)
sudo iotop -o # which processes are reading and writing right now (package iotop)In iostat, look at r/s and w/s (reads and writes per second), await (milliseconds each request waits) and %util (how busy the disk is). A disk at ~100% %util with high await (milliseconds per request) is saturated. Usual causes: a backup or log job, a database without the right index, or swapping. Run heavy jobs with ionice -c3 (idle priority) or schedule them for quiet hours.
Limiting resources with systemd
The best fix for "one process ate the server" is a limit set in advance. Every systemd service runs in its own cgroup, and you can cap it:
systemd-run --unit=greedy --quiet -p MemoryMax=50M -p CPUQuota=20% stress-ng --vm 1 --vm-bytes 200M --vm-keep --timeout 6s --quiet
sleep 3
systemctl show greedy -p MemoryMax -p CPUQuotaPerSecUSec | sed 's/52428800/52428800 (50 MB)/; s/200ms/200ms (20% of one CPU)/'
mem=$(systemctl show greedy -p MemoryCurrent --value)
echo "memory in use: $(( mem / 1024 / 1024 )) MB (asked for 200 MB)"
sleep 4CPUQuotaPerSecUSec=200ms (20% of one CPU) MemoryMax=52428800 (50 MB) memory in use: 46 MB (asked for 200 MB)
The process asked for 200 MB but was held at 50 MB. In a unit file it's the same settings:
[Service]
MemoryMax=512M # hard cap: exceed it and the service is OOM-killed (Restart= brings it back)
MemoryHigh=400M # soft cap: slowed down and pushed to swap first
CPUQuota=150% # at most 1.5 cores
TasksMax=200 # limits fork bombs and thread leaks
IOWeight=50 # lower disk priority (default 100)systemd-cgtop shows live usage per service, like top for cgroups. Docker's --memory and --cpus flags and Kubernetes resources.limits are built on the very same kernel feature.
Per-user limits: ulimit
Each process also has limits like the maximum number of open files. Busy web servers and databases hit the default of 1024 quickly ("Too many open files"):
ulimit -n
ulimit -a | grep -E "open files|max user processes"
(ulimit -n 64; python3 -c "
files = []
try:
while True: files.append(open('/dev/null'))
except OSError as e: print(f'opened {len(files)} files, then: {e}')
")1048576 open files (-n) 1048576 max user processes (-u) unlimited opened 61 files, then: [Errno 24] Too many open files: '/dev/null'
This machine allows 1,048,576 open files (the default inside Docker containers); a fresh login on Ubuntu usually gets 1024. The subshell lowered it to 64 to show what happens when a program runs out. For a service, raise it with LimitNOFILE=65536 in the unit (not ulimit, which only affects your shell). For login sessions, it's /etc/security/limits.conf.
Kernel settings: sysctl
The kernel has hundreds of tunable settings in /proc/sys, read and set with sysctl:
sysctl vm.swappiness net.core.somaxconn fs.file-maxvm.swappiness = 60 net.core.somaxconn = 4096 fs.file-max = 9223372036854775807
| Setting | Effect |
|---|---|
vm.swappiness |
How eagerly to swap (0–200; lower = keep programs in RAM). Database servers often use 1–10 |
net.core.somaxconn |
Queue size for new connections waiting to be accepted |
fs.file-max |
Open files allowed system-wide |
net.ipv4.ip_local_port_range |
Ports available for outgoing connections (busy proxies run out) |
Set one for now with sudo sysctl -w vm.swappiness=10; make it permanent in a file in /etc/sysctl.d/ and load it with sudo sysctl --system. Change kernel settings only for a measured problem: the defaults are good for most servers.
Measuring a single command
/usr/bin/time -v python3 -c "numbers = list(range(5_000_000)); print(sum(numbers))" 2>&1 | grep -E "^[0-9]|Elapsed|Maximum resident"12499997500000 Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.15 Maximum resident set size (kbytes): 204128
/usr/bin/time -v (not the shell's time) reports wall time, CPU time and peak memory of a command. Use it to compare before and after an optimisation.
Practice
- Run the 60-second check on your machine and write down normal values, so you'll recognise abnormal ones later.
- Start
stress-ng --cpu 1 --timeout 30sand find it intop. Note the load average before and after. - Start a temporary service with
systemd-run -p MemoryMax=100Mthat tries to use more, and watch it get limited or killed injournalctl. - Find the
LimitNOFILEof a running service:systemctl show nginx -p LimitNOFILE.
1.free -h shows very little free memory but lots of buff/cache. Is the server out of memory?
2.The load average is 8.0 on a 2-core server. What does that mean?
3.How do you stop one service from using more than 512 MB of RAM?
4.An app logs "Too many open files". What's the usual fix?