How to Fix Linux Out of Memory (OOM) Killer Error
In this tutorial, you'll learn about How to Fix Linux Out of Memory (OOM) Killer Error. We cover key concepts, practical examples, and best practices.
Your application is killed unexpectedly and you find Killed in the output — the Linux OOM killer terminated the process because the system ran out of memory.
The Problem
bazel build
Killed
No error code. Running dmesg shows:
[12345.678] oom-kill: constriction=CONSTRAINT_NONE, oom_score_adj=0
[12345.678] [pid 1234] invoked oom-killer: gfp_mask=0x...
[12345.678] Out of memory: Killed process 1234 (bazel)
Step-by-Step Fix
Step 1: Check memory usage
free -h
Expected:
total used free shared buff/cache available
Mem: 7.6G 7.2G 100M 200M 300M 150M
If available is near zero, the system is under memory pressure.
Step 2: Find what is using memory
ps aux --sort=-%mem | head -10
Or:
top -o %MEM
Step 3: Check OOM killer logs
sudo dmesg | grep -i "oom\|killed"
Step 4: Add swap space
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Make permanent in /etc/fstab:
/swapfile none swap sw 0 0
Step 5: Protect critical processes
# Lower oom_score (less likely to be killed)
sudo echo -500 > /proc/<pid>/oom_score_adj
Make permanent in systemd service:
[Service]
OOMScoreAdjust=-500
Step 6: Adjust vm.overcommit
# Don't overcommit memory
sudo sysctl vm.overcommit_memory=2
sudo sysctl vm.overcommit_ratio=80
Make permanent in /etc/sysctl.conf:
vm.overcommit_memory=2
vm.overcommit_ratio=80
Step 7: Limit process memory with cgroups
sudo systemctl set-property myapp.service MemoryMax=2G
Prevention Tips
- Monitor memory with
free -handhtop - Add swap for memory pressure relief
- Set memory limits on applications
- Configure OOM score adjustment for critical services
- Use
sysctl vm.swappiness=10to reduce swap usage
Common Mistakes with out of memory
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world LINUX code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro