Systems Performance Analysis & Tuning Questions
Deep, tool-driven diagnosis of a slow host or service once first-pass resource readings point somewhere: sampling with perf and reading flame graphs, continuous low-overhead profiling of production hosts, tracing system calls and library calls with strace and ltrace and their overhead, kernel tracing with ftrace, tracepoints, kprobes and eBPF / bpftrace, and the low-level causes these tools expose: page faults and page-cache behaviour, memory pressure and OOM-killer analysis (system-wide shortage versus a cgroup limit), per-process memory accounting from /proc, NUMA locality, scheduling and CPU-frequency effects, interrupt and softirq load, block-I/O latency, memory growth inside a process, and lock and futex contention. Covers choosing the right tool and its production safety, and isolating the bottleneck before tuning. First-pass resource-saturation readings (load average, utilization and iowait, the USE checklist), profiler theory and application-level instrumentation, kernel internals as concepts, general Linux administration and database tuning are covered elsewhere.
You find OOM killer messages in the kernel log for a long-running service. How do you determine whether it was killed by a system-wide shortage or by a container or cgroup memory limit, and what evidence would you cite?
Sample Answer
The idea in plain words
The OOM killer (out-of-memory killer) is the kernel's last resort: when it cannot find free memory for an allocation after reclaiming what it can, it picks a process and kills it with SIGKILL (the signal that ends a process immediately and cannot be caught). There are two very different situations behind the same message. In a system-wide shortage, the whole machine ran out of memory. In a cgroup (control group, the kernel feature that containers use to limit resources) shortage, one group of processes hit its own memory limit while the host still had plenty free. The one distinction that matters most is CONSTRAINT_NONE (whole host) against CONSTRAINT_MEMCG (a group limit); the other constraint values are rare. The insight: the kernel log says which one happened, in the constraint= field of the oom-kill: line, and the supporting evidence is the memory numbers at that moment: host available memory, the group's usage and limit, and the group's own event counters.
Method
1. Read the kernel log around the kill.
journalctl -k --since "1 hour ago" | grep -iE 'oom|killed process'
dmesg -T | grep -iE 'oom|killed process'
journalctl -kshows kernel messages;dmesg -Tprints them with human-readable timestamps. Both need enough privilege to read the kernel ring buffer.- Find the line beginning
oom-kill:constraint=.CONSTRAINT_NONEmeans no cgroup or policy restriction was involved: a system-wide shortage.CONSTRAINT_MEMCGmeans a memory cgroup limit was hit, and the same line names the cgroup inoom_memcg=andtask_memcg=. (CONSTRAINT_CPUSETandCONSTRAINT_MEMORY_POLICYalso exist: they mean the allocation was limited to certain CPUs' memory nodes by a cpuset, a control group that pins processes to chosen CPUs and memory, or by a NUMA policy, a rule about which memory banks a process may use on multi-socket machines.) - The follow-up line says
Memory cgroup out of memory: Killed process ...for a group limit, andOut of memory: Killed process ...for the whole system. - The kill line lists
total-vm(virtual size),anon-rss(anonymous memory: heap and stack, with no file behind it),file-rss(pages of files the process has mapped in, which can be re-read from disk) andshmem-rss(shared memory), all in kilobytes.
2. Check the numbers on the other side.
-
System-wide:
MemAvailablein/proc/meminfo(an estimate of memory usable without swapping, the figure to trust rather thanfree, because it counts reclaimable page cache, the RAM the kernel uses to keep recently read file contents, as available), swap use (SwapFree; swap is disk space that holds memory pushed out of RAM), and theMem-Infoblock the kernel prints in the log. A system-wide kill shows both nearly exhausted. Monitoring history (sar -r, or your metrics system) should show host available memory falling to near zero before the kill. -
cgroup v2:
cat /sys/fs/cgroup/<group>/memory.max(the limit),memory.current(usage now),memory.peak(highest usage, on kernels that have it) andmemory.events, which has countersmax(times usage reached the limit),oom(times the group hit OOM) andoom_kill(processes killed). Readmemory.eventsfirst: it is the single file that confirms a limit-driven kill. An illustrative excerpt:textlow 0 high 0 max 4812 oom 1 oom_kill 1oom_kill 1is the group's own record of the kill. On cgroup v1 the equivalents arememory.limit_in_bytes,memory.max_usage_in_bytes,memory.failcntandmemory.oom_control. -
Container platforms report it themselves, and the wording depends on the platform and version. On Kubernetes,
kubectl describe podtypically showsReason: OOMKilledandExit Code: 137(137 is 128 + 9, death by SIGKILL), anddocker inspectshows anOOMKilledfield. That tells you a limit-driven kill happened, but the kernel log still tells you which cgroup.
3. Cite the evidence together. One log line is a claim; the log line plus the host's available memory plus the group's limit and usage is the proof.
Worked example
Assumptions (hypothetical): a service named api runs in a container with a 2 GiB memory limit on a 16 GiB host.
Illustrative excerpt of the kernel log, shortened and not a real capture. In the first line, gfp_mask is a set of flags describing the kind of memory allocation that failed, order=0 means it asked for a single page (order is a power of two: 2 to the 0 pages), and oom_score_adj=900 is the per-process kill bias, a number from -1000 to 1000 that makes the process a more likely victim when high (a high value such as 900 is usually set on purpose, for example by a container platform, to make the process an early victim):
api invoked oom-killer: gfp_mask=0xcc0(GFP_KERNEL), order=0, oom_score_adj=900
oom-kill:constraint=CONSTRAINT_MEMCG,oom_memcg=/containers/api,task_memcg=/containers/api,task=api,pid=4127,uid=998
Memory cgroup out of memory: Killed process 4127 (api) total-vm:5242880kB, anon-rss:2015232kB, file-rss:12288kB, shmem-rss:0kB
Reading it:
-
CONSTRAINT_MEMCGwithoom_memcg=/containers/api: a group limit, not the host. -
The limit is 2 GiB = 2 x 1,048,576 kB = 2,097,152 kB. The victim's resident memory is 2,015,232 + 12,288 + 0 = 2,027,520 kB (1.93 GiB). The gap, 2,097,152 - 2,027,520 = 69,632 kB (68 MiB), is other memory charged to the group, such as page cache and kernel structures.
-
Host side:
MemAvailablewas 9.1 GiB at the time, read in this illustrative excerpt ofgrep MemAvailable /proc/meminfo:textMemAvailable: 9542656 kB9,542,656 kB / 1,048,576 kB per GiB = 9.10 GiB. A 16 GiB host with 9.1 GiB available was not short of memory, which confirms the group limit was the cause. Compare the system-wide case, where the line reads
constraint=CONSTRAINT_NONE, the message isOut of memory: Killed process ...,MemAvailableis near zero and swap is full. -
Cgroup counters would add:
memory.eventsshowingmaxandoom_killgreater than zero, as in the excerpt above.
Judgment and next steps
- The fix differs by case. Cgroup kill: the process needed more than its limit, so raise the limit if the working set is legitimate, or fix the leak or a memory spike (a heap that grows, a batch loaded whole); setting the limit equal to the request leaves no burst room (in Kubernetes, a container's request is the memory the scheduler reserves for it when placing it on a node, and its limit is the ceiling the kernel enforces; if they are equal the container can never use more than it asked for, so any spike above its normal use is killed). System-wide kill: find which process grew, check overcommit settings (the kernel's policy on how much memory it promises to processes beyond what physically exists) and swap, and consider limiting the largest consumers with cgroups so one process cannot starve the host.
- A kill inside a container does not mean the host was under pressure, and a healthy host does not clear the container.
- The working set (the memory a program actively uses) is what the limit must cover. Common mistakes: reading the first
oom-killerline and not theconstraint=line, looking atfreeinstead ofMemAvailable, assuming the process with the biggesttotal-vmwas the culprit (the kernel scores resident memory, not virtual size), and forgetting that page cache counts toward a cgroup's usage even though it is reclaimed first.
You are on call and a process is pinned at 100% CPU, but top shows the time is in user space. How would you use strace to see what it is doing, and how do you read what comes back?
Sample Answer
The idea in plain words
A system call (syscall) is a request a program makes to the kernel, such as read, write or openat. Most of them take a file descriptor, a small integer the kernel hands out to stand for an open file, socket or pipe (for example read(5, ...) reads from descriptor 5). strace (system-call tracer) attaches to a process and prints every syscall it makes, with the arguments and the return value. In top, the us figure is time spent running the program's own code (user space) and sy is time the kernel spends working for it, mostly inside syscalls.
The insight: strace only sees the line between the program and the kernel. A process that is 100% busy in user space may make almost no syscalls, so a quiet strace is itself a result: the loop is inside the program's own code and the next tool is a CPU profiler (perf, which samples many times a second which function is executing and reports the hottest ones), not more strace. When strace is not quiet, the pattern of repeated calls shows the shape of the busy loop.
Method, in the order to do it
- Find the hot thread.
top -H -p PID(-Hlists threads,-p PIDlimits to one process) shows which thread ID (TID, the kernel's number for one thread) is at 100%. - Take a short summary first, because strace slows the target (it stops the process at every syscall using the kernel's
ptracefacility, the debugging interface that lets one process pause and inspect another):
timeout -s INT 10 strace -c -f -p PID
timeout -s INT 10sends Ctrl-C after 10 seconds so strace detaches cleanly and prints its table.-ccounts calls, errors and time per syscall instead of printing each call. By default thesecondscolumn is CPU time spent in the kernel, not wall-clock time (-wswitches to wall-clock).-ffollows all threads. Without it,-p PIDtraces only the thread whose ID is PID, usually an idle main thread, which gives a misleading "nothing happening".-p PIDattaches to the running process. This needs the same user or root, and can be blocked by thekernel.yama.ptrace_scopesetting or by a container's security profile.
- If calls exist, look at a few seconds of the real sequence:
timeout -s INT 5 strace -f -tt -T -o /tmp/strace.out -p PID
-ttprefixes each line with a wall-clock time to the microsecond.-Tappends the time spent inside each syscall in angle brackets.-o /tmp/strace.outwrites to a file so the terminal does not become the bottleneck.
Illustrative excerpt of what a busy-poll loop looks like in that file (not a real capture; because of -f, each line starts with the ID of the thread that made the call):
4242 14:02:11.201334 read(5, 0x7f3a1c004000, 4096) = -1 EAGAIN (Resource temporarily unavailable) <0.000001>
4242 14:02:11.201556 read(5, 0x7f3a1c004000, 4096) = -1 EAGAIN (Resource temporarily unavailable) <0.000001>
4242 14:02:11.201778 read(5, 0x7f3a1c004000, 4096) = -1 EAGAIN (Resource temporarily unavailable) <0.000001>
Same call, same descriptor, same error, about 222 microseconds apart (201556 - 201334 = 222), each spending about 1 microsecond inside the call (the summary in the worked example below averages 1 microsecond per read): the thread keeps asking descriptor 5 for data that is not there yet and does its own work in the gaps. EAGAIN ("resource temporarily unavailable") is the kernel's answer for a non-blocking descriptor (one set so that read returns at once instead of sleeping until data arrives) that has nothing to give yet.
4. Read the output with this table.
| What strace shows | What it means | Next step |
|---|---|---|
| Only the attach message, no calls | Pure user-space loop (compute, a spin on memory, a regex or parsing loop) | perf record -F 99 -g -p PID -- sleep 10, then perf report (-F 99 samples 99 times a second, -g keeps the call stack, -p PID picks the process, -- sleep 10 sets the 10-second window) |
read(...) = -1 EAGAIN or poll(..., 0) = 0 (Timeout) repeating | Busy-polling: the code checks a non-blocking descriptor in a loop instead of sleeping | Change the code to block in epoll_wait (a call that sleeps until one of many descriptors is ready) or use a timeout |
The same failing call, such as openat(...) = -1 ENOENT, again and again | A retry loop on an error nobody handles | Fix the cause of the error and add backoff |
Few calls, each with a large <time> | Time is spent waiting in the kernel, not on the CPU | The CPU story is something else, look at I/O or locks |
The first row is the main path for this question: a process burning CPU with a quiet strace goes to perf. The other rows describe what a noisy strace tells you about the loop's shape.
A detail that surprises people: clock_gettime and gettimeofday usually do not appear in strace at all, because Linux answers them in user space through the vDSO (a small kernel-provided code page mapped into every process, so reading the time needs no kernel entry). A loop that reads the clock constantly looks silent.
Worked example: reading a summary
Assumptions: top showed the process at 99% us. A 10-second window of strace -c -f -p PID printed the following.
Illustrative excerpt (hand-built to be internally consistent, not a real capture):
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
60.00 0.045000 1 45000 45000 read
28.00 0.021000 3 7000 write
12.00 0.009000 3 3000 futex
------ ----------- ----------- --------- --------- ----------------
100.00 0.075000 1 55000 45000 total
Reading it line by line:
- Kernel time: 0.045 + 0.021 + 0.009 = 0.075 s. Over a 10 s window that is 0.075 / 10 = 0.75% of one CPU. The kernel is not where a core pinned at 99% goes, so about all of that CPU is user-space work.
- Percent column: read is 0.045 / 0.075 = 60.00%, write 0.021 / 0.075 = 28.00%, futex 0.009 / 0.075 = 12.00%.
- Calls: 45,000 + 7,000 + 3,000 = 55,000, which is 5,500 syscalls per second.
- Errors: all 45,000
readcalls failed. The summary counts failures but does not name the error; the sequence from step 3 does, and in this example it shows theEAGAINlines above ("no data yet, try later"). So the program polls a non-blocking descriptor about 4,500 times per second (45,000 / 10) and finds nothing (one poll every 222 microseconds is about 4,500 per second, which agrees with the excerpt above). futex: 3,000 calls at 3 microseconds is 0.009 s in total. A futex (fast userspace mutex) is the kernel call threads use to sleep and wake around a lock; 300 per second and 0.9 ms of kernel time per second is background noise, so locks are not the story here.- Where the rest of the CPU goes: the thread is 99% busy, so about 0.99 x 10 = 9.9 s of the window is user-space time, against 0.075 s in the kernel. Divided over 55,000 syscalls that is 9.9 / 55,000 = 180 microseconds of user-space work between consecutive syscalls, which is the support for "heavy user-space work between polls". Treat 180 as a rough figure: the 99% comes from
topon the untraced process, the call count comes from the traced window, and strace's own stops take time out of that window, so the true gap without the tracer is somewhat shorter.
Diagnosis: a busy-poll loop plus heavy user-space work between polls (roughly 180 microseconds per syscall, from the line above). The fix is to wait in epoll_wait, and perf tells you which user functions burn the rest. Because strace slows the target, the true unattached call rate is higher than 5,500 per second.
Judgment and trade-offs
- On a latency-sensitive production process, keep the window to seconds, prefer
-cover a full trace, and considerperf trace -p PID(it reads kernel tracepoints and is far lighter than ptrace). If the process is critical and the answer is probably user space, skip strace and go straight toperf. - Quiet strace does not prove the process is healthy. It proves the time is not in syscalls.
- Common mistakes: tracing without
-fon a multithreaded service, treating the syscall with the largest wall time as the CPU hog, and leaving strace attached after the capture.
How does the Linux OOM killer choose a victim, and what settings influence that choice? How would you protect a critical process from being selected, and what are the trade-offs?
Sample Answer
The idea in plain words
When memory runs out, the OOM killer (out-of-memory killer) must choose which process to sacrifice. It computes a badness score for each candidate, roughly "how much memory would we get back" adjusted by an operator-set bias, and kills the highest score. The score is mainly the process's memory footprint: resident pages, swapped-out pages and page-table pages. The bias is oom_score_adj, a per-process setting from -1000 to +1000 that shifts the score by that many thousandths of total memory. The insight: the kernel picks by memory used plus your bias, not by importance, so protecting a critical process means shifting the bias, and every protection moves the kill onto someone else.
How the score is built
For each candidate, the kernel computes in units of pages (4 KiB on x86-64):
points = resident pages (RSS) + swap entries + page-table pages, then points = points + oom_score_adj x (totalpages / 1000), with the division done first in integer arithmetic
Terms: RSS is the pages of the process currently in RAM; swap entries are its pages that were pushed out to swap (disk space that holds evicted memory); page-table pages are the memory the kernel itself spends on the tables that map the process's virtual pages to physical ones; totalpages is the memory available to the allocation (all RAM plus swap for a system-wide OOM; the group's limit for a cgroup OOM). A task with oom_score_adj of -1000 is skipped completely. Kernel threads and PID 1 are not candidates. A task with a very negative bias can end with zero or negative points; it still ranks below every task with a positive score, so it is chosen only if nothing else is left.
The number shown in /proc/PID/oom_score is a rescaling of these points. In current mainline source it is (1000 + points x 1000 / totalpages) x 2 / 3, so a process whose points are zero shows 666, and larger points show larger numbers. Compare the displayed scores for ranking, not for the arithmetic below.
Worked example
Assumptions: a 16 GiB host, 4 KiB pages, page-table pages ignored to keep the arithmetic readable (the kernel adds them, which raises every process's points a little). With no swap, totalpages = 16 GiB / 4 KiB = 16 x 262,144 = 4,194,304 pages, and totalpages / 1000 = 4,194 (integer division). With swap, totalpages includes it, so the bias grows: each 1000 of oom_score_adj is worth a thousandth of RAM plus swap. The program prints both cases:
GIB = 262144 # 4 KiB pages per GiB
def tdiv(a, b):
"""C-style integer division (truncates toward zero)."""
q = abs(a) // abs(b)
return q if (a < 0) == (b < 0) else -q
procs = {"A web app": (6, 0), "B batch job": (4, 500), "C database": (8, -900)}
for swap_gib in (0, 4):
totalpages = (16 + swap_gib) * GIB
print(f"RAM 16 GiB + swap {swap_gib} GiB: totalpages = {totalpages}")
for name, (rss_gib, adj) in procs.items():
bias = adj * (totalpages // 1000) # kernel divides first
points = rss_gib * GIB + bias
shown = (1000 + tdiv(points * 1000, totalpages)) * 2 // 3
print(f" {name:12s} rss={rss_gib * GIB:8d} adj={adj:5d} "
f"bias={bias:9d} points={points:9d} oom_score={shown}")
victim = max(procs, key=lambda n: procs[n][0] * GIB + procs[n][1] * (totalpages // 1000))
print(" victim:", victim)
Output:
RAM 16 GiB + swap 0 GiB: totalpages = 4194304
A web app rss= 1572864 adj= 0 bias= 0 points= 1572864 oom_score=916
B batch job rss= 1048576 adj= 500 bias= 2097000 points= 3145576 oom_score=1166
C database rss= 2097152 adj= -900 bias= -3774600 points= -1677448 oom_score=400
victim: B batch job
RAM 16 GiB + swap 4 GiB: totalpages = 5242880
A web app rss= 1572864 adj= 0 bias= 0 points= 1572864 oom_score=866
B batch job rss= 1048576 adj= 500 bias= 2621000 points= 3669576 oom_score=1132
C database rss= 2097152 adj= -900 bias= -4717800 points= -2620648 oom_score=334
victim: B batch job
Reading the no-swap case by hand:
- Process A, a web app: RSS 6 GiB = 1,572,864 pages,
oom_score_adj0, so points = 1,572,864. - Process B, a batch job: RSS 4 GiB = 1,048,576 pages,
oom_score_adj+500. Bias = 500 x 4,194 = 2,097,000 pages. Points = 1,048,576 + 2,097,000 = 3,145,576. - Process C, a database: RSS 8 GiB = 2,097,152 pages,
oom_score_adj-900. Bias = -900 x 4,194 = -3,774,600 pages. Points = 2,097,152 - 3,774,600 = -1,677,448, which is below zero, so C ranks last.
The victim is B, even though A uses more memory (6 GiB against 4 GiB), because B's +500 bias is worth about 8 GiB of score: +500/1000 of the 16 GiB. The database, the biggest process, is last in line. With 4 GiB of swap added, totalpages grows to 5,242,880 and every bias grows by about a quarter, but the order is unchanged here.
The settings that influence the choice
oom_score_adjper process (/proc/PID/oom_score_adj; the oldoom_adjis the legacy interface). Lowering it below its current value needs theCAP_SYS_RESOURCEcapability (a Linux privilege that ordinary users lack, held by root).- The unit-file setting
OOMScoreAdjust=in systemd, which sets it at service start. - Container platforms set it for you. Kubernetes's kubelet documents
oom_score_adj-997 for Guaranteed pods (every container has memory and CPU requests equal to its limits) and 1000 for BestEffort pods (no requests or limits set), with Burstable pods (everything in between) getting min(max(2, 1000 - 1000 x memory request / node memory), 999). Low-priority pods die first. These are the documented values at the time of writing, so check your Kubernetes version. vm.oom_kill_allocating_task: when 1, the kernel kills the task that triggered the failed allocation instead of scanning for the highest score (cheaper, less accurate).vm.panic_on_oom: 0 (default) kills a process; non-zero panics the machine, useful in clusters that prefer a clean node restart.- cgroup limits (
memory.max, andmemory.oom.groupin cgroup v2 to kill the whole group together): these decide which pool is scored, since a cgroup OOM only considers processes inside that group. vm.overcommit_memoryandvm.overcommit_ratio, which decide how much memory the kernel promises to processes (overcommit means promising more memory than physically exists, on the bet that not everyone uses it at once) and so how often it gets to the point of killing.
Protecting a critical process, and the trade-offs
In practice the two levers that matter are oom_score_adj and a cgroup memory.max; the other settings in the list above (oom_kill_allocating_task, panic_on_oom, the overcommit settings) are rarely touched. Options, strongest first: echo -1000 > /proc/PID/oom_score_adj (or OOMScoreAdjust=-1000) makes it unkillable by the OOM killer; a value like -900 makes it the last choice but not exempt; a memory cgroup limit on the neighbours keeps the problem local so the critical process is never scored at all.
Trade-offs:
- The kill moves to another process. If that process is also important (a sidecar, meaning a helper process or container that runs next to the main one,
sshd, a monitoring agent), you traded one outage for another. Givesshdor an agent a strong negative bias too, so you can still log in. - At -1000, if the protected process is the one leaking, the kernel keeps killing everything else and may end with no killable process and a panic or a machine that thrashes (spends its time moving pages between RAM and swap and makes almost no progress). A bounded value such as -900 plus a cgroup
memory.maxon that process keeps a leak contained. - A protected process that must be restarted after a failure needs a supervisor, because protection does not fix the shortage. The better long-term protection is capacity: right-sized memory, limits on the neighbours, and an early user-space killer (a daemon such as
systemd-oomdorearlyoomthat watches memory pressure and kills a chosen process before the kernel is stuck).
Common mistakes: believing the largest process is always chosen, setting -1000 on many services so nothing is killable, and changing oom_score_adj in a shell without making it persistent (it resets when the process restarts).
You need to diagnose memory use, open files, CPU affinity and namespaces for one process. Which parts of /proc would you read, and what does each tell you?
Sample Answer
The idea in plain words
/proc is a pseudo-filesystem: nothing in it is stored on disk, the kernel generates the text when you read it. Every running process has a directory /proc/<pid>/ (<pid> is its process ID) that exposes what the kernel knows about it, so a handful of cat, ls and readlink (print where a symbolic link points) commands answer most "what is this process doing" questions without installing anything and with almost no overhead. The four asked-for areas map to four places: memory to status and smaps_rollup, open files to fd and limits, CPU affinity to status (and stat), namespaces to ns/.
Memory: status, smaps_rollup, maps
grep -E '^(VmSize|VmRSS|VmHWM|RssAnon|RssFile|RssShmem|VmSwap|Threads):' /proc/<pid>/status
cat /proc/<pid>/smaps_rollup
| Field | Meaning |
|---|---|
VmSize | Virtual address space reserved. Large and often meaningless on its own (thread stacks, mapped files and allocator reservations all count) |
VmRSS | Resident set size: pages of this process currently in RAM |
VmHWM | Peak RSS since the process started |
RssAnon, RssFile, RssShmem | RSS split into heap/stack memory, mapped file pages and shared memory; they add up to VmRSS |
VmSwap | Part of the process currently swapped out |
Threads | Thread count (a steady rise explains growing stack memory) |
Illustrative excerpt of the status read for a process (values in kilobytes except Threads):
VmSize: 4812340 kB
VmHWM: 540672 kB
VmRSS: 524288 kB
RssAnon: 480000 kB
RssFile: 40000 kB
RssShmem: 4288 kB
VmSwap: 0 kB
Threads: 38
Reading it: 480,000 + 40,000 + 4,288 = 524,288, so the three parts add up to VmRSS; the process has used at most 540,672 kB (VmHWM) so far and 524,288 kB now; VmSize is about 9 times the resident figure, which is why it says little by itself; nothing is swapped out. Most of the resident memory is anonymous (heap and stack), so a leak would show up in RssAnon.
smaps_rollup sums the per-mapping file smaps and adds Pss (proportional set size: shared pages divided fairly among the processes sharing them, so totals across processes do not double count). Illustrative excerpt of smaps_rollup (abridged to the lines that matter, in kilobytes):
Rss: 524288 kB
Pss: 498176 kB
Pss_Anon: 480000 kB
Pss_File: 17000 kB
Pss_Shmem: 1176 kB
Pss (498,176) is lower than Rss (524,288) because pages shared with other processes, mostly library code, are split among their users; 480,000 + 17,000 + 1,176 = 498,176. When you add up memory across many processes, add Pss, not Rss. maps lists each address range with its permissions and backing file; [heap] and [stack] are labelled, anonymous regions have no name. A growing count of lines in maps points at an mmap or thread leak rather than heap growth.
Open files: fd, fdinfo, limits
ls -l /proc/<pid>/fd
ls /proc/<pid>/fd | wc -l
grep 'open files' /proc/<pid>/limits
cat /proc/<pid>/fdinfo/<n>
A file descriptor is the small integer a process uses to refer to something it has open (a file, a socket, a pipe), so "open files" really means "open descriptors". Each entry in fd is a symbolic link (a file that just names another path) named after the descriptor number and pointing at the target: a path, socket:[inode], pipe:[inode] or anon_inode:[eventpoll]. An inode is the kernel's identity number for the underlying object, so socket:[48213] is "the socket with identity 48213"; anon_inode:[eventpoll] is an epoll instance (the object a program uses to wait on many descriptors at once). ls -l therefore shows what kind of thing is open:
lrwx------ 1 app app 64 Jan 10 09:14 3 -> /var/log/app.log
lrwx------ 1 app app 64 Jan 10 09:14 4 -> 'socket:[48213]'
lrwx------ 1 app app 64 Jan 10 09:14 5 -> 'anon_inode:[eventpoll]'
(Illustrative excerpt.) wc -l counts them and limits shows the cap (Max open files, soft and hard). fdinfo/<n> gives the file offset (pos) and open flags. Files deleted but still open show (deleted) after the path: this is the classic reason a disk is full while du finds nothing. Reading another user's fd needs the same user or root.
Illustrative excerpt for a service failing with "Too many open files":
ls /proc/4242/fd | wc -l
1020
grep 'open files' /proc/4242/limits
Max open files 1024 1024 files
1,020 of 1,024 descriptors are used (99.6%), so the next burst of connections fails. Counting by type (ls -l /proc/4242/fd | grep -c socket) says whether sockets or files are leaking.
CPU affinity: status, stat, task/
grep -E '^(Cpus_allowed|Cpus_allowed_list|Mems_allowed_list|voluntary_ctxt_switches|nonvoluntary_ctxt_switches):' /proc/<pid>/status
Cpus_allowed is a bitmask (one bit per CPU, 1 meaning allowed) written in hexadecimal (each hex digit stands for 4 CPUs: f is binary 1111, c is 1100), and Cpus_allowed_list is the same in readable form. Illustrative excerpt: Cpus_allowed: f and Cpus_allowed_list: 0-3 agree, because f is binary 1111 (four CPUs); Cpus_allowed: c would be binary 1100, which is CPUs 2 and 3. The mask reflects limits set with taskset (a command that starts or re-pins a process to chosen CPUs; sched_setaffinity is the system call behind it) and also a cpuset cgroup. A cgroup (control group) is a kernel mechanism that groups processes and caps their resources, and its cpuset controller restricts which CPUs and memory nodes the group may use, so a container limited to some CPUs shows it here; /proc/<pid>/cgroup says which group applies. Mems_allowed_list is the same idea for NUMA memory nodes (NUMA: a multi-socket server where each CPU socket has memory attached close to it, called a node, and memory on another socket is slower to reach); a single-socket host shows 0. The two context-switch counters tell you whether the process gives up the CPU by itself (voluntary, it blocked waiting for something) or is forced off (nonvoluntary, it was preempted: the scheduler took the CPU away to run something else), which hints at CPU starvation when the second is large. Per-thread data lives in /proc/<pid>/task/<tid>/, and the 39th field of a thread's stat is the CPU it last ran on.
Namespaces: ns/
A namespace gives a group of processes their own private view of a resource (process IDs, network interfaces, mounts, hostname, users). Containers are built from them.
ls -l /proc/<pid>/ns
readlink /proc/<pid>/ns/net /proc/1/ns/net
Each link looks like net:[4026532198]; the number identifies the namespace. Two processes with the same number share it. A container is simply ordinary processes started inside their own namespaces (plus cgroup limits), which is why two processes on one machine can have different network interfaces. Illustrative excerpt: the service shows net:[4026532198] while PID 1 shows net:[4026531840], so they have different network stacks, and an ss run on the host (ss lists sockets; -t TCP, -a all states, -n numeric addresses, -p owning process) will not show the service's sockets. lsns lists namespaces, and nsenter -t <pid> -n ss -tanp (-t target PID, -n enter its network namespace) runs a command inside. From inside a container the PID namespace hides host PIDs, so use the host's PID when reading /proc from outside.
Worked reading order
For a process 4242 that is slow and large: read status (is RSS mostly RssAnon, is nonvoluntary_ctxt_switches high, is Cpus_allowed_list narrower than expected), then limits against the fd count, then ns/net before using host-side network tools. Four reads, no tracing.
Common mistakes
- Trusting
VmSizeas memory use. - Reading
/procfrom the host with a container's PID. - Forgetting that
/procis a snapshot: sample twice to see a trend. - Missing per-thread differences: the process-level mask can look fine while one thread is pinned.
What is the difference between page cache and anonymous memory? How would you see the split for a process, and why do fsync and dropping caches change what you observe?
Sample Answer
The idea in plain words
Linux uses RAM that applications are not using to keep copies of file contents, so the next read does not have to go to the disk. Those copies live in the page cache: pages of RAM (usually 4 KiB each) that hold the contents of files, owned by the kernel and shared by every process. Anonymous memory is every page with no file behind it: the heap (malloc), thread stacks and memory mapped with MAP_ANONYMOUS (a flag to mmap, the call that adds a region to a process's address space, that asks for fresh memory with no file behind it). A page is mapped into a process when that process's address space includes it, so the process can read it directly as memory; mapping a file means its pages appear in the address space and are read in on first use.
The one test that separates them is: if the kernel needs the page back, is there a file it can re-read the data from? A clean cache page (identical to what is on disk) can simply be dropped. A dirty cache page (changed in RAM, not yet written) must be written out first. An anonymous page has nowhere to go except swap space (disk space set aside to hold memory pages pushed out of RAM), and with no swap it cannot be reclaimed at all, so running short ends in the OOM killer (the kernel killing a process to free memory).
The split side by side
| Page cache | Anonymous memory | |
|---|---|---|
| Backing | A file on disk (tmpfs and shared memory are RAM-only files, see below) | None |
| Typical sources | read() and write() data, mapped executables and libraries | malloc, stacks, a managed-language heap |
| Reclaim when RAM is short | Clean: dropped instantly. Dirty: written back first | Swapped out, or not reclaimable |
System counter in /proc/meminfo | Cached, Buffers (block-device metadata), Dirty, Writeback | AnonPages |
| Counted in a process's RSS (resident set size, the pages of that process currently in RAM)? | Only the part it has mapped (RssFile) | Yes (RssAnon) |
Two exceptions to keep in mind. First, tmpfs and shared memory (tmpfs is a filesystem that lives entirely in RAM, /dev/shm is one, and memfd is an anonymous in-memory file a program creates with a system call) show up inside Cached (their own line is Shmem) but behave like anonymous memory: there is no disk copy, so only swap can reclaim them. Second, a private file mapping that a process writes to becomes an anonymous copy of that page (copy-on-write: the process first shares the cached page, and the kernel makes the process's own copy only when it writes), so a file-backed region can slowly turn anonymous.
Seeing the split
System wide:
grep -E '^(MemTotal|MemFree|MemAvailable|Buffers|Cached|AnonPages|Shmem|Dirty|Writeback):' /proc/meminfo
free -m
-E enables extended regular expressions so the | means "or"; free -m prints megabytes. Illustrative excerpts for the host in the worked example below, before the test (values in kB for /proc/meminfo, MiB for free):
MemTotal: 8388608 kB
MemFree: 3072000 kB
MemAvailable: 5529600 kB
Buffers: 65536 kB
Cached: 3072000 kB
AnonPages: 2048000 kB
Shmem: 102400 kB
Dirty: 0 kB
Writeback: 0 kB
total used free shared buff/cache available
Mem: 8192 2128 3000 100 3064 5400
Note Cached (3,000 MiB) is large while MemFree is also 3,000 MiB, and available (5,400 MiB) is the figure that adds droppable cache to free memory. In free, the buff/cache column is page cache plus buffers, and available is the honest "how much could a new program get" estimate. A low free column on a busy file-serving host is normal, because the cache is meant to fill spare RAM.
For one process:
grep -E '^(VmRSS|RssAnon|RssFile|RssShmem|VmSwap):' /proc/<pid>/status
Illustrative excerpt (values in kB, as the kernel prints them):
VmRSS: 1310720 kB
RssAnon: 1048576 kB
RssFile: 262144 kB
RssShmem: 0 kB
VmSwap: 0 kB
Check: 1,048,576 + 262,144 + 0 = 1,310,720, so the three parts add up to VmRSS. This process holds 1 GiB of anonymous memory (1,048,576 kB) and has 256 MiB of file pages mapped. /proc/<pid>/smaps_rollup adds proportional totals (Pss, which splits shared pages fairly between sharers) and /proc/<pid>/smaps breaks the same numbers down per mapping.
Important limit: a process that read()s a 2 GiB file does not get 2 GiB added to its RSS. The cached pages belong to the system, not the process. To ask "how much of this file is cached?" use fincore <file> (from util-linux), which prints the resident pages of each file given. Inside a container, the control-group (cgroup, the kernel's per-group resource accounting) version 2 file memory.stat splits the group's memory into anon, file, file_dirty, file_writeback and shmem.
Why fsync changes what you observe
write() normally copies the data into the page cache, marks those pages dirty and returns. The disk is written later by the kernel's writeback threads (background kernel threads that write dirty pages to storage), once the data has aged (vm.dirty_expire_centisecs, commonly 3000 meaning 30 seconds) or the dirty total passes vm.dirty_background_ratio (the percentage of memory that may be dirty before background writing starts). fsync(fd) blocks until that file's dirty data (and the metadata needed to find it) is on the storage device.
What moves: Dirty and Writeback fall toward zero. What does not move: Cached, because the pages stay in memory as clean copies. Two practical consequences: a benchmark that never calls fsync measures RAM speed, not disk speed, and data that was only written to the cache is lost on power failure even though write() succeeded.
Why dropping caches changes what you observe
sync; echo 1 > /proc/sys/vm/drop_caches
sync writes all dirty data out first. Writing 1 frees clean page cache, 2 frees reclaimable kernel objects (dentries and inodes: a dentry caches one directory-entry lookup, a name inside a directory, and an inode caches a file's metadata such as size and permissions; both live in the kernel's slab allocator, its pool for small fixed-size objects), 3 frees both. Only clean, unused pages are dropped: dirty pages survive (which is why sync comes first), pages a process currently has mapped stay, and anonymous memory is untouched. The effect is that Cached and MemFree change a lot, MemAvailable barely changes (it already counted that cache as reclaimable), and the next reads are real disk reads, so latency rises and iostat shows read traffic until the cache refills. That makes it a tool for cold-cache benchmarks. As a production "fix" it is harmful: hit ratios collapse (a cache hit ratio is the share of reads served from the cache instead of the disk), and it cannot cure a leak because leaked memory is anonymous.
Worked example
Assumptions (a hypothetical 8192 MiB host, all values in MiB): AnonPages 2000, Cached 3000 of which 100 is Shmem and 500 is mapped by processes, Buffers, slab and other kernel memory 192, Dirty 0. Then MemFree = 8192 - 2000 - 3000 - 192 = 3000.
A process runs dd if=/dev/zero of=testfile bs=1M count=256 (if is the input, of the output, bs=1M the block size, count=256 the number of blocks, so 256 MiB). Adding conv=fsync makes dd wait until the data is flushed before it exits. The write is kept small on purpose: with the common default vm.dirty_background_ratio of 10, background writing starts when dirty data reaches about 10% of the free and reclaimable memory (roughly 540 MiB on this host), so 256 MiB stays dirty until fsync or the 30-second timer, whereas a 1 GiB write would already be flushing while dd is still running and Dirty would never reach 1024. The table follows the counters as the writes return, after the flush, and after caches are dropped.
| Step | AnonPages | Cached | Dirty | MemFree |
|---|---|---|---|---|
| Start | 2000 | 3000 | 0 | 3000 |
| After the writes return (no fsync yet) | 2000 | 3256 | 256 | 2744 |
| After fsync completes | 2000 | 3256 | 0 | 2744 |
After sync; echo 1 > .../drop_caches | 2000 | 600 | 0 | 5400 |
Arithmetic: Cached 3000 + 256 = 3256; MemFree 3000 - 256 = 2744. Droppable pages = 3256 - 100 (Shmem) - 500 (mapped) = 2656; Cached becomes 3256 - 2656 = 600; MemFree becomes 2744 + 2656 = 5400. Cross-check: 5400 + 2000 + 600 + 192 = 8192. MemAvailable is roughly MemFree plus reclaimable cache, so about 2744 + 2656 = 5400 before the drop and 5400 after: the host did not gain usable memory, it only lost its cache.
Common mistakes
- Reading low
MemFreeas a problem and checkingavailabletoo late. - Adding
RssFileto "memory used" and calling it a leak: it is cache the process is touching. - Treating
Cachedas always reclaimable:Shmemand dirty pages are not. - Dropping caches on a live host to "free memory".
That is every published Systems Performance Analysis & Tuning question for Systems Administrator so far. Browse the other topics in this category, or practice this one interactively.