StackPilot

Server keeps running out of memory? What to check next

By The StackPilot Team 7 min read

Some links on this page are affiliate links. If you sign up through them we may earn a commission at no extra cost to you. We only link to services we have actually used, and commission never decides what we recommend.

You already ran free -m, saw the number near zero, restarted the service, and it came back a week later. Or the OOM killer took down something you actually needed while the process you suspected is still running fine. The checks below are ordered so that each one eliminates a whole category of cause instead of adding another guess.

Quick verdict

Start with the kernel's own OOM report — dmesg -T or journalctl -k — before you install a single package. It tells you which process the kernel killed, how much memory each candidate held, and whether the box was genuinely out of memory or just out of memory in one cgroup. The tradeoff is that this only works if the event was logged and you can still read it; for a slow leak over days you need something recording continuously, which means a small always-on sampler rather than a dashboard you check when it breaks. If you run containers, go to cgroup v2 accounting second — the host can show plenty of free RAM while a container limit is what's actually killing you.

What you are actually choosing between

ApproachCost shapeOps burden
Kernel logs + /proc inspection by handCheapest tier — no new softwareLow to set up, high per incident; useless if logs rotated away
cgroup v2 memory.stat / memory.eventsCheapest tier, already on the boxLow, but only covers containerised or systemd-scoped workloads
Always-on sampler (node_exporter, a cron script writing to disk)Mid — a few MB of disk and one more thing to keep aliveMedium; you own retention and the sampler itself
Full metrics stack (Prometheus + Grafana + alerting)Premium in time, modest in moneyHigh; worth it only if you have several hosts
Allocation profiler (heaptrack, pprof, tracemalloc, JVM NMT)Free but expensive in engineering hoursHigh; needs a repro and often a restart to attach

Performance ceiling and lock-in barely differ across the first four — they all read the same kernel counters. The profiler row is the only one that touches the running process, and it's the only one that can tell you which function allocated the memory. Reach for it last, not first.

Step by step

  1. Confirm an OOM kill actually happened. "Out of memory" in a ticket usually means "the app got slow". Check the kernel ring buffer:
   dmesg -T | grep -iE 'out of memory|killed process|oom-kill'
   journalctl -k --since '7 days ago' | grep -i 'oom'

If there is no oom-kill line, nothing was OOM-killed and you are debugging a different problem — latency, disk, or a connection pool. Stop here and go look at that instead.

  1. Read the OOM report instead of skimming it. The block lists every process on the box with total_vm, rss, pgtables_bytes, swapents, and oom_score_adj, then ends with a per-node free memory line. Two things matter: the process with the highest oom_score is not necessarily your leak — it is the biggest killable one, and a oom_score_adj of -1000 on a database will push the kill onto something else. If the victim changes between incidents, you have a candidate list, not a culprit.
  1. **Check whether the box was out of memory or out of reclaimable memory.** free -m's free column excludes page cache, which is why it looks alarming. Read /proc/meminfo and look at MemAvailable, not MemFree:
   grep -E 'MemTotal|MemFree|MemAvailable|^Cached|^Slab|SReclaimable|SUnreclaim|AnonHugePages' /proc/meminfo

If MemAvailable was low and SUnreclaim is large, the growth is in the kernel — dentry and inode cache from millions of small files, or a driver — and no application profiler will find it. If AnonHugePages is a large share of total, transparent hugepages plus fragmentation can produce allocation failures while free memory still exists.

  1. Separate anonymous from file-backed per process. RSS double-counts shared pages, so a forking worker pool looks enormous when it isn't. Use PSS or USS:
   sudo smem -tk -P 'python|node|java' | tail -20
   # or, per pid, on kernels 4.14+
   grep -E 'Rss|Pss|Private' /proc/<pid>/smaps_rollup

A process with high Private_Dirty and rising Pss over hours is your leak. High RSS with flat PSS means shared libraries or a shared memory segment, and the fix is elsewhere.

  1. Rule out tmpfs before anything else. tmpfs pages count as memory, not disk, and they are invisible to ps. A /tmp mounted as tmpfs, or a /dev/shm segment held by a database or a browser-testing job, will consume RAM that no process appears to own:
   df -h -t tmpfs
   ls -la /dev/shm

This is the single most common cause of "memory vanished and nothing is using it" on machines that were fine for months.

  1. If anything runs in a container, read the cgroup, not the host. With cgroup v2, the limit that kills you lives in the container's own files:
   cat /sys/fs/cgroup/<unit-or-container>/memory.max
   cat /sys/fs/cgroup/<unit-or-container>/memory.current
   grep -E '^(anon|file|slab|kernel) ' /sys/fs/cgroup/<unit-or-container>/memory.stat
   cat /sys/fs/cgroup/<unit-or-container>/memory.events

memory.events counts oom_kill and high events since boot. A nonzero oom_kill with a host showing 40% used means the container limit is the problem, and adding RAM to the host will change nothing.

  1. Record before you reproduce. Most leaks are slow. A five-line cron job that appends the top ten processes by PSS plus /proc/meminfo every minute gives you the shape of the curve, which is what you actually need:
   */1 * * * * { date -Is; grep -E 'MemAvailable|SUnreclaim' /proc/meminfo; \
     ps -eo pid,rss,comm --sort=-rss | head -11; } >> /var/log/memlog.txt

Rotate it. A linear climb points at a leak; a step function points at a batch job, a cache with no eviction, or a burst of connections.

  1. Only now profile. Once you know which PID grows and roughly when, attach the language-appropriate tool: tracemalloc for Python, --inspect heap snapshots or --heapsnapshot-near-heap-limit for Node, jmap/NMT for the JVM, heaptrack or pprof for native code. If RSS climbs but the heap dump is flat, suspect allocator fragmentation — glibc's per-thread arenas are a classic, and capping them with MALLOC_ARENA_MAX is a mitigation, not a fix.
  1. Make the next incident survivable while you work. earlyoom or systemd-oomd will kill a chosen victim before the kernel picks badly, and oom_score_adj lets you protect the database. This buys time; it does not diagnose anything.

Where this falls short

Everything above assumes the event was logged and the machine is still up. If the box hard-locks or reboots under pressure, you get no OOM report and no sampler output — you need serial console or netconsole capture, or panic_on_oom deliberately left off so the kernel kills instead of panicking. If the leak is in a process that gets restarted by systemd or a supervisor within seconds, the evidence disappears with it; disable the restart temporarily or you will chase a ghost.

The manual approach also breaks down past a handful of hosts. Reading dmesg on twelve machines after the fact is not monitoring, it's archaeology. And no amount of /proc reading will tell you why a JVM's old generation keeps growing — at some point you need the profiler and the repro, and you should budget engineering days for it rather than an afternoon.

If the workload is genuinely sized wrong — a build agent with a fixed heap on a box that also runs a database — stop diagnosing and split the roles onto separate machines. Memory troubleshooting on an overloaded host is a slow way to learn that lesson.

FAQ

Why does the OOM killer kill my database instead of the leaking process?

The kernel picks the highest oom_score, which is roughly proportional to memory used and adjusted by oom_score_adj. Your database is usually the largest resident process, so it wins. Set a negative oom_score_adj on it and a positive one on the suspect, and the next kill lands where you want it.

How do I find which process is leaking memory on Linux?

Compare PSS, not RSS, over time. /proc/<pid>/smaps_rollup gives you Pss and Private_Dirty per process, and a value that climbs steadily across hours with no matching workload is the leak. Record it on a timer — a single snapshot cannot show a trend.

Does high page cache mean the server is out of memory?

No. Page cache is reclaimable and the kernel will drop it under pressure. Look at MemAvailable in /proc/meminfo; if that is healthy while MemFree is near zero, the machine is doing its job. The exception is SUnreclaim in the slab — that memory cannot be given back.

Why does my container get OOM-killed when the host has free RAM?

The container has its own cgroup memory limit, and that limit is what the kernel enforces inside it. Check memory.max and memory.events in the container's cgroup directory; a rising oom_kill counter there confirms it, and host-level RAM is irrelevant to the outcome.

Related reading: Self Hosted Log Aggregation on a Single Server That Fits, How to Monitor a VPS Without Spending Money: 4 Free Paths

Bottom line

Read the kernel's OOM report first, then the cgroup counters if anything is containerised, then rule out tmpfs and slab. Install nothing until those three are exhausted — they cost nothing and they resolve most cases. Only after you know which PID grows, and by how much per hour, does a profiler earn its keep.

Today: run the dmesg and journalctl -k grep from step 1, and if it returns nothing, add the one-line cron sampler from step 7 so the next incident leaves evidence behind.