The service is down again, the process list no longer shows the Java worker, and there is no stack trace anywhere in the application log. The last line it wrote was an ordinary request log entry at 03:12:47. Then nothing. You run journalctl -k --since "03:00" and there it is, one line in the middle of the kernel buffer: Out of memory: Killed process 4121 (java) total-vm:9412316kB, anon-rss:6801220kB. The kernel shot your process, and it did not ask the application for permission.
This memo is for the moment after that discovery, when someone asks "so what do we do?" It covers how to confirm what happened, why Linux chose that process, and three ways to stop it recurring, with their costs. It is also, incidentally, one of the most common practical questions in SRE and platform engineering interviews, including for the infrastructure roles that Portuguese tech employers in Lisbon and Porto hire for, because the answer shows whether a candidate understands memory beyond the free command.
Confirm which killer fired, because there are at least four
"The OOM killer" is shorthand for several different mechanisms, and the fix depends on which one it was. Before changing anything, find the exact log line.
The classic kernel OOM killer runs when the whole machine cannot satisfy a memory allocation. Its message starts with Out of memory: Killed process, followed by the PID, the process name and memory figures. Find it with journalctl -k | grep -i "killed process" or dmesg -T | grep -i oom. Just above that line, the kernel prints a table of every candidate process with its memory use, which is often more useful than the final verdict.
The cgroup OOM killer fires when a process exceeds the memory limit of its control group, even if the machine has plenty of free memory. The message reads Memory cgroup out of memory: Killed process, and the log usually includes oom-kill:constraint=CONSTRAINT_MEMCG. This is what happens to containers with a memory limit, and to systemd services with MemoryMax= set.
The third mechanism is userspace. systemd-oomd, enabled by default on Fedora since version 34 and on Ubuntu since 22.04, watches memory pressure and kills whole cgroups before the kernel runs out. Its messages appear in journalctl -u systemd-oomd, not in the kernel log. earlyoom is a similar tool on some other distributions.
The fourth, in Kubernetes, is the kubelet evicting pods under node memory pressure. An evicted pod shows status Evicted, while a container killed by the kernel for exceeding its own limit shows OOMKilled with exit code 137. That number is 128 plus 9, the signal number of SIGKILL, which is why any process killed with kill -9 also exits with 137.
If none of these log entries exist, the process probably was not OOM killed at all. A crash, a supervisor restart or a deployment can look similar from the outside.
How Linux chooses the process it kills
The kernel's choice often looks unfair. The process that leaked memory may survive while a well behaved database dies. The reason is that the kernel does not know who leaked; it only knows who holds the most memory right now.
For each candidate, the kernel computes a "badness" score, mainly from the process's resident memory, its swap usage and its page tables, expressed as a share of the memory available to it. It then adds oom_score_adj, a per-process value from minus 1000 to plus 1000. A value of minus 1000 makes a process immune; plus 1000 makes it the first victim. The process with the highest final score is killed. You can see the current score of any process in /proc/<pid>/oom_score and its adjustment in /proc/<pid>/oom_score_adj.
A worked illustration with round numbers: a VM with 8 GiB of RAM and no swap runs PostgreSQL using about 2.5 GiB, a Java service using about 4 GiB of resident memory, and a Python batch job that grows from 300 MiB to 2 GiB over an hour because of an unbounded cache.
When the Python job pushes total usage past 8 GiB, the kernel looks for the largest consumer. That is the Java service at 4 GiB, not the 2 GiB Python job that caused the problem. Java dies, the Python job keeps running, and next week it happens again.
This is why the first diagnostic question is never "why was Java killed?" but rather "what was memory doing in the 30 minutes before?" Monitoring with per-process or per-cgroup memory, from node_exporter, cAdvisor or a similar collector, answers it. The candidate table in the kernel log gives a snapshot of the moment itself.
Why overcommit lets the kernel get here at all
A common reaction is: why did the allocation succeed in the first place? If there was not enough memory, malloc should have failed and the application could have handled it.
Linux overcommits memory by default. When a program asks for memory, the kernel usually grants address space without reserving physical pages. Pages are only allocated when the program first writes to them. This is efficient, because most programs reserve far more than they use; a JVM may reserve a large heap and touch only part of it. The cost is that the kernel can promise more memory than exists, and when the promises come due, it must break one.
The behaviour is controlled by vm.overcommit_memory. The default, 0, uses a heuristic that refuses only obviously impossible allocations. A value of 1 always grants. A value of 2 enforces strict accounting: total committed memory may not exceed swap plus a share of RAM set by vm.overcommit_ratio, which defaults to 50 percent. You can compare CommitLimit and Committed_AS in /proc/meminfo to see how far the system is overcommitted.
Strict mode sounds like the responsible choice, and for a few workloads it is. In practice, it makes many ordinary programs fail allocations they would never have used, and some software, such as Redis, explicitly recommends overcommit mode 1 because of how it forks for background saves. Changing overcommit is rarely the first fix. It is useful mainly to understand why the kill happened late, at page touch time, instead of early at allocation.
Option one: give the workload memory it actually needs
The most direct fix is also the least glamorous: make sure memory demand fits memory supply. That means either adding memory or reducing what the processes use, and it starts with measuring the real peak.
Look at the peak resident memory of each service over a representative week, not the average. Then compare the sum of peaks with what the machine or container actually has. In the illustration above, the three processes peak at about 8.5 GiB on an 8 GiB machine with no headroom for the page cache or the kernel itself. Either the machine needs 12 GiB, or one of the processes needs a cap.
Caps should be set inside the application where possible. For the JVM, modern versions read the container memory limit automatically, a behaviour available since JDK 10 and backported to 8u191. By default, the maximum heap is 25 percent of available memory, controlled by -XX:MaxRAMPercentage.
Setting it to 75 percent in a container with a 4 GiB limit gives a 3 GiB heap and leaves about 1 GiB for metaspace, thread stacks, direct buffers and native libraries. Teams often set the heap to 100 percent of the limit and are surprised when the kernel kills the container, because the heap is only one part of a JVM's memory.
For PostgreSQL, shared_buffers plus work_mem multiplied by concurrent sorts can add up quickly. For Python and Node.js services, the usual culprits are unbounded in-memory caches, large DataFrames and batch sizes that grow with input. A leak needs a fix in code; no kernel setting will make it go away.
This option has the clearest trade-off: it costs money or engineering time, and it removes the cause rather than the symptom.
Option two: protect the process that must not die
Sometimes the machine is right sized, and the problem is which process gets killed when something else misbehaves. Then you can steer the kernel's choice with oom_score_adj.
For a systemd service, set OOMScoreAdjust= in the unit file. A value such as minus 500 makes the service much less likely to be chosen; a positive value marks a process as expendable. A batch job or a cache that can be rebuilt is a good candidate for plus 500 or more, so that it dies first and protects the main service. In the earlier illustration, marking the Python batch job as expendable would have saved the Java service and killed the actual source of growth.
Kubernetes does this automatically by quality of service class. Pods in the Guaranteed class, where requests equal limits, get an oom_score_adj of minus 997. BestEffort pods with no requests at all get plus 1000. Burstable pods fall in between, based on their memory request relative to the node's capacity. Setting requests and limits deliberately is therefore also a way of choosing who dies first under node pressure.
The dangerous version of this option is setting minus 1000, total immunity, on a large process. If that process is the one growing, the kernel will kill everything else first: your monitoring agent, the SSH daemon, the log shipper. You end up with a machine that is technically up but impossible to reach. Use minus 1000 only for tiny, critical system processes, and never as a fix for a memory problem in the protected process itself.
Option three: kill earlier, or slow down instead of dying
The kernel OOM killer acts at the last possible moment, when the system has often been thrashing for minutes. Desktop users know this as a frozen machine; on servers, it shows up as request latency climbing to seconds before the kill. A third option is to act earlier.
systemd-oomd uses pressure stall information, a kernel feature since Linux 4.20 that reports how much time tasks spend waiting for memory. When a cgroup stays above a configured pressure threshold, typically for 20 to 30 seconds, systemd-oomd kills it. It is configured with ManagedOOMMemoryPressure=kill on a slice or service and a limit such as ManagedOOMMemoryPressureLimit=50%. earlyoom does something simpler, acting when available memory and swap fall below a percentage.
Cgroup v2 also offers a softer control. memory.high throttles a cgroup and forces reclaim when it goes over the threshold, slowing the process instead of killing it, while memory.max remains the hard limit. Setting memory.high somewhat below memory.max gives you a warning zone where latency rises but nothing dies, and your monitoring can catch it. The memory.events file for each cgroup counts how often it hit high, max and oom_kill, which is a good metric to alert on.
Swap belongs in this option too. A small swap file or zram device does not make memory infinite, but it gives the kernel somewhere to put cold pages, turning a sudden kill into a gradual slowdown. Whether that is better depends on the workload: for a batch job, slower is fine; for a latency sensitive API, a fast restart may be preferable to minutes of degraded responses.
The three options side by side
The table compares the options on the dimensions that usually decide the conversation.
| Option one: right size memory | Option two: steer the victim | Option three: earlier or softer action | |
|---|---|---|---|
| What it changes | Demand fits supply | Which process dies | When and how processes die |
| Main tools | Bigger instance, heap and cache limits, leak fixes | oom_score_adj, OOMScoreAdjust=, Kubernetes QoS |
systemd-oomd, earlyoom, memory.high, swap or zram |
| Fixes the root cause | Yes | No | No |
| Typical cost | Money or engineering days | Minutes of configuration | Hours of tuning and testing |
| Main risk | Overprovisioning if peaks are misread | Protected process starves others | Kills during legitimate bursts, or slow degradation |
| Best for | Leaks, undersized hosts, misconfigured JVMs | Mixed hosts with clear priorities | Shared hosts, desktops, latency tolerant jobs |
Most production fixes combine options. A typical sequence is to protect the critical service in the first hour, find the real memory driver in the first week, and add early pressure handling where many workloads share a host.
The choice also depends on who owns the host. On a dedicated VM running one service, option one is usually cheap: moving from 8 GiB to 16 GiB on most cloud providers roughly doubles the instance price, which may be less than a day of an engineer's time spent chasing native memory in a JVM.
On a shared Kubernetes node with 30 or 40 pods from different teams, nobody can simply buy a bigger box for one service, and options two and three become the main levers, enforced through requests, limits and quality of service classes. On a developer laptop or a CI runner, option three with systemd-oomd or earlyoom is often the whole answer, because the goal there is a responsive machine, not a protected process.
Mistakes that turn one OOM kill into a recurring incident
These come up again and again in incident reviews and in interview answers:
- Restarting the service and closing the ticket without reading the candidate table in the kernel log.
- Blaming the killed process when another process caused the growth.
- Setting the JVM heap equal to the container limit, leaving no room for native memory.
- Applying
oom_score_adjof minus 1000 to a large, growing process. - Disabling the OOM killer through
vm.panic_on_oomwithout understanding that it reboots the machine instead. - Raising the container limit repeatedly instead of looking for the leak.
- Confusing Kubernetes eviction with a container OOMKill, and tuning the wrong setting.
- Alerting on free memory, which is low on any healthy Linux system because of the page cache, instead of on available memory and
oom_killevents. - Testing a fix on a quiet staging host where peak memory never gets within 20 percent of the production peak, then declaring the problem solved.
The verdict on trade-offs is fairly clear. Option two is the fastest way to stop the bleeding, and it is safe as long as you avoid total immunity. Option three makes failures gentler and more visible, at the cost of tuning time and occasional false kills.
Only option one removes the cause, and it is the one most likely to be postponed because it needs a budget line or a sprint. If you can do just one thing this week, protect the service; if you can do two, find what is actually growing.