DEV Community

Cover image for How to Diagnose Linux Performance: A Developer's Field Guide to Finding the Bottleneck
Mango Developer
Mango Developer

Posted on Originally published at mangodeveloper.com

How to Diagnose Linux Performance: A Developer's Field Guide to Finding the Bottleneck

The first time I got paged for "the server is slow," I SSHed in, ran top, saw load average 4.5, and concluded "CPU bound." I spent an hour tuning nginx workers before realizing the actual problem was iowait on a dying disk. Top told me everything and nothing. The bottleneck was hidden in a column I'd never learned to read. This is the article I wish someone had handed me that night.

Linux performance diagnosis isn't memorizing 50 commands. It's a method: figure out which resource is saturated, find the process responsible, understand why it's saturated, fix the root cause. The tools are the means, not the end. I'll walk through the method with the actual commands, what their output means, and the production stories that taught me each one.

The Mental Model: USE Method

Brendan Gregg's USE method-Utilization, Saturation, Errors-is the framework I reach for first. For every resource (CPU, memory, disk, network), check three things:

  • Utilization: how busy is it (e.g., 80% CPU)
  • Saturation: how much work is queued waiting (e.g., run queue length, disk queue depth)
  • Errors: is anything failing (e.g., packet drops, ECC memory errors, disk read errors)
Resource Utilization Saturation Errors
CPU mpstat %usr+%sys run queue (uptime), perf sched dmesg for MCE
Memory free -h used vs available swap I/O, vmstat si/so dmesg for OOM, edac
Disk iostat -x %util iostat await, queue depth dmesg for I/O errors, smartctl
Network nstat packets/sec, ip -s link ss -l backlog, drops nstat TcpExtListenOverflows

You don't have to check every cell every time. The method gives you a checklist so you don't tunnel-vision on the first thing you see.

Load Average: What It Actually Means

uptime shows three numbers:

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode

$ uptime
10:42:13 up 23 days, 4:17, 3 users, load average: 1.05, 2.34, 4.12

Enter fullscreen mode Exit fullscreen mode

Those are the exponentially weighted moving averages of the run queue length over 1, 5, and 15 minutes. "Run queue length" means the number of processes that are runnable (want CPU) plus the number that are in uninterruptible sleep (waiting on disk I/O, usually).

The trick: load average includes disk-waiting processes. A load of 4 on a 4-core box might be 4 processes burning CPU (bad), or 4 processes blocked on a slow disk (different problem). The number alone doesn't tell you. You need to look at CPU states.

A quick triage command:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
uptime; echo; vmstat 1 5

Enter fullscreen mode Exit fullscreen mode


plaintext

vmstat 1 5 prints five 1-second snapshots. The columns to watch:

  • r: runnable processes. Sustained > core count = CPU saturated.
  • b: processes in uninterruptible sleep (D state). Sustained > 0 = disk-bound.
  • us: user CPU. High = your app is computing.
  • sy: system CPU. High = kernel work (syscalls, softirq).
  • wa: iowait. High = waiting on disk.
  • id: idle. Should be > 0 if you have headroom.
Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
procs -----------memory---------- ---cpu-- -----
r b swpd free buff cache si so us sy id wa st
4 0 0 123456 89012 9876543 0 0 85 10 5 0 0 <- CPU bound
0 8 0 456789 89012 8765432 0 0 10 5 5 80 0 <- disk bound
2 1 234567 12345 89012 1234567 20 30 30 20 0 0 0 <- swapping, memory pressure

Enter fullscreen mode Exit fullscreen mode


markdown

The last column, st, is steal time-CPU the hypervisor gave to another tenant. Persistent st > 5 on a cloud VM means your noisy neighbor is eating your compute. The fix is to move instances or upgrade to dedicated tenancy.

CPU: When It's Compute-Bound

top and htop are fine for a quick look. For real diagnosis, mpstat and pidstat give you per-core and per-process breakdowns.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
mpstat -P ALL 1

Enter fullscreen mode Exit fullscreen mode


plaintext

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
10:42:13 AM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle
10:42:14 AM all 3.50 0.00 1.20 0.00 0.00 0.30 0.00 0.00 0.00 95.00
10:42:14 AM 0 5.00 0.00 2.00 0.00 0.00 0.00 0.00 0.00 0.00 93.00
10:42:14 AM 1 2.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 98.00

Enter fullscreen mode Exit fullscreen mode


plaintext

If one core is at 100% usr and the others are idle, you have a single-threaded hot path. Distribution across cores is the issue, not total CPU.

Per-process CPU:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
pidstat 1

Enter fullscreen mode Exit fullscreen mode


plaintext

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
10:42:14 AM UID PID %usr %system %guest %wait %CPU CPU Command
10:42:15 AM 0 1234 85.00 2.00 0.00 0.00 87.00 2 python3
10:42:15 AM 0 5678 0.00 12.00 0.00 0.00 12.00 0 kworker/u8:2

Enter fullscreen mode Exit fullscreen mode


markdown

%wait is time spent waiting for CPU while runnable. Persistent %wait > 5 means the process wants more CPU than it's getting-not necessarily a bug, but a signal.

Softirq: The Hidden CPU Sink

Softirqs are kernel work that runs in interrupt context but deferrable. High softirq CPU on a network-heavy box usually means the kernel is processing packets in softirq instead of using NAPI polling.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
watch -n 1 'cat /proc/softirqs | head -20'

Enter fullscreen mode Exit fullscreen mode


plaintext

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
CPU0 CPU1 CPU2 CPU3
HI: 1 0 0 0
TIMER: 1234567 1234567 1234567 1234567
NET_TX: 0 0 0 0
NET_RX: 9876543 1234567 987654 876543 <- imbalanced
BLOCK: 123456 234567 345678 456789
IRQ_POLL: 0 0 0 0
TASKLET: 0 0 0 0
SCHED: 4567890 4567890 4567890 4567890
HRTIMER: 0 0 0 0
RCU: 3456789 3456789 3456789 3456789

Enter fullscreen mode Exit fullscreen mode


plaintext

If NET_RX is concentrated on one CPU while others sit idle, RPS/RFS isn't enabled. Fix:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

Enable RPS on a 10G NIC (queues go to all CPUs)

for i in /sys/class/net/eth0/queues/rx-*/rps_cpus; do
echo ffff > "$i" # bitmask: all 16 CPUs
done

Enter fullscreen mode Exit fullscreen mode


markdown

perf: When You Need to Know What Code Is Hot

top tells you which process is burning CPU. perf tells you which function.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo perf record -F 99 -p 1234 -g -- sleep 30
sudo perf report

Enter fullscreen mode Exit fullscreen mode


plaintext

For a flame graph, install FlameGraph scripts:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
git clone https://github.com/brendangregg/FlameGraph.git
sudo perf record -F 99 -p 1234 -g -- sleep 30
sudo perf script | FlameGraph/stackcollapse-perf.pl | FlameGraph/flamegraph.pl > flame.svg

Enter fullscreen mode Exit fullscreen mode


markdown

Open flame.svg in a browser. Wider bars = more CPU time. The stack at the top of each bar is the leaf function. Look for surprisingly wide bars and drill in.

Memory: Free, Buffers, Cache, and the Truth About "Used"

free -h lies to you in a useful way:

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
total used free shared buff/cache available
Mem: 31Gi 12Gi 2.1Gi 245Mi 17Gi 18Gi
Swap: 4.0Gi 1.2Gi 2.8Gi

Enter fullscreen mode Exit fullscreen mode


plaintext

used includes buffers and cache in older versions of free; newer versions separate them. The number you care about is available-that's how much memory is reclaimable without swapping. A box with free=0 and available=10Gi is healthy. A box with free=0 and available=0 is in trouble.

The deeper view:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
cat /proc/meminfo | head -30

Enter fullscreen mode Exit fullscreen mode


plaintext

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
MemTotal: 32882312 kB
MemFree: 123456 kB
MemAvailable: 18456789 kB
Buffers: 890123 kB
Cached: 17234567 kB
SwapCached: 12345 kB
Active: 12345678 kB
Inactive: 9876543 kB
...
Slab: 1234567 kB
SReclaimable: 234567 kB
SUnreclaim: 1000000 kB

Enter fullscreen mode Exit fullscreen mode


plaintext

Slab is kernel memory for inodes, dentries, file handles. SReclaimable is reclaimable under pressure. A box with millions of open files can have a 5GB slab; that's normal.

Swapping: The Slow Death

Linux swaps even when there's plenty of RAM, because of vm.swappiness (default 60, range 0-100). Swappiness isn't "how likely to swap"; it's the relative cost the kernel assigns to swapping vs dropping cache.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sysctl vm.swappiness # 60

Enter fullscreen mode Exit fullscreen mode


plaintext

For a database server, set swappiness to 1 or 10:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo sysctl -w vm.swappiness=1
echo "vm.swappiness=1" | sudo tee -a /etc/sysctl.d/99-swappiness.conf

Enter fullscreen mode Exit fullscreen mode


plaintext

Detect swapping in real time:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
vmstat 1

columns si (swap in) and so (swap out)

Enter fullscreen mode Exit fullscreen mode


plaintext

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
2 1 1234567 12345 890123 1234567 120 340 450 380 12000 15000 25 10 30 35 0

Enter fullscreen mode Exit fullscreen mode


plaintext

si and so in the hundreds means the box is actively paging. Performance is cratering. The fix is either more RAM (the obvious answer) or finding the memory hog:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
ps aux --sort=-%mem | head -10

Enter fullscreen mode Exit fullscreen mode


plaintext

Or, more precisely, sort by RSS:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
ps -eo pid,user,rss,comm --sort=-rss | head -10

Enter fullscreen mode Exit fullscreen mode


markdown

OOM Killer

When the kernel runs out of memory, it picks a process to kill based on a score (/proc/<pid>/oom_score). The heuristic favors memory-hungry processes, which is usually what you want killed. But it doesn't always pick the right one.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
dmesg -T | grep -i "killed process"

Enter fullscreen mode Exit fullscreen mode


plaintext

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
[2024-11-12 03:14:22] Out of memory: Killed process 1234 (java) total-vm:8G, anon-rss:6G

Enter fullscreen mode Exit fullscreen mode


markdown

If the OOM killer is firing, your box is genuinely undersized. Don't tune oom_score_adj to protect a process unless you understand what you're trading off-you'll just shift the kill to something else.

Disk: iowait and the Slow Death

Disk is the resource developers underestimate most. A box with plenty of CPU and RAM can still crawl if its disks are saturated.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
iostat -xz 1

Enter fullscreen mode Exit fullscreen mode


plaintext

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
Device r/s w/s rkB/s wkB/s rrqm/s wrqm/s %util r_await w_await aqu-sz
nvme0n1 120.50 34.20 15488.00 4387.00 0.00 2.00 85.20 1.20 5.40 0.42
sda 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00

Enter fullscreen mode Exit fullscreen mode


markdown

The columns to know:

  • %util: percentage of time the device had at least one I/O in flight. Sustained >80% = saturated.
  • r_await / w_await: average time per read/write in ms, including queue time. >10ms on NVMe is slow; >50ms on HDD is normal.
  • aqu-sz: average queue depth. >1 means I/O is queuing.
  • r/s, w/s: IOPS. Compare against device spec.

A box at 100% %util with 200 IOPS and high await is slow because the disk is slow. A box at 100% %util with 50,000 IOPS and low await is just busy-your app is hammering it.

iotop: Which Process Is Doing the I/O

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo iotop -oP

Enter fullscreen mode Exit fullscreen mode


plaintext

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
TID PRIO USER DISK READ DISK WRITE SWAPIN IO> COMMAND
1234 be/4 app 5.20 M/s 0.00 B/s 0.00 % 45.20 % postgres -D /var/lib/postgresql
5678 be/4 app 0.00 B/s 8.40 M/s 0.00 % 12.30 % dd if=/dev/zero of=/tmp/bigfile

Enter fullscreen mode Exit fullscreen mode


markdown

For containers, iotop shows the host process. Map back to the container with docker top or by PID namespace.

biolatency: Distribution, Not Average

Averages hide outliers. biolatency from the BCC tools shows you the distribution:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo biolatency 10

Enter fullscreen mode Exit fullscreen mode


plaintext

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
Tracing block device I/O... Hit Ctrl-C to end.

usecs : count distribution
0 -> 1 : 0 | |
2 -> 3 : 0 | |
4 -> 7 : 123 | |
8 -> 15 : 4567 |********** |
16 -> 31 : 23456 |*********************************************|
32 -> 63 : 12345 |
************************ |
64 -> 127 : 567 |* |
128 -> 255 : 234 | |
256 -> 511 : 89 | |
512 -> 1023 : 45 | |
1024 -> 2047 : 12 | |
2048 -> 4095 : 5 | |
4096 -> 8191 : 2 | |
8192 -> 16383 : 1 | |

Enter fullscreen mode Exit fullscreen mode


plaintext

If you see a long tail at 100ms+, you have outliers-probably a failing drive or a noisy neighbor on shared storage. SMART checks:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo smartctl -a /dev/sda | grep -iE 'reallocat|pending|uncorrect|error'

Enter fullscreen mode Exit fullscreen mode


markdown

Any non-zero value in Reallocated_Sector_Ct, Current_Pending_Sector, or Offline_Uncorrectable is the disk's way of telling you it's about to die.

Network: Sockets, Drops, and Latency

ss is the modern netstat. Use it.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
ss -s

Enter fullscreen mode Exit fullscreen mode


plaintext

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
Total: 1234
TCP: 567 (estab 234, closed 100, orphaned 0, timewait 100)

Transport Total IP IPv6
RAW 1 0 1
UDP 5 3 2
TCP 567 300 267
INET 573 303 270
FRAG 0 0 0

Enter fullscreen mode Exit fullscreen mode


plaintext

Per-socket detail:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
ss -tinap state established '( sport = :443 or dport = :443 )'

Enter fullscreen mode Exit fullscreen mode


plaintext

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
Recv-Q Send-Q Local Address:Port Peer Address:Port Process
0 0 1.2.3.4:443 5.6.7.8:54321 users:(("nginx",pid=1234,fd=10))
0 0 1.2.3.4:443 5.6.7.9:54322 users:(("nginx",pid=1234,fd=11))
cubic wscale:7,2 rto:204 rtt:0.123/0.045 mss:1448 pmtu:1500 rcvmss:1228 advmss:1448 cwnd:10 bytes_sent:123456 bytes_retrans:12

Enter fullscreen mode Exit fullscreen mode


plaintext

bytes_retrans non-zero means packets were lost and retransmitted. Persistent retrans on a connection means network problems-not your app.

Drops and Overflows

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
nstat -az | grep -iE 'drop|overflow|fail|reset'

Enter fullscreen mode Exit fullscreen mode


plaintext

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
TcpExtListenOverflows 123 1.0
TcpExtListenDrops 45 0.4
TcpExtEmbryonicRsts 12 0.1
IpExtInOctets 1234567890

Enter fullscreen mode Exit fullscreen mode


plaintext

ListenOverflows means the accept queue filled up and connections were dropped. The fix is either raising net.core.somaxconn and your app's listen backlog, or figuring out why your app isn't accepting fast enough.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sysctl net.core.somaxconn
sysctl net.ipv4.tcp_max_syn_backlog

Enter fullscreen mode Exit fullscreen mode


plaintext

For a high-traffic web server, bump both:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo sysctl -w net.core.somaxconn=4096
sudo sysctl -w net.ipv4.tcp_max_syn_backlog=8192

Enter fullscreen mode Exit fullscreen mode


markdown

conntrack Exhaustion

If you're behind NAT or running a firewall, every connection has a conntrack entry. The table has a finite size:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo cat /proc/sys/net/netfilter/nf_conntrack_count
sudo cat /proc/sys/net/netfilter/nf_conntrack_max

Enter fullscreen mode Exit fullscreen mode


plaintext

If count is close to max, new connections stall. Common on busy Docker hosts. Fix:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
echo 262144 | sudo tee /proc/sys/net/netfilter/nf_conntrack_max
echo 65536 | sudo tee /proc/sys/net/netfilter/nf_conntrack_buckets

Enter fullscreen mode Exit fullscreen mode


plaintext

The kernel-doc says nf_conntrack_buckets is set at module load and read-only afterward. To change it permanently, write to /etc/modprobe.d/nf_conntrack.conf:

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


conf
options nf_conntrack hashsize=65536

Enter fullscreen mode Exit fullscreen mode


markdown

sar: Long-Term History

sar records what happened while you were asleep. On Debian/Ubuntu, install sysstat and enable:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo apt install sysstat
sudo sed -i 's/false/true/' /etc/default/sysstat
sudo systemctl enable --now sysstat

Enter fullscreen mode Exit fullscreen mode


plaintext

After a day, you can query:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sar -u # CPU
sar -r # memory
sar -d # disk
sar -n DEV # network per interface
sar -q # run queue

Enter fullscreen mode Exit fullscreen mode


plaintext

Specify a time:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sar -u -s 02:00:00 -e 04:00:00 # last night's 2 AM to 4 AM

Enter fullscreen mode Exit fullscreen mode


plaintext

The killer feature: comparing today to last week:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sar -u -f /var/log/sysstat/sa11 # the 11th of the month

Enter fullscreen mode Exit fullscreen mode


markdown

If a problem is intermittent (slow every night at 3 AM, fine during the day), sar will show you exactly when it started.

eBPF: The Modern Way

eBPF is the biggest thing to happen to Linux observability in a decade. It lets you run sandboxed programs in the kernel that observe anything-syscalls, function entries, packet drops, scheduler decisions-without modifying the kernel or restarting your app.

The two main userlands are BCC (Python tools, bigger) and bpftrace (one-liners, smaller).

Install on Debian/Ubuntu:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo apt install bpftrace bcc-tools

Enter fullscreen mode Exit fullscreen mode


plaintext

Useful one-liners:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

Count syscalls by process for 10 seconds

sudo bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count(); } interval:s:10 { exit(); }'

Show file opens with their filenames

sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat { join(args->filename); }'

Distribution of read() syscall latency

sudo bpftrace -e 'tracepoint:syscalls:sys_enter_read { @start[tid] = nsecs; }
tracepoint:syscalls:sys_exit_read /@start[tid]/ {
@us = hist((nsecs - @start[tid]) / 1000); delete(@start[tid]);
}'

Count TCP retransmits by remote IP

sudo bpftrace -e 'tracepoint:tcp:tcp_retransmit_skb { @[ntop(args->daddr)] = count(); }'

Show which process is doing the most disk I/O

sudo biosnoop # from bcc-tools

Enter fullscreen mode Exit fullscreen mode


markdown

bpftrace is the modern equivalent of strace for system-wide analysis. The examples directory /usr/share/bpftrace/tools/ has dozens of prewritten scripts: bashreadline, cpuwalk, runqlat, bioslat, tcplife. Use them.

perf vs eBPF: When to Use Which

perf samples. It's low-overhead and good for "what's hot." eBPF traces events. It's higher overhead per event but tells you exactly what happened. Use perf for profiling CPU; use eBPF for understanding latency, errors, and event flow.

Common Mistakes

Looking at top and concluding "CPU bound." Symptom: you tune CPU and nothing changes. Fix: check %wa (iowait) and b (blocked processes). The box may be disk-bound while CPU looks busy.

Setting swappiness to 0. Symptom: processes get OOM-killed while there's still swap available. Fix: 1 or 10. Swappiness 0 disables swap use almost entirely, which is rarely what you want.

Adding swap to fix OOM. Symptom: box still slow. Fix: swap hides memory pressure, it doesn't fix it. Find the memory leak. Swap on SSD at 100MB/s is 100× slower than RAM.

Tuning somaxconn without tuning the app's listen backlog. Symptom: connections still drop. Fix: nginx, haproxy, postgres, your Go server-all have their own backlog settings that have to match or exceed somaxconn.

Diagnosing a network problem with ping. Symptom: "ping works, app doesn't." Fix: ping tells you ICMP works. Use ss, tcpdump, mtr, and curl -v to test the actual protocol.

Ignoring kernel logs. Symptom: box reboots, no idea why. Fix: journalctl -k -b -1 for last boot's kernel logs. dmesg -T for current. Most hardware and driver problems show up here.

Trusting container CPU limits as "available CPU." Symptom: container shows 100% in docker stats but host is idle. Fix: container limits are caps, not guarantees. docker stats shows usage against the limit; check the host with mpstat to see if there's actually pressure.

Troubleshooting with Real Production Examples

"The API is slow between 3 AM and 4 AM." sar -u -s 03:00 -e 04:00 showed CPU at 5%, but iostat -xz showed the data disk at 100% %util with 200ms w_await. A nightly backup job was reading the entire database volume. Fix: schedule the backup to read from a replica instead of the primary, or use a snapshot-based backup that doesn't hammer the live disk.

"Goroutines pile up under load and latency triples." pidstat -t 1 showed one Go thread at 100% sys, others idle. perf record showed runtime.futex dominating. The app was using a mutex for every request, contending under load. Fix: sharded the data structure to reduce contention; latency dropped back to baseline.

"Container randomly restarts every few hours." dmesg -T | grep -i oom showed the kernel killing the container's process. The container had no memory limit set, so it grew until the host OOM-killed it. Fix: set a memory limit in compose (mem_limit: 2g), find the leak, and add alerting on container memory usage.

"SSH sessions hang for 30 seconds then resume." nstat -az | grep -i retrans showed TCP retransmits on the host's primary interface. mtr to the gateway showed packet loss starting at the second hop. The switch port was failing. Fix: replaced the cable; nothing wrong with the host.

"Database queries that used to take 5ms now take 500ms." iostat showed disk at 100% util with 4KB random reads. The working set had grown past RAM, and Postgres was hitting disk for every query. Fix: added RAM, tuned shared_buffers, indexed the hot query. pg_stat_statements confirmed which query was the problem.

"Postgres reports high CPU but no queries are running." perf top showed hash_bytes and GetSnapshotData consuming most CPU. This is a known Postgres scaling issue: every connection takes a snapshot, and snapshots scale O(N) with the number of connections. Fix: added PgBouncer in transaction-pooling mode. CPU dropped 80%.

Monitoring: Catching It Before the Page

The cheapest useful stack is Prometheus + node_exporter + Grafana. node_exporter exposes hundreds of metrics out of the box; the standard dashboards (node-exporter-full, etc.) cover CPU, memory, disk, network, and filesystem.

A minimal alert set that catches the most common problems:

Alert Expression For
High CPU 100 - avg(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100 > 80 10m
Memory pressure node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes < 0.1 5m
Disk space node_filesystem_avail_bytes / node_filesystem_size_bytes < 0.1 5m
Disk I/O saturation rate(node_disk_io_time_seconds_total[5m]) > 0.8 10m
Swap in use node_memory_SwapTotal_bytes - node_memory_SwapFree_bytes > 0 5m
Load average node_load1 > count(node_cpu_seconds_total{mode="idle"}) 10m
conntrack near limit node_nf_conntrack_entries / node_nf_conntrack_entries_limit > 0.8 5m

For application-level monitoring, instrument your code. OpenTelemetry is the modern baseline. Don't rely on external metrics alone-an app can have plenty of CPU and still be slow because of a downstream dependency.

Best Practices

  • Always look at distributions, not averages. P99 latency, I/O latency histograms, flame graphs.
  • Save a baseline. When the box was healthy, what did vmstat, iostat, sar show? Without a baseline you can't tell "weird" from "normal weird."
  • Capture first, analyze later. perf record, tcpdump -w, sar-all let you capture and walk away. You can't capture after the user has stopped complaining.
  • Profile in production, briefly. perf record -F 99 -g -- sleep 10 is low enough overhead to run on a live box. Don't run heavy profilers for minutes on end.
  • Check the kernel log first when something is weird. dmesg -T | tail -50. Five seconds, often revealing.
  • Have a "log dump" script ready. When the box is on fire, you don't want to remember which flags perf takes.

CI/CD Considerations

Performance regressions caught in CI are 100× cheaper than those caught in production. The minimum useful pipeline:

  1. Load test on every PR. Use k6, Locust, or vegeta. Compare against a baseline. If P99 latency regressed by 10%, block the PR.
  2. Benchmark suite. Use Go's testing.B, pytest-benchmark, JMH. Track results over time. Show the diff in the PR.
  3. Continuous profiling. Pyroscope, Parca, or Grafana Phlare. Capture profiles in production continuously, diff between deployments.
  4. Canary deploys. Ship to 5% of traffic, watch metrics for 30 minutes, then ship the rest. The metrics to watch: latency, error rate, CPU, memory.

A minimal k6 script for the load test:

JavaScriptCopy

Enter fullscreen mode Exit fullscreen mode


javascript
// tests/load.js
import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
stages: [
{ duration: '30s', target: 50 },
{ duration: '1m', target: 50 },
{ duration: '30s', target: 0 },
],
thresholds: {
http_req_duration: ['p(99)<200'],
http_req_failed: ['rate<0.01'],
},
};

export default function () {
const res = http.get('https://staging.example.com/api/users');
check(res, { 'status 200': (r) => r.status === 200 });
sleep(1);
}

Enter fullscreen mode Exit fullscreen mode


plaintext

Run in CI:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
k6 run --out json=results.json tests/load.js

parse results.json, compare p99 to baseline, fail if regression > threshold

Enter fullscreen mode Exit fullscreen mode

Cost Considerations

Most performance problems are cheap to fix once you've found them. The cost is in finding them:

Component Cost Notes
sysstat / sar $0 Built-in
BCC tools / bpftrace $0 Open source
perf $0 Built-in
Prometheus + Grafana $0 Self-hosted
Datadog / New Relic $15-$50/host/mo Polished, expensive at scale
Pyroscope / Parca continuous profiling $0 self-hosted Or Grafana Cloud paid tier
k6 Cloud $99+/mo Or run k6 OSS on your own runner
APM (Honeycomb, Lightstep) Usage-based Can get expensive fast on high-cardinality

The economic argument for self-hosted monitoring: at 50 hosts, Datadog is $750+/mo. A dedicated Grafana box is $50/mo and does 80% of the job. The 20% gap is polish-alerting UX, integrations, support. Whether that's worth $700/mo depends on your team's size and the cost of an outage.

Alternatives and Comparison

Tool Layer Strength Weakness
top / htop Process Universal Misleading averages
vmstat / mpstat / iostat System Simple, low-overhead No distribution data
sar Historical Captures everything Requires setup
dstat System One screen Mostly subsumed by bpftrace
perf Profiler Kernel-level, samples Steep learning curve
eBPF / bpftrace Tracing Programmable, low-overhead Requires root, modern kernel
SystemTap Tracing Pre-dates eBPF Largely replaced by eBPF
strace Syscalls Per-process detail Very slow on busy processes
tcpdump Network Universal Hard to read without filters
Wireshark Network Great UI Not on servers
bcc tools eBPF Pre-written scripts Python deps
Pyroscope / Parca Continuous profiling Always-on Storage cost at scale

For daily work: htop for triage, vmstat/iostat/ss for quick system views, bpftrace for the deep stuff, sar for history, perf for CPU profiling. Everything else is situational.

Real-World Use Cases

Web app with periodic latency spikes. bpftrace showed a single Go goroutine stuck in runtime.futex for 200ms at a time. The app was using a global sync.Map that was contending under load. Replaced with a sharded structure; spikes gone.

Database server with intermittent slow queries. sar showed disk %util spiking to 100% every hour on the hour. A cron'd log rotate was compressing 50GB of logs and starving the DB of I/O. Moved log rotation to a non-peak time.

Container host with random OOM kills. dmesg showed the kernel killing the sidecar proxy. The container had no memory limit; the proxy was leaking. Set a limit, found the leak, added alerting. No more kills.

Microservice with elevated error rate. Distributed tracing showed 100% of errors came from one downstream service. ss showed the connection count to that service had plateaued at 1000-the HTTP client's connection pool was exhausted. Raised the pool, fixed the leak, errors dropped.

CI runner that got slower over time. sar showed swap usage climbing over a week. The runner was holding onto build artifacts in /tmp. A cron clean-up brought performance back.

Conclusion

Linux performance diagnosis is a method more than a toolset. Start with the USE method: check utilization, saturation, and errors for each resource. Drill down with the right tool-vmstat and iostat for triage, bpftrace and perf for the deep stuff, sar for history. The recurring lesson: averages lie, distributions tell the truth. Capture broadly, analyze narrowly, and always have a baseline. The first time you find a real bottleneck with a flame graph or a bpftrace one-liner, you'll never go back to guessing from top.


Originally published on Mango Developer.

Top comments (0)