Website Vidya
Linux & ServersStep-by-Step Guide

Diagnose OOM Killer Events in Linux: Logs & Memory Tuning

Learn oom killer events in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
11 min read
PDF Cheat Sheet
Diagnose OOM Killer Events in Linux: Logs & Memory Tuning
AI Executive SummaryWebsiteVidya AI

11 min read

Learn oom killer events in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What dmesg Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

When server workloads unexpectedly vanish without leaving application stack traces or error logs in their userland log files, system administrators must investigate oom killer events in linux to determine whether the kernel intervened to prevent a system-wide lockup. The Out of Memory (OOM) Killer is an emergency kernel subsystem that monitors memory exhaustion and forcibly sacrifices one or more processes to free physical RAM.

Because Linux employs an opportunistic memory overcommit architecture—promising more virtual memory to running applications than exists in physical RAM and swap space combined—a sudden burst in memory allocation can push the memory subsystem into an irrecoverable state. Without the OOM Killer, the entire operating system would deadlock, freeze hardware interrupts, and become completely unresponsive.

In this comprehensive guide, we examine the kernel mechanics governing OOM invocations, dissect the badness heuristic scoring algorithm, demonstrate how to extract forensic OOM telemetry using dmesg and journalctl, and implement memory overcommit and cgroup controls to safeguard critical daemons.

Advertisement
Diagnose OOM Killer Events in Linux: Logs & Memory Tuning — syntax, flags, and practical terminal workflow diagram
Diagnose OOM Killer Events in Linux: Logs & Memory Tuning — command syntax, key options, and production workflow reference.

What dmesg Does and When to Use It

At the operating system level, memory allocation begins when a process requests virtual address space via malloc(), mmap(), or brk(). Under default kernel settings (vm.overcommit_memory = 0), the kernel grants these allocations opportunistically without immediately reserving physical RAM pages, relying on demand paging to assign physical page frames only when written to. When free physical pages, page cache, and swap space are completely exhausted, the kernel page allocator fails in get_page_from_freelist(), triggering out_of_memory() inside the kernel mm/oom_kill.c subsystem.

The OOM Killer selects a sacrificial process using the oom_badness() scoring algorithm. It assigns each process a score between 0 and 1000 based on its resident set size (RSS), page table allocations, and swap usage relative to total available memory. The kernel adjusts this score using the /proc/[pid]/oom_score_adj knob (which accepts integer offsets from -1000 to +1000). A process with an adjustment of -1000 is completely exempt from OOM termination, while a value of +1000 guarantees it will be targeted first.

Under the hood, dmesg gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -T, -k, -g <pat>, -l <list> turns raw process and service tables into actionable diagnostics during incident response.

Availability and Installation Across Linux Distributions

The dmesg utility is packaged in util-linux across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether dmesg is installed and inspect which binary path and version your shell resolves:

type -a dmesg
dmesg --version 2>/dev/null || man -f dmesg

# Illustrative output (reviewed against documentation)
dmesg is /usr/bin/dmesg
dmesg (util-linux)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y util-linux

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y util-linux

# Arch Linux
sudo pacman -S --noconfirm util-linux

# Alpine Linux
sudo apk add --no-cache util-linux

Command Syntax, Arguments, and Exit Status Codes

dmesg [options] | grep -i -E 'killed process|oom-killer'

Diagnosing OOM events relies on combining kernel ring buffer utilities (dmesg) and the systemd journal (journalctl). Using dmesg -T translates raw boot seconds into human-readable timestamps, allowing administrators to correlate memory termination events with application traffic spikes or deployment windows. Piping the output to grep -i -E 'oom|killed process' isolates the exact invocation.

In modern systemd-managed distributions, journalctl -k queries the persistent kernel log stream. Filtering with -g 'Out of memory' or priority flags (-p 3 for errors) extracts the full diagnostic table generated by the kernel. This table provides crucial forensic evidence, including total-vm (total virtual memory pages), anon-rss (anonymous resident pages), file-rss (page cache resident pages), and shmem-rss (shared memory pages) for all active tasks at the moment of failure.

  • 0 — Command executed successfully and matching kernel log messages were returned.
  • 1 — No matching OOM event or log entries found in the kernel buffer.
  • 2 — Syntax error or invalid command-line flag passed to dmesg or journalctl.
  • 130 — Process interrupted by user signal (SIGINT, Ctrl+C).

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-T--ctimeDisplays human-readable timestamps in dmesg output instead of raw seconds since system boot.
-k--dmesgRestricts journalctl queries strictly to kernel messages (equivalent to dmesg).
-g <pat>--grep=<pat>Filters journalctl entries using regular expressions to find OOM killer invocations.
-l <list>--level=<list>Restricts dmesg output to specific log levels (e.g., -l err,crit,alert,emerg).
-w--followFollows the kernel ring buffer in real time to catch emerging memory exhaustion events.
-x--decodeDecodes facility and log-level prefixes into human-readable labels.
-p <range>--priority=<range>Filters systemd journal logs by priority (e.g., -p 3 for errors and higher).
-u <unit>--unit=<unit>Filters systemd journal logs for a specific service unit (e.g., -u mariadb.service).
-S <time>--since=<time>Restricts journal query to logs generated since a specific time or date.

Combining dmesg -T -l err,crit allows fast extraction of severe kernel alerts while filtering out normal driver initialization chatter. For post-mortem analysis of past server crashes, journalctl -k -S 'yesterday' provides persistent log retrieval even if the server has rebooted since the OOM event occurred.

Advertisement

For continuous observation on servers experiencing suspected memory leaks, running dmesg -Tw in a dedicated monitoring session streams new kernel events as they happen, capturing the detailed task table before a hard system lockup.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Search Kernel Ring Buffer for OOM Invocations with Human Timestamps

Extract exact timestamps and terminated process names from the kernel ring buffer.

dmesg -T | grep -i -E 'killed process|oom-killer'

# Illustrative output (reviewed against documentation)
[Fri Oct 23 01:15:22 2026] Out of memory: Killed process 28412 (mysqld) total-vm:8452100kB, anon-rss:6230104kB, file-rss:0kB, shmem-rss:0kB, UID:112 pgtables:16804kB oom_score_adj:0

The -T flag formats the boot timestamp into standard calendar time, showing that PID 28412 (mysqld) was terminated after consuming over 6GB of resident memory.

2. Query Systemd Journal for Historical OOM Events

Search persistent systemd journal logs for out-of-memory kernel events across reboots.

journalctl -k -g "Out of memory" --since "2 days ago"

# Illustrative output (reviewed against documentation)
Oct 21 14:32:01 node-01 kernel: Out of memory: Killed process 14209 (python3) total-vm:4194304kB, anon-rss:3670016kB

Unlike the in-memory dmesg ring buffer, journalctl queries persistent journal files on disk, ensuring historical crashes are reviewable.

3. Inspect Full Process Memory Table at Time of OOM

Display the detailed memory allocation table printed by the kernel immediately preceding process termination.

journalctl -k -p err -e -n 50

# Illustrative output (reviewed against documentation)
kernel: Tasks state (memory values in pages):
kernel: [  pid  ]   uid  tgid total_vm      rss pgtables_bytes swapents oom_score_adj name
kernel: [    742]     0   742    18204     1420       163840        0             0 systemd-journal
kernel: [  28412]   112 28412  2113025  1557526     17207296        0             0 mysqld

The kernel dumps all active task PIDs, virtual memory (total_vm), resident pages (rss), page tables, and oom_score_adj, proving which processes drove memory exhaustion.

4. Query Current OOM Score and Adjustment for a Daemon

Inspect the raw badness score and administrator adjustment value for an active process.

PID=$(pgrep -f nginx | head -n 1)
cat /proc/$PID/oom_score
cat /proc/$PID/oom_score_adj

# Illustrative output (reviewed against documentation)
42
0

The oom_score file shows the calculated badness rank, while oom_score_adj reflects administrator adjustments (0 indicates default neutral priority).

5. Protect Critical Daemons from OOM Termination with oom_score_adj

Set oom_score_adj to -1000 to completely exempt a critical service (such as sshd) from the OOM Killer.

echo -1000 | sudo tee /proc/$(pgrep -f sshd | head -n 1)/oom_score_adj

# Illustrative output (reviewed against documentation)
-1000

Writing -1000 to oom_score_adj marks the process as unkillable by the OOM Killer, ensuring administrators maintain remote SSH access even under memory starvation.

6. Monitor System Memory and Swap Pressure in Real Time

Use free and vmstat to monitor memory depletion and swap activity before an OOM event triggers.

free -h && vmstat 1 5

# Illustrative output (reviewed against documentation)
total        used        free      shared  buff/cache   available
Mem:            15Gi        14Gi       210Mi       120Mi       850Mi       890Mi
Swap:          4.0Gi       3.8Gi       204Mi
procs -----------memory---------- ---swap-- -----io----
 r  b   swpd   free   buff  cache   si   so    bi    bo
 4  1 398420 215040  24500 846000 1200 4500  2300  6700

Elevated swap-out (so) rates combined with near-zero available memory signal imminent memory exhaustion and impending OOM killer action.

Real-World Workflows, Pipelines, and Shell Automation

Automated Incident Alerting and Post-Mortem Forensic Collector

Deploy an automated script that monitors systemd journal entries for OOM events, captures diagnostic state, and notifies operators.

#!/usr/bin/env bash
set -euo pipefail

LOG_EVENT=$(journalctl -k -n 100 -g "Killed process" --output=cat)
if [ -n "$LOG_EVENT" ]; then
  echo "[CRITICAL] OOM Killer event detected!"
  echo "$LOG_EVENT"
  echo "=== Memory Dump ==="
  free -m
  echo "=== Top Memory Consumers ==="
  ps aux --sort=-%mem | head -n 10
fi

# Illustrative output (reviewed against documentation)
[CRITICAL] OOM Killer event detected!
Out of memory: Killed process 28412 (mysqld)
=== Memory Dump ===
              total        used        free
Mem:          16000       15420         580
=== Top Memory Consumers ===
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
node        4102 12.0 45.2 8412000 7232000 ?     Sl   00:10  15:20 node app.js

Automatically correlating the killed process with the active top memory consumers identifies whether a rogue secondary worker starved a primary database daemon.

Tuning Kernel Overcommit and Systemd OOMScoreAdjust

Configure systemd service definitions with OOMScoreAdjust and set conservative kernel overcommit ratios.

# /etc/systemd/system/mysqld.service.d/override.conf
# [Service]
# OOMScoreAdjust=-500

sudo systemctl daemon-reload && sudo systemctl restart mysqld
sysctl vm.overcommit_memory=2
sysctl vm.overcommit_ratio=80

# Illustrative output (reviewed against documentation)
vm.overcommit_memory = 2
vm.overcommit_ratio = 80

Setting vm.overcommit_memory=2 strictly prevents the kernel from granting more memory than Swap + 80% of RAM, eliminating unexpected OOM killer panics.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding dmesg inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Access to dmesg is governed by the sysctl setting kernel.dmesg_restrict. When set to 1, unprivileged users cannot read the kernel log buffer because kernel addresses and memory dumps might facilitate kernel privilege escalation exploits. System administrators should configure appropriate sudo policies or use journalctl with the systemd-journal group for operators who need to diagnose memory issues.

In multi-tenant or containerized environments (Docker, Kubernetes), failure to set memory limits on containers allows a single runaway container to trigger an OOM event on the host node. Utilizing Linux Control Groups (cgroups v2) memory.max and memory.oom.group ensures that if a container exceeds its memory budget, only processes inside that specific container are terminated rather than impacting neighboring tenant services.

GNU/Linux, BSD, and BusyBox Implementation Differences

The dmesg command in util-linux supports rich features like -T (human timestamps) and -l (log levels), whereas BusyBox dmesg (found in minimal Alpine Linux containers) only supports -c (clear) and -s (buffer size). On BusyBox, administrators must read timestamps as raw seconds since boot or inspect /var/log/messages directly.

Similarly, journalctl is unique to systemd-based Linux distributions (Ubuntu, Debian, RHEL, Fedora, Rocky). Non-systemd systems (such as Alpine with OpenRC or Void Linux with runit) rely on traditional syslog daemons (rsyslog, syslog-ng) logging kernel events to /var/log/kern.log or /var/log/messages.

Troubleshooting Common Errors and Diagnostics

dmesg: read kernel buffer failed: Operation not permitted

Root Cause: The kernel.dmesg_restrict sysctl parameter is set to 1, restricting kernel ring buffer access strictly to the root user.

Resolution: Run dmesg with sudo, or inspect system logs via journalctl if your user account is in the adm or systemd-journal group.

sudo dmesg -T | grep -i oom
# Or journalctl:
journalctl -k -g "Out of memory"

Kernel ring buffer wrapped around, losing older OOM event details

Root Cause: On systems with high logging volume, dmesg ring buffer memory has overwritten earlier log entries.

Resolution: Query the persistent on-disk systemd journal or syslog archives which retain historical kernel events across log rotations.

journalctl -k -S "2026-10-22" -U "2026-10-23"
# Or on syslog systems:
zgrep -i oom /var/log/syslog*.gz

Process killed silently with exit code 137 without host dmesg log

Root Cause: The process was running inside a container or systemd slice and exceeded its cgroup memory limit, triggering the cgroup OOM killer rather than the global kernel OOM killer.

Resolution: Inspect container runtime events using docker inspect / crictl or check the specific systemd unit journal.

journalctl -u myapp.service -e
docker inspect <container_id> --format '{{.State.OOMKilled}}'

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
The OOM killer selects its victim using the oom_badness() algorithm, which targets the process holding the largest resident memory footprint (RSS) that can free the most RAM quickly. If a rogue python script consumes 2GB and exhausts available RAM, but MySQL is holding 10GB of buffer pool memory, the kernel will often terminate MySQL because it frees the most memory with a single termination.
Write -1000 to the process's /proc/[pid]/oom_score_adj file. A score adjustment of -1000 completely exempts the process from the OOM killer's selection heuristic. For systemd services, add OOMScoreAdjust=-1000 inside the [Service] section of the unit file.
Exit code 137 means a process was terminated by signal 9 (SIGKILL), because 128 + 9 = 137. When the OOM killer selects a process, it dispatches an uncatchable SIGKILL to immediately reclaim its memory pages.
Adding swap space provides an emergency buffer for inactive anonymous memory pages, which delays OOM events and gives administrators time to respond. However, if application memory demand continuously exceeds physical capacity, the system will experience severe disk thrashing (heavy I/O wait) before swap is exhausted and the OOM killer triggers anyway.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout