/proc, /sys, sysctl, and limits: the kernel's view of a process and how to tune it

/proc is the kernel telling you the truth about a process: status for state, limits for the contract, fd for the count, smaps_rollup for honest memory, stack for what it is waiting on. Read it before you turn a sysctl.

Read the briefing
About 4 min to read 12 drills

What to remember

  1. /proc//limits is the only authority on a process's limits. Your shell's ulimit means nothing to a systemd service — check the file after a restart.
  2. EMFILE is the process limit; ENFILE is the system limit. One is RLIMIT_NOFILE, the other fs.file-max. Different fixes, and the error name tells you which.
  3. PSI 'full' means everything is stalled. Sustained double-digit memory full is thrashing and an OOM kill is close. 'some' means at least one task waits.
  4. sysctl -w lasts until reboot. Persist in /etc/sysctl.d and reload with sysctl --system, or your tuning quietly disappears.
  5. Network sysctls are per namespace. Setting somaxconn on the host does nothing for pods. Set it in the pod spec.

The big picture

/proc and /sys are the kernel telling you the truth about a process and the host: state, limits, open files, memory maps, kernel stacks, pressure. sysctl is how you change kernel behaviour, and ulimits are how you bound processes. Interviewers use this topic to see whether you can answer "why is this process stuck, out of files, or out of memory" from primary sources instead of from a dashboard's guess.

The mental model

Every process has a directory, /proc/, that is its own dashboard: status is the summary, limits the contract, fd the open files, maps and smaps the memory, stack and wchan what the kernel is doing on its behalf. /proc/pressure is the host's saturation gauge. /proc/sys holds the knobs, persisted through /etc/sysctl.d. Read the dashboard before you turn a knob.

In depth

/proc/<pid>: status, limits, fd

status summarizes a process: State (R running, S sleeping, D uninterruptible, Z zombie, T stopped), VmRSS/VmHWM/VmSwap, Threads, voluntary_ctxt_switches and nonvoluntary_ctxt_switches (a high nonvoluntary count means CPU contention), Cpus_allowed_list. limits shows the soft and hard limits as this process sees them: open files, processes, locked memory, core size. Limits are inherited at exec, so ulimit -n in your shell changes only that shell's children; a systemd service takes LimitNOFILE= from its unit; a running process can be changed with prlimit --pid <pid> --nofile=65536:65536. fd/ lists open descriptors: ls /proc/<pid>/fd | wc -l against "Max open files" tells you how close EMFILE is, ls -l shows sockets, pipes, and files, and fdinfo/<n> shows offsets and flags. Three file ceilings exist: the per-process RLIMIT_NOFILE (soft ≤ hard ≤ fs.nr_open), and the system-wide fs.file-max (fs.file-nr shows allocation). EMFILE means the process limit; ENFILE means the system limit.

maps, smaps, stack, wchan

maps lists every mapping (heap, stacks, libraries, anonymous memory, file-backed pages). smaps_rollup sums them: Rss (resident), Pss (proportional set size: shared pages divided among the processes sharing them), Shared_Clean/Shared_Dirty, Private_Dirty, Swap. Summing RSS across processes overcounts shared libraries and shared memory; summing Pss is honest. stack (root only) shows the kernel stack of a process: for a D-state process it names the wait (nfs_wait_on_request, io_schedule, mutex_lock); wchan gives the single function; task/<tid>/ repeats all of this per thread. exe and maps marked (deleted) mean the process is still running a binary or library that was replaced on disk, the classic "we upgraded but the vulnerability is still live" finding. oom_score_adj shows who the OOM killer prefers.

PSI, sysctl, and ulimits

PSI (/proc/pressure/cpu, memory, io) reports some (at least one task stalled) and full (all non-idle tasks stalled) as 10/60/300-second averages plus a total in microseconds; the same files exist per cgroup under cgroup v2. Memory full above a few percent means the host is thrashing; user-space monitors can register triggers to be woken when pressure crosses a threshold. sysctl: sysctl -a lists, sysctl -w key=value changes at runtime only, persistence goes in /etc/sysctl.d/*.conf loaded by sysctl --system in lexical order (later files win); an unknown key logs an error unless prefixed with -. Keys that matter in interviews: net.core.somaxconn, net.ipv4.ip_local_port_range, net.ipv4.tcp_tw_reuse, vm.swappiness, vm.overcommit_memory, vm.max_map_count (Elasticsearch), fs.inotify.max_user_watches, fs.file-max, kernel.pid_max, net.netfilter.nf_conntrack_max. Network sysctls are per network namespace, so container values are set in the pod (Kubernetes securityContext.sysctls), not on the host. ulimits: pam_limits (/etc/security/limits.conf) applies to login sessions only; systemd services use Limit*= and TasksMax=; Docker uses --ulimit; Kubernetes has no per-pod ulimit field, so the runtime default or the image's entrypoint decides.

Myths and facts

Myth: ulimit -n 65536 as root fixes a service's 'Too many open files'.

Fact: It changes the shell's children only. The service inherits limits from systemd (LimitNOFILE=) or its launcher; verify with /proc//limits.

Myth: Summing RSS across processes gives total memory use.

Fact: Shared pages are counted once per process; sum Pss from smaps_rollup instead.

Myth: sysctl -w is permanent.

Fact: It lasts until reboot; persist in /etc/sysctl.d and reload with sysctl --system.

Myth: kill -9 will terminate a process in D state.

Fact: Signals are delivered when the process returns from the uninterruptible wait; until the I/O completes or the filesystem gives up, it stays. Read /proc//stack to see what it waits for.

Myth: Editing net.core.somaxconn on the host tunes the pods' listen backlogs.

Fact: Network sysctls are namespaced; each pod's network namespace has its own value.

How pros do it

  • Diagnose from /proc first: status, limits, fd count, smaps_rollup, stack; then act.
  • Set service limits in the unit file (LimitNOFILE, LimitMEMLOCK, TasksMax) and verify with /proc//limits after restart.
  • Persist sysctls in /etc/sysctl.d with comments explaining each key and its source; treat them as code.
  • Alert on PSI (cpu/memory/io full and some) at host and cgroup level; it predicts stalls before latency alerts fire.
  • After upgrades, check for (deleted) in /proc/*/maps to find processes still running old libraries.

Questions people ask

Why does my service still hit the old limit after I edited /etc/security/limits.conf?

Because limits.conf is applied by pam_limits to login sessions, and a systemd service never goes through PAM: it inherits its limits from systemd, so set LimitNOFILE= in the unit or a drop-in, daemon-reload and restart. Prove it with cat /proc/<pid>/limits afterwards, the only view that describes the process itself. The caveat: containers are the same story one layer down; Docker's --ulimit or the runtime default decides, and Kubernetes has no pod-level knob.

How do I see how many files a process has open and its limit?

ls /proc/<pid>/fd | wc -l for the count and grep 'open files' /proc/<pid>/limits for the soft and hard limits it actually runs under. Say the errno next: EMFILE (too many open files) is that per-process limit, ENFILE (too many open files in system) is fs.file-max, read against fs.file-nr. The caveat: a count near the limit is usually a leak rather than a limit that is too small, so ls -l the descriptors before raising anything.

How do I find what a D-state process is waiting on?

cat /proc/<pid>/stack (root) for the kernel stack and /proc/<pid>/wchan for the single function; NFS, block I/O and mutex names tell you which dependency is stuck. That also explains why kill -9 did nothing: signals are delivered only when the wait returns. The caveat: when you need every blocked task at once, echo w > /proc/sysrq-trigger dumps them all to dmesg.

What does memory PSI full avg10=30 mean?

In the last 10 seconds, all non-idle tasks were stalled on memory 30% of the time: the host is thrashing (reclaim, swap, refaults) and an OOM kill is close. Name the consumer with smaps_rollup Pss or top RES and shed it before the kernel chooses for you. The caveat: 'some' rising alone is latency, not yet a crisis; alert on some for warning and full for paging.

Where do container sysctls go?

Namespaced ones (most net.) go in the pod via securityContext.sysctls; setting somaxconn on the node changes nothing for pods. Non-namespaced ones (vm., fs.file-max, kernel.pid_max) are host-level and shared by every container. The caveat: the kubelet's safe list is short (net.ipv4.ip_local_port_range, tcp_syncookies, ping_group_range, ip_unprivileged_port_start, kernel.shm_rmid_forced and a few keepalive knobs on newer versions); net.core.somaxconn is not on it, so a pod may only set it when the kubelet runs with --allowed-unsafe-sysctls.

Further reading

Drills · 12

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

A systemd-managed service logs accept: too many open files. You run ulimit -n 65536 as root, restart the service, and it fails again within minutes. Why, and what is the fix?

  1. The service leaks descriptors, so no limit helps. Possibly, but the limit was never applied; verify /proc//limits first.
  2. fs.file-max is too low. That would give ENFILE ('file table overflow'), and it is a system-wide symptom.
  3. You must reboot for ulimit changes to take effect. Limits apply at process start; a correctly configured unit takes effect on restart.
  4. The shell's ulimit only affects that shell's children; the service inherits limits from its unit. Set LimitNOFILE=65536 in the unit (or a drop-in), systemctl daemon-reload, restart, and confirm in /proc//limits. Limits are per process and inherited from the launcher; systemd is the launcher.
In short

The service inherits limits from systemd, not from your shell; set LimitNOFILE= in the unit, daemon-reload, restart and check /proc//limits.

Why

The diagnostic that ends the argument is cat /proc/$(pidof svc)/limits: if it still says 1024, the change did not reach the process. Then check ls /proc/<pid>/fd | wc -l over time to decide whether the new limit is enough or a leak exists.

The common mistake

Running ulimit -n in a root shell and believing the service got it. That shell's children got it; systemd's did not.

Read the docs

2 Scenario: what do you do next?

An indexer process on a bare-metal host stopped making progress twenty minutes ago. kill -9 did nothing; the process is still listed. CPU on the host is idle and nothing was deployed.

Step 1. First look?

  1. kill -9 again, harder. Signals cannot interrupt a D-state wait; the process will die only when the wait ends.
  2. Reboot the host. Possibly the eventual outcome, but you have not identified the cause or the blast radius.
  3. /proc/<pid>/status for State (expect D), /proc/<pid>/wchan and /proc/<pid>/stack for the kernel wait, and /proc/pressure/io to see whether the host as a whole is stalling on I/O. A process that ignores SIGKILL is in uninterruptible sleep; /proc names what it waits on.
  4. Check the indexer's application logs for exceptions. The process is frozen in the kernel; its logs stopped when it did.

Step 2. State: D. wchan: nfs_wait_on_request. stack shows nfs_updatepage / nfs_file_write. PSI io full avg60 is 38%. The host mounts a snapshots directory over NFS from a storage server that has stopped responding to ping. Mitigation?

  1. Increase fs.file-max. Unrelated knob.
  2. Raise the process's I/O priority with ionice. The disk is not the problem; the network filesystem is unreachable.
  3. The NFS server is down and the hard mount makes writes wait forever. Restore or fail over the NFS server (or, if the data can be lost, force-unmount with umount -f -l), then the process completes or dies; move the indexer's writes off that mount for now. Names the mechanism (hard NFS mount, uninterruptible waits), fixes the dependency, and unblocks the process without destroying the host.
  4. Delete the indexer's working directory to free the process. Deleting files does not complete an outstanding RPC to a dead server.

Step 3. Systemic fix?

  1. Switch to kill -9 in a loop via cron. Still cannot interrupt D state.
  2. Replace NFS with a bigger NFS server. The same hang recurs the next time it is unreachable.
  3. Mount NFS with soft,timeo,retrans (or intr semantics) where data loss on failure is acceptable, otherwise remove NFS from the critical path; alert on PSI io and on D-state process counts; document the dependency. Changes the failure mode from 'hang forever' to 'fail fast', adds detection, and records the dependency.
In short

Read /proc//status, wchan and stack: the process is in D state inside an NFS write to a dead server, so restore the NFS server or force-unmount, then use soft mounts and alert on PSI io.

Why

D state plus a kernel stack mentioning NFS is a complete diagnosis: the process is inside a filesystem RPC that will not return. Interviewers listen for the /proc evidence, the hard-vs-soft mount understanding, and the PSI-based detection.

The common mistake

Retrying kill -9 or rebooting before reading the kernel stack. The process is not ignoring you; the kernel has not returned from the I/O.

Read the docs

3 Answer out loud

A process is misbehaving: slow, stuck, or growing. Walk me through what you read under /proc, in what order, and what each file tells you. Four to six sentences.

In short

A strong answer reads status, limits against the fd count, smaps_rollup, stack and wchan in order, and turns each file into a conclusion.

What a strong answer does
  • coverage: status (State, VmRSS/HWM, Threads, nonvoluntary switches), limits vs fd count, smaps_rollup Pss/Private_Dirty, stack/wchan for D state, exe/maps (deleted), plus /proc/pressure for the host.
  • interpretation: Maps observations to causes: EMFILE vs ENFILE, Pss vs Rss, D-state wait names, deleted binaries, PSI thresholds.
  • communication: Ordered by question (alive? bounded? leaking? waiting?) with one sentence per file.
Why

The rubric rewards ordering by question and turning each file into a conclusion; naming /proc paths without interpretation scores low.

The common mistake

Listing /proc files without saying what each one would change about your next move, and forgetting /proc/pressure, which tells you whether the host rather than the process is the one stalling.

4 Pick the strongest answer

You fix a production issue with sysctl -w net.core.somaxconn=4096. What happens to that setting after the host reboots?

  1. It persists until the next kernel upgrade. The value lives in kernel memory and is gone the moment the kernel restarts.
  2. It is lost. -w writes to the running kernel only; to persist it you add the setting to a file under /etc/sysctl.d/ and it is applied at boot. Runtime and persistent configuration are separate on purpose, so an emergency change cannot silently become permanent.
  3. It applies only to processes started after the change. Most sysctls take effect globally and immediately; somaxconn affects subsequent listen() calls, but that is not a reboot question.
  4. It persists automatically; sysctl writes /etc/sysctl.conf for you. Nothing on disk is modified by -w.
In short

sysctl -w changes only the running kernel, so after a reboot the value is gone.

Why

This is a small question that reveals operational habits. Everyone knows the command; the people who have been burned mention the persistence file without being asked.

The common mistake

Fixing an incident with sysctl -w, never writing it to a file, and being surprised months later when a routine reboot brings the problem back.

Read the docs

5 Read the output

The shell reports a limit of 1024 but the service has 65,530 descriptors open. Which limit is the service actually hitting?

$ journalctl -u api --since -5min | tail -2
Sep 02 14:03:11 web-3 api[8123]: accept: too many open files
Sep 02 14:03:11 web-3 api[8123]: accept: too many open files

$ ulimit -n
1024

$ cat /proc/8123/limits | grep 'open files'
Max open files            65536                65536                files

$ ls /proc/8123/fd | wc -l
65530
  1. 1024, the shell's limit, which applies to every process on the host. Limits are per-process and inherited from the parent; systemd is the parent here, not your shell.
  2. There is no limit problem; the log line is spurious. 65,530 of 65,536 used is a descriptor leak about to become an outage.
  3. The system-wide fs.file-max limit. That failure looks different and would affect every process at once, not one service.
  4. Its own, 65,536, set by its systemd unit. ulimit -n reports the limit of your login shell, which has nothing to do with a service started by systemd. /proc//limits is the authoritative per-process view; the shell's ulimit describes a different process tree.
In short

ulimit -n describes only your shell, so read the service's own limit in /proc//limits.

Why

Two lessons in one artifact: which limit governs a systemd service, and the instinct to ask whether a limit is too low or the usage is wrong. Raising LimitNOFILE without looking at the descriptors is the mistake the question is built to catch.

The common mistake

Running ulimit -n in your shell and reporting that number as the service's limit. They are two different processes.

Read the docs

6 Scenario: what do you do next?

An API service starts returning 502s a few hours after every deploy, and recovers on restart. Memory and CPU look normal. The logs show too many open files shortly before each failure.

Step 1. How do you turn this into evidence rather than a guess?

  1. Add a liveness probe that restarts the pod every hour. That is a scheduled restart wearing a costume; the bug ships to production permanently.
  2. Roll back to the previous release and close the ticket. Rolling back is a fine mitigation, but closing without the diagnosis guarantees a repeat.
  3. Track the descriptor count over time — ls /proc/<pid>/fd | wc -l on an interval — and look at what the descriptors point to. A count that climbs monotonically and never falls is a leak; a count that plateaus near the limit is undersizing. The shape of the curve distinguishes the two causes, and the symlink targets name the leaking resource.
  4. Raise LimitNOFILE to 1,048,576 and redeploy. If it is a leak this only moves the outage later, and you will have removed the signal that told you about it.

Step 2. The count climbs steadily, and ls -l /proc/<pid>/fd shows thousands of sockets to the same upstream host, most in CLOSE_WAIT. What does that tell you?

  1. conntrack is full on the node. A full conntrack table drops packets; it does not create local CLOSE_WAIT descriptors.
  2. The host has run out of ephemeral ports. That produces connect failures with a different error, and would not show as descriptors held open.
  3. The application is not closing connections it has finished with: CLOSE_WAIT means the peer closed and the local side never called close(). It is a client-side resource leak, almost always a missing close or an HTTP client created per request instead of reused. CLOSE_WAIT accumulating locally is unambiguous — the kernel is waiting on the application, not on the network.
  4. The upstream host is refusing connections. Refused connections never reach CLOSE_WAIT; they fail immediately.

Step 3. What goes into the fix?

  1. Fix the client to reuse a pooled connection and close responses, add a descriptor-count metric with an alert well below the limit, and keep the limit where it is so the alert stays meaningful. Cause, detection, and a deliberate decision not to hide the signal by raising the ceiling.
  2. Set the limit to unlimited so it can never be reached. It converts a contained service failure into host-wide descriptor exhaustion affecting everything else.
  3. Switch the upstream to UDP to avoid connection state. A protocol change to avoid fixing a resource leak, with an enormous blast radius.
In short

Track the descriptor count over time and read where the descriptors point: sockets piling up in CLOSE_WAIT mean the app never closes its connections, so fix the client and alert below the limit.

Why

The interviewer is looking for the instinct to characterise before acting: is the resource leaking or merely undersized? The two look identical at the moment of failure and have opposite fixes.

Read the docs

7 Pick the strongest answer

You are on a box and cat /proc/pressure/memory shows some avg10=62.10 and full avg10=41.30. What does this mean, and what usually follows?

  1. The kernel is compacting memory and this is normal. Sustained double-digit full pressure is never normal for a latency-sensitive host.
  2. In the last 10 seconds, at least one task was stalled on memory 62% of the time and all non-idle tasks were stalled 41% of the time: the host is thrashing (reclaim, swap, refaults) and an OOM kill or severe latency is imminent. PSI full is the strongest saturation signal for memory.
  3. The numbers are cumulative since boot. avg10/60/300 are windowed averages; 'total' is cumulative microseconds.
  4. 62% of memory is used and 41% is in swap. PSI measures stalled time, not bytes.
In short

In the last 10 seconds at least one task waited on memory 62% of the time and all tasks waited 41% of the time; the host is thrashing and an OOM kill is near.

Why

PSI turns 'memory is tight' into a time fraction you can alert on. some above a few percent for minutes means noticeable latency; full in the tens means the host is mostly waiting for pages. Mitigate by finding the consumer (smaps_rollup Pss, top RES) and shedding it before the OOM killer chooses for you.

Read the docs

8 Read the output

A dashboard sums RSS and reports nginx at ~254 MB. How much memory does nginx really occupy, and why is the dashboard wrong?

$ ps -o pid,rss,comm -C nginx
    PID   RSS COMMAND
   2201  9820 nginx
   2202 61200 nginx
   2203 60940 nginx
   2204 61010 nginx
   2205 60880 nginx
$ grep -E '^(Rss|Pss|Shared_Clean|Shared_Dirty|Private_Dirty)' /proc/2202/smaps_rollup
Rss:               61200 kB
Pss:               18540 kB
Shared_Clean:      52100 kB
Shared_Dirty:       4800 kB
Private_Dirty:      4300 kB
  1. About 17 MB: only Private_Dirty counts. Shared pages still occupy RAM once; ignoring them undercounts.
  2. Roughly the sum of Pss, about 18.5 MB per worker plus the master, on the order of 80 MB: the 52 MB of shared clean pages (libraries, shared memory) exist once but RSS counts them in every worker, so summing RSS overcounts by about three times. Pss divides shared pages among sharers; summing it gives the honest total.
  3. 254 MB; RSS is resident memory, so the sum is correct. Shared pages are resident once, not once per process.
  4. It cannot be determined without VmSwap. Swap is separate from resident accounting; Pss answers the question.
In short

nginx really uses about 80 MB; RSS counts the shared pages in every worker, so summing RSS overcounts by about three times.

Why

Forking servers (nginx, PostgreSQL, gunicorn) are the classic case: workers share the parent's pages, so per-process RSS is misleading in aggregate. Use Pss for capacity questions and Private_Dirty for "what would freeing this process return".

Read the docs

9 Find what's broken

This file is about to be rolled out to every host in the fleet. Three lines are wrong. Which, and why?

# /etc/sysctl.d/90-fleet.conf
net.core.somaxconn = 128
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65535
vm.swappiness = 10
vm.max_map_count = 262144
fs.file-max = 65536
fs.inotify.max_user_watches = 524288
kernel.pid_max = 4194304
In short

Line 2 lowers somaxconn to 128, line 3 sets tcp_tw_recycle which no longer exists, and line 8 lowers fs.file-max to a value one service can exhaust.

What's broken
  • Line 2: somaxconn 128 caps every listen backlog far below the modern default of 4096; bursts overflow the accept queue and clients see SYN retries.
  • Line 3: tcp_tw_recycle was removed in kernel 4.12 (it broke clients behind NAT); the key does not exist, so sysctl --system logs an error on every boot.
  • Line 8: fs.file-max 65536 lowers the system-wide open-file cap from a memory-scaled default in the millions to a value a single busy service can exhaust.
Why

Tuning files accumulate copy-pasted folklore. Two of these lines lower defaults that the kernel had already raised, and one references a knob that no longer exists. tcp_tw_reuse, a low swappiness, and the maximum pid_max are defensible choices.

Read the docs

10 Quick recall

You do not trust the unit file. Which /proc file shows the soft and hard limits a running process actually has?

In short

/proc//limits shows a process's soft and hard limits.

Accepted

/proc/<pid>/limits · /proc/PID/limits · /proc/pid/limits

Why

/proc//limits lists each RLIMIT with soft and hard values as the process sees them.

11 Quick recall

You suspect a descriptor leak. Which directory do you count to get a process's open-file count right now?

In short

/proc//fd lists every open file descriptor of a process.

Accepted

/proc/<pid>/fd · /proc/PID/fd · proc pid fd

Why

ls -l /proc/<pid>/fd shows each descriptor as a symlink to what it points at — a file, a socket, a pipe, or a deleted inode. Counting the entries gives that process's open-file count, and reading the targets usually tells you what it is leaking.

Read the docs

12 Pick the strongest answer

Follow-up: what is the difference between a soft and a hard rlimit, and who can move which?

  1. They are identical; the distinction is historical. The distinction is what lets a service raise its own descriptor limit at startup without root.
  2. The soft limit applies to users and the hard limit to the kernel. Both are per-process rlimits; the system-wide equivalents are separate sysctls.
  3. The soft limit warns and the hard limit blocks. Nothing warns. Exceeding the soft limit fails the syscall outright.
  4. The soft limit is the value actually enforced; the hard limit is the ceiling the soft limit may be raised to. An unprivileged process can raise its soft limit up to the hard limit, and can lower the hard limit, but can never raise it. The hard limit is a one-way ratchet for unprivileged processes, which is what makes it a security boundary.
In short

The soft limit is the one enforced; the hard limit is the ceiling an unprivileged process can raise its soft limit to, and it can only be lowered.

Why

The precise answer names who can move which limit in which direction. Saying "soft warns, hard blocks" is the common wrong answer and it is a quick disqualifier on a Linux-heavy loop.

Read the docs

Next lesson Filesystems and storage: inodes, mounts, durability, the I/O path, and flash wear
Drill · /proc, /sys, sysctl, and limits
0:00

Loading…