Learn / Linux / Processes & System
Lesson 26 of 74

Monitoring CPU, Memory and Load

The first five minutes on a slow server: uptime and what load average really measures, every line of top and its keys, CPU time split into us, sy, wa and st, free and why 'available' matters more than 'free', vmstat for trends, htop, df, a USE-method checklist, and why containers show the host's numbers.

25 min read Report a problem Hands-on lab included 6-question quiz

Why look before you act

"The server is slow" is the most common alert you'll get, and the worst response is to restart things at random. A restart destroys the evidence and the problem comes back. Experienced engineers spend the first few minutes looking: which resource is running out, and who is using it?

There are only a few resources to check:

What can run out

CPUuptime · top · vmstat r
Memoryfree · top (M) · vmstat si/so
Disk I/Otop wa · vmstat b · iostat
Disk spacedf -h · du
Networkss · ip -s (Networking module)

For each one, ask: how much is used (utilisation), is work queueing (saturation), and are there errors? This is the "USE method".

This lesson covers the tools for the first four. You'll find the same numbers in every monitoring dashboard (Grafana, Datadog, CloudWatch): knowing what they mean on the command line means knowing what the graphs mean too.

uptime and the load average

bash
uptime
nproc
text
 16:17:58 up  1:32,  0 user,  load average: 0.25, 0.20, 0.18
2
PartMeaning
up 1:32time since boot. An unexpected short uptime = something rebooted the machine
0 userlogged-in sessions
load average: 0.25, 0.20, 0.18averages over the last 1, 5 and 15 minutes
2nproc: CPU cores

What load actually measures

The load average is the average number of processes that are:

  • running on a CPU,
  • waiting for a CPU (runnable), or
  • blocked on disk I/O (state D), a Linux-specific addition.

So it measures demand, not percentage. Always compare it with the core count:

Load ÷ coresMeaning
< 0.7headroom
≈ 1.0fully used
> 1.0work is queueing; latency grows

Read the three numbers as a trend: 6.2, 3.1, 1.0 is getting worse; 1.0, 3.1, 6.2 is recovering. And remember the D part: a high load with idle CPUs almost always means processes stuck on a slow disk or network filesystem.

Try it · Task 1 of 4

Load and cores

Read how busy the server is, and record how many CPU cores it has.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

The load average is the average number of processes that are running or waiting to run (plus those stuck waiting on disk), over the last 1, 5 and 15 minutes. It only means something next to the number of CPU cores: a load of 4 is fully busy on 4 cores, and badly overloaded on 1.

1. uptime

bash
uptime
cat /proc/loadavg
nproc
text
 16:17:58 up  1:32,  0 user,  load average: 0.25, 0.20, 0.18
0.25 0.20 0.18 3/188 43
2
PartMeaning
16:17:58current time
up 1:32time since boot (1 hour 32 minutes); a surprisingly short uptime means a recent reboot or crash
0 userlogged-in users
0.25, 0.20, 0.18load over the last 1, 5 and 15 minutes
3/188 (in /proc/loadavg)runnable tasks right now / total tasks
2 (nproc)CPU cores

2. Reading the numbers

Divide the load by the cores:

Load ÷ coresMeaning
below 0.7comfortable
around 1.0fully used
well above 1.0processes are queueing for the CPU (or stuck on disk)

And read the three numbers as a trend: 8.0, 4.0, 1.0 means "it's getting worse right now", while 1.0, 4.0, 8.0 means "it was bad and is recovering".

2 · Your task

Save the number of CPU cores this machine reports (just the number) to /root/cores.txt.

Expected result: cat /root/cores.txt prints the same number as nproc.

Hint: the commands, explained
text
nproc > /root/cores.txt

What each part does

  • nproc: print the number of CPU cores available. A load average equal to this number means the CPUs are fully busy.
First start the lab machine in the terminal panel on the right.

top: the live view

top refreshes every few seconds. Here is a snapshot in batch mode (top -b -n 1), useful for scripts and for sharing in tickets:

text
top - 16:17:58 up  1:32,  0 user,  load average: 0.25, 0.20, 0.18
Tasks:  10 total,   2 running,   8 sleeping,   0 stopped,   0 zombie
%Cpu(s): 23.8 us,  0.0 sy,  0.0 ni, 76.2 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st 
MiB Mem :   8023.6 total,   6389.8 free,    826.2 used,   1061.8 buff/cache     
MiB Swap:      0.0 total,      0.0 free,      0.0 used.   7197.5 avail Mem 

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
     32 root      20   0   15536  10112   6676 R  60.0   0.1   0:05.02 img-resize
      1 root      20   0    4760   3688   3432 S   0.0   0.0   0:00.02 shack-init
     33 root      20   0  179392 174092   6804 S   0.0   2.1   0:00.12 cache-warmer
     35 appsvc    20   0   15536  10252   6824 S   0.0   0.1   0:00.01 shop-web

The CPU line

%Cpu(s) splits all CPU time into categories that add up to 100:

FieldTime spentHigh value suggests
usrunning user programsan application is busy: find it in the list
syin the kernel on behalf of programsheavy system calls, networking, too many processes
nirunning niced programsbatch jobs (harmless, they yield)
ididlenothing to worry about
waidle, waiting for I/Oa slow or overloaded disk
hi / sihandling hardware / software interruptsvery high network traffic
ststolen by the hypervisorcloud: noisy neighbours, or a burstable instance (like AWS t3) out of credits

wa and st are the two that save the most time. Both make a server feel slow, and neither is fixed by optimising your application.

The process list

ColumnMeaning
PR / NIpriority / niceness
VIRTvirtual memory reserved (ignore, mostly)
RESresident memory: real RAM in use (same as RSS)
SHRthe part of RES shared with other processes (libraries)
Sstate: R, S, D, T, Z
%CPUCPU in the last interval. 100% = one full core, so on 8 cores a process can show up to 800%
TIME+total CPU time consumed

Keys inside top

KeyDoesKeyDoes
Psort by CPUcfull command lines
Msort by memoryushow one user's processes
Tsort by CPU timekkill (asks PID, signal)
1per-core CPU linesrrenice
Hshow threadsqquit

htop is a friendlier alternative with colour bars, mouse support and a tree view (F5). It's on most servers; use whichever you prefer, but know top because it's always there.

Try it · Task 2 of 4

Find the CPU hog in top

Use top to find the process using the most CPU.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

top is a live, refreshing view of the whole system: summary lines at the top, the busiest processes below. Unlike ps, its %CPU is current usage (over the last refresh interval), so it shows what's happening right now.

1. Run top

Run top in the terminal and watch it refresh. Useful keys while it runs:

KeyDoes
Psort by CPU (default)
Msort by memory
1show each CPU core separately
cshow full command lines
kkill a process (asks for the PID)
qquit

For a one-off snapshot (and for scripts), use batch mode:

bash
top -b -n 1 | head -15

-b = batch (plain text, no screen control), -n 1 = one refresh, then exit.

text
top - 16:17:58 up  1:32,  0 user,  load average: 0.25, 0.20, 0.18
Tasks:  10 total,   2 running,   8 sleeping,   0 stopped,   0 zombie
%Cpu(s): 23.8 us,  0.0 sy,  0.0 ni, 76.2 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st 
MiB Mem :   8023.6 total,   6389.8 free,    826.2 used,   1061.8 buff/cache     
MiB Swap:      0.0 total,      0.0 free,      0.0 used.   7197.5 avail Mem 

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
     32 root      20   0   15536  10112   6676 R  60.0   0.1   0:05.02 img-resize
      1 root      20   0    4760   3688   3432 S   0.0   0.0   0:00.02 shack-init
      8 root      20   0    3132   2060   1948 S   0.0   0.0   0:00.00 sleep
     31 root      20   0    4768   3216   2880 S   0.0   0.0   0:00.00 su
     33 root      20   0  179392 174092   6804 S   0.0   2.1   0:00.12 cache-warmer
     35 appsvc    20   0   15536  10252   6824 S   0.0   0.1   0:00.01 shop-web

2. The summary lines

LineRead it as
top - ... load averagethe same as uptime
Tasks: ... 0 zombieprocess counts by state; watch running and zombie
%Cpu(s): 23.8 ustime in user programs
0.0 sytime in the kernel (high = lots of system calls, networking, context switches)
0.0 nitime in niced programs
76.2 ididle. 100 minus idle = how busy the CPU is
0.0 wawaiting for disk I/O. High wa = a disk problem, not a CPU problem
0.0 st"steal": time a cloud hypervisor gave to other VMs. High = noisy neighbours or exhausted burst credits
MiB Mem / Swapmemory, explained in the next step

In the process list, RES is real memory (like RSS in ps) and S is the state. img-resize is at the top, in state R (running), using most of the CPU this lab may use.

2 · Your task

Find the process using the most CPU in top and save its name (the COMMAND column) to /root/top-cpu.txt.

Expected result: /root/top-cpu.txt contains the name of the busiest process.

Hint: the commands, explained
text
top -b -n 1 | head -10
echo img-resize > /root/top-cpu.txt

What each part does

  • top -b -n 1: run top in batch mode (plain text, no screen refresh) for 1 round. | head -10: the summary plus the first few processes.
  • top sorts by %CPU by default, so the first process line is the CPU hog. Write its name (COMMAND column) into the file.
First start the lab machine in the terminal panel on the right.

free: memory, correctly

bash
free -h
text
               total        used        free      shared  buff/cache   available
Mem:           7.8Gi       826Mi       6.2Gi        12Mi       1.0Gi       7.0Gi
Swap:             0B          0B          0B

The key idea: Linux uses otherwise-empty RAM as a page cache for files it has read or written. Reading the same file again comes from memory instead of disk, which is a huge speed-up. When a program needs memory, the cache is dropped instantly.

How RAM is divided

usedprograms' memory
buff/cachefile cache · mostly reclaimable
freecompletely unused

available ≈ free + the reclaimable part of buff/cache. That's the number to alert on.

ColumnMeaning
usedmemory programs are using
freememory nobody is using. Low is normal on a busy server
sharedshared memory (tmpfs, shared segments)
buff/cachekernel buffers and file cache
availableestimate of memory programs can still get without swapping. This is the real headroom

So "free memory is only 200 MB!" is usually a false alarm, while "available is 200 MB and falling" is real. The raw numbers live in /proc/meminfo:

text
MemTotal:        8216208 kB
MemFree:         6542924 kB
MemAvailable:    7370156 kB
Buffers:           22176 kB
Cached:           995444 kB
SwapTotal:             0 kB

To find who uses the memory, sort by resident size:

bash
ps aux --sort=-rss | head -4
text
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root          33  1.1  2.1 179392 174092 ?       Ss   16:17   0:00 python3 /opt/shop/cache.py
appsvc        35  0.0  0.1  15536 10252 ?        Ss   16:17   0:00 python3 /opt/shop/web.py
root          32 48.0  0.1  15536 10112 ?        Rs   16:17   0:05 python3 /opt/shop/resize.py

What happens when memory really runs out (swap and the OOM killer) is the next lesson.

Try it · Task 3 of 4

Memory

Work out how much memory is really free, and which process uses the most.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

Linux uses spare memory as a cache for files it has read, because unused RAM is wasted RAM. That cache is handed back instantly when programs need memory. So "free" memory on a healthy server is often low, and that's fine. The number that answers "how much memory can programs still get?" is available.

1. free

bash
free -h

-h = human-readable units (Gi, Mi). -m for megabytes.

text
               total        used        free      shared  buff/cache   available
Mem:           7.8Gi       826Mi       6.2Gi        12Mi       1.0Gi       7.0Gi
Swap:             0B          0B          0B
ColumnMeaning
totalinstalled RAM
usedused by programs
freecompletely unused
buff/cachefile cache and buffers: reclaimable
availablewhat programs can still get without swapping: roughly free + reclaimable cache. Watch this one
Swapdisk space used as overflow memory (none on this machine)

2. Who uses the memory?

bash
ps aux --sort=-rss | head -4

Or in top, press M.

text
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root          33  1.1  2.1 179392 174092 ?       Ss   16:17   0:00 python3 /opt/shop/cache.py
appsvc        35  0.0  0.1  15536 10252 ?        Ss   16:17   0:00 python3 /opt/shop/web.py
root          32 48.0  0.1  15536 10112 ?        Rs   16:17   0:05 python3 /opt/shop/resize.py

The cache script holds about 170 MB of real memory (RSS 174092 KB), far more than anything else. On this lab, which is capped at 512 MB, that's a third of everything it may use.

2 · Your task

Find the process using the most memory (largest RSS/RES) and save its process name as top shows it to /root/top-mem.txt.

Expected result: /root/top-mem.txt contains the name of the biggest memory user.

Hint: the commands, explained
text
top -b -n 1 -o %MEM | head -8
echo cache-warmer > /root/top-mem.txt

What each part does

  • -o %MEM: sort by memory instead of CPU. The first process line now uses the most RAM.
  • Write its COMMAND name into the file.
First start the lab machine in the terminal panel on the right.

Snapshots can mislead: a CPU spike at the moment you ran top may be nothing. vmstat prints one line per interval so you can see what's sustained:

bash
vmstat 1 5

Every 1 second, 5 times. The first line is the average since boot, so ignore it.

text
procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st gu
 1  0      0 6543124  22176 1065236    0    0   521   197  348    3  4  1 94  1  0  0
 1  0      0 6543124  22176 1065276    0    0     0     0  267  155 26  0 74  0  0  0
 1  0      0 6543124  22176 1065276    0    0     0     0  270  157 26  0 74  0  0  0
 1  0      0 6543124  22176 1065276    0    0     0     0  264  175 26  0 73  0  0  0
 1  0      0 6543124  22176 1065276    0    0     0     0  285  158 27  0 72  0  1  0
GroupColumnsLook for
procsr runnable, b blockedr > cores = CPU saturated; b > 0 for long = I/O trouble
memoryswpd, free, buff, cache (KB)free + cache shrinking steadily
swapsi, soany sustained swap activity = out of RAM
iobi, boblocks read/written per second
systemin interrupts, cs context switcheshuge cs = too many threads fighting
cpuus sy id wa stsame as top

Here: one process constantly runnable, nothing blocked, no swapping, a quiet disk. The server is CPU-bound, by one process.

For per-disk detail, iostat -x 1 (package sysstat) shows each device's utilisation and wait times; pidstat and sar from the same package record history.

Disk space: df

A full disk breaks things in confusing ways: databases stop, logs stop, deploys fail with odd errors. Always check it:

bash
df -h /
text
Filesystem      Size  Used Avail Use% Mounted on
overlay         252G   20G   23G  48% /

(The lab machine runs on an overlay filesystem shared with others, so Size, Used and Avail don't add up exactly.) Finding what fills a disk is covered in the Disk Space and Cleanup lesson.

Containers show the host

Inside a container, nproc, free and top read /proc, which describes the host. The container's own limits are cgroup settings that those classic tools don't read. That's why the lab machines show several cores and gigabytes of RAM, while each lab is actually limited to half a core and 512 MB. In Kubernetes, use kubectl top pod and the container's limits; on the host, systemd-cgtop shows usage per service and container.

A five-minute checklist

text
uptime                              # load vs nproc; recent reboot?
top  (then 1, P, M)                 # us/sy vs wa vs st; who's on top
free -h                             # available, swap used
vmstat 1 5                          # sustained r, b, si/so, wa
df -h                               # any filesystem near 100%?
dmesg -T | tail                     # kernel errors: OOM kills, disk errors
journalctl -p err --since "1 hour ago"   # recent errors (Logs module)

Turning this into a script, as in the lab, means the first minute of every incident is the same, and you can paste the result straight into the ticket.

Panicking about low "free" memory. Look at "available". Linux deliberately fills RAM with cache.

Reading load without core count. Load 6 is idle-ish on 32 cores and a crisis on 2.

Blaming the app for high load with idle CPU. That's D state: check wa, vmstat b and the storage.

Trusting one snapshot. Use vmstat 1 or watch top for a minute before deciding.

Restarting first. You lose the evidence. Capture top -b -n 1, free -h and ps aux first, then act.

"What is load average?" The average number of runnable plus uninterruptible (I/O-blocked) processes over 1, 5 and 15 minutes. Compare it with the number of cores.

"The server is slow. What do you check first?" uptime (load vs cores), top (CPU split, especially wa and st, and top processes), free -h (available, swap), vmstat for trends, df -h, then dmesg and logs.

"What's the difference between free and available memory?" free is unused RAM; available also counts cache that can be reclaimed, so it's what applications can still get.

"High load but the CPU is idle. Why?" Processes in D state waiting on disk or NFS I/O; check wa and the storage.

"What is CPU steal?" Time the VM was ready to run but the hypervisor ran something else: noisy neighbours or exhausted burst credits.

Try it · Task 4 of 4

A health-check script

Save the checks as a script you can run in the first minute of the next alert.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

top and free are snapshots. vmstat prints a new line every few seconds, so you can see trends: is the CPU constantly busy, is anything waiting on the disk, is the machine swapping? And once you know which checks you run every time, put them in a script.

1. vmstat

bash
vmstat 1 5

One line per second, five lines. The first line is an average since boot; read the later ones.

text
procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st gu
 1  0      0 6543124  22176 1065236    0    0   521   197  348    3  4  1 94  1  0  0
 1  0      0 6543124  22176 1065276    0    0     0     0  267  155 26  0 74  0  0  0
 1  0      0 6543124  22176 1065276    0    0     0     0  270  157 26  0 74  0  0  0
 1  0      0 6543124  22176 1065276    0    0     0     0  264  175 26  0 73  0  0  0
 1  0      0 6543124  22176 1065276    0    0     0     0  285  158 27  0 72  0  1  0
ColumnWatch for
rprocesses running or waiting for CPU. Constantly above the core count = CPU-bound
bprocesses blocked on I/O (state D). Constantly above 0 = disk trouble
si / soswap in / out per second. Anything non-zero for long = out of memory
bi / boblocks read from / written to disk
us sy id wa stthe same CPU split as top

Here: one process always running (r 1, the resizer), nothing blocked, no swapping, the disk quiet. A CPU-bound problem, not memory or disk.

2. A health snapshot script

Write the checks into /root/health.sh, for example:

bash
#!/bin/bash
echo "=== $(hostname) at $(date) ==="
uptime
echo; free -h
echo; df -h /
echo; echo "Top 5 by CPU:"
ps -eo pid,user,%cpu,%mem,comm --sort=-%cpu | head -6
echo; echo "Top 5 by memory:"
ps -eo pid,user,%mem,rss,comm --sort=-rss | head -6

Save it with nano /root/health.sh (or a heredoc), then make it executable and run it:

text
chmod +x /root/health.sh
/root/health.sh
2 · Your task

Create an executable script /root/health.sh whose output includes at least:

  • the load average (from uptime),
  • the memory summary (from free),
  • the busiest processes by CPU (so img-resize appears).

Expected result: running /root/health.sh prints a line with "load average", the Mem: line, and img-resize.

Hint

Use the example script above. Remember chmod +x /root/health.sh.

First start the lab machine in the terminal panel on the right.

Summary

  • Check CPU, memory, disk I/O, disk space (and network): utilisation, saturation, errors.
  • Load average = runnable + D-state processes over 1/5/15 min; divide by nproc.
  • top: us app work, sy kernel, wa disk wait, st steal; RES is real memory; P, M, 1, top -b -n 1.
  • free -h: watch available; buff/cache is reclaimable.
  • vmstat 1: r vs cores, b, si/so, wa. df -h for space.
  • Containers see the host's numbers; their limits are cgroups.
Check your understanding

Quick quiz

Feedback