
Memory leaks in Linux are tricky and hard to notice. Your app start fine, dashboard look good. Then, day after day, it use little more RAM, and at some point Ubuntu server gets slow, and system shut down your application in middle of night. Logs do not say “memory leak”, you just see that service is down. You restart it, and everything works again. Until it happens again. This guide shows you how to find and fix memory leaks in Linux applications.
This guide is to give you clear way to deal with this problem. You will learn how to check if leak is real, find line of code that causes it, and fix it. All command here work on Ubuntu, and I tested it on Ubuntu 24.04 LTS.
Memory leak investigation depend on programming language and runtime used by application. This guide focus on general Linux monitoring tool and practical example for PHP and Node.js application.
TL;DR
- Memory leak occurs when application retain memory it no longer need, causing memory usage to grow unnecessarily over time.
- First, confirm leak with “
free”, “ps”, and “pidstat”. Do not dig into code until you see steady growth. - For PHP, watch your PHP-FPM worker with “ps” and log “
memory_get_usage()” to find where growth start. - To fix it, read data in small piece, put limit on cache, and close what you open.
- Until fix is ready, set “
pm.max_requests” in PHP-FPM or systemd memory limit.
What Is Memory Leak?
Memory leak occur when application retain memory it no longer need or fail to release allocated memory appropriately. This can cause memory usage to grow over time and eventually reduce memory available to other application.

Some normal thing look like leak, but they are not. Linux use free RAM to cache files on purpose, so “full” memory bar does not mean there is problem. But cache with no size limit is leak in real life. Here is simple test to use:
- Normal use: memory goes up, then level off, then drop when load goes down.
- Cache growth: memory usage increase as data is cached but eventually stabilize because cache has maximum size or expiration policy. Unbounded cache may continue growing and cause memory pressure.
- Leak: memory usage continue to grow under similar workload without stabilizing, even after activity decrease. This may indicate memory leak, but further investigation is need to confirm cause.
Most common cause is missing “free()” in files and sockets that are never closed, lists that only grow, event listener in Node.js are never removed, and caches with no size limit.
How to Know If Your Ubuntu Server Has Memory Leak?
Before looking at any code, confirm leak with basic system tool. First, install one extra package you need:
sudo apt update
sudo apt install -y sysstatThis gives you “pidstat”. Other tool below are already on Ubuntu.
Check memory with “free” and “ps”
Start with big picture:
free -hLook at “available” column, as it show how much memory your apps can still get, including cache that Linux can give back. If this number keep getting smaller over hours or days, something is holding on to memory.

Next, find which program use most memory:
ps aux --sort=-%mem | head -n 10The “RSS” column show how much real RAM process is using right now. The “VSZ” column show virtual size. It is often very large even for healthy program, so do not worry about it.

Watch one process over time
One check proves nothing, you need to see trend:
pidstat -r -p <PID> 5This command report memory statistic and page fault for selected process every 5 second. Watch “RSS” column to see how much physical RAM process is using. The first report may show average since system startup, so focus on subsequent interval-based report when tracking change over time.
For deeper understanding of memory value reported by Linux, refer to Linux process memory documentation, which explain how process memory statistics are represented.
Simple tip: Track RSS of suspect process for several hour under similar workload. If memory usage continue to grow without stabilizing, even after activity decrease, it may indicate memory leak or memory retention problem. Investigate further before concluding that leak is present.
For broader view of your server’s resource usage, read guide on monitoring CPU, RAM, and disk usage on a Linux VPS, which cover ways to keep track of overall server performance.
Check if OOM killer already acted
When server run out of memory, Linux OOM killer stop one process to free some. On Ubuntu, you can check if this already happened:
sudo dmesg -T | grep -i "out of memory"
sudo journalctl -k | grep -i "killed process"If you see “php-fpm8.3” or your app’s name, kernel has already stepped in. Write down time of each kill. If it happen at regular gaps, such as every 18 hour, you know how fast leak grow.
Check for PHP memory limit error
PHP has its own safety limit. When one request goes over it, PHP stop and write message to your web server log:
sudo grep -i "allowed memory size" /var/log/nginx/error.logIf you use Apache, check “/var/log/apache2/error.log” instead. This error does not always mean leak. It can also mean one heavy request, such as big import.
For additional detail about PHP’s memory restriction, see PHP core configuration reference, which explain how the “memory_limit” directive control memory allocation for script.
If you’re encountering frequent PHP memory-related errors, our guide on how to set the PHP memory limit for better performance explains how to check and adjust memory available to PHP applications.
If this issue affects WordPress website, you can also follow our guide on fixing the WordPress memory exhausted error to troubleshoot memory-related failures and adjust memory setting.
How to Find Memory Leaks in PHP Apps on Ubuntu
Now you know which process grow. Next, you need to find code that causes it.
Step 1: Watch your PHP-FPM workers
List worker and sort them by memory using below command:
ps -C php-fpm8.3 -o pid,rss,cmd --sort=-rssRun it few times during day. Workers grow little after their first request, and that is normal. A worker whose RSS keep climbing and never drop is one to worry about.
Step 2: Log memory use in your code
To show memory growth, I wrote small PHP script that keep adding data to global array. It print current PHP memory usage every 250 iteration. These iteration simulate repeated work within one process, not separate web request:
<?php
$cache = [];
function handle_request(int $i): void {
global $cache;
$cache[] = str_repeat("x", 10000);
}
for ($i = 1; $i <= 1000; $i++) {
handle_request($i);
if ($i % 250 === 0) {
printf("after %4d requests: %.1f MB\n", $i, memory_get_usage() / 1048576);
}
}You can see output as mentioned below:
after 250 requests: 3.4 MB
after 500 requests: 6.3 MB
after 750 requests: 9.2 MB
after 1000 requests: 12.2 MBNumber goes up in straight line, and it never come back down. That is what leak looks like. In your own app, add same “memory_get_usage()” log inside loop, queue job, or around function you suspect. Place where number climbs is your suspect.
You can also refer to PHP memory_get_usage() documentation to understand how function report memory currently allocated to your script and how its optional parameter affects reported value.
To check peak PHP-managed memory usage of each web request, add following code near top of your entry file. It register shutdown function that logs peak memory allocated by PHP during that request. Include request URI in log to help identify which request produced value:
register_shutdown_function(function () {
error_log("peak memory: " . round(memory_get_peak_usage() /
1048576, 1) . " MB");
});Sort those line and you will see which page use most memory.
I found while testing: when I ran “php -r 'echo ini_get("memory_limit");'” on Ubuntu 24.04, it printed “-1”. That means PHP CLI configuration on my system has no PHP memory limit configured. Your value may be different depending on your PHP installation and configuration. CLI PHP and PHP-FPM can load different configuration files, so check CLI settings separately from FPM setting.
To check PHP-FPM memory limit on Ubuntu, run “grep memory_limit /etc/php/8.3/fpm/php.ini”.
Common causes in PHP apps
- Global arrays, static properties, or other reference that continue accumulating data in long-running PHP processes, such as queue worker or persistent application runtime
- Loading whole big database result or file into memory at once
- Circular reference between object, which can pile up before PHP clean them
- Database connection, file handle, or other resource that are not released when they are no longer needed, especially in long-running process
How to Find Memory Leaks in Node.js Apps on Ubuntu
Node.js generally clean up memory for you, but it can still leak when some code hold on to old data. Easiest way to find cause is to compare heap. Start your app so that it saves snapshot when it gets signal:
node --heapsnapshot-signal=SIGUSR2 app.js
kill -USR2 <PID>Take snapshot after app start, send steady traffic for while, then take another. Open both in Memory tab of Chrome DevTools and use compare view to see which object type grew. Listener added inside request handler and never removed is common cause.
For more advanced investigation, Node.js heap snapshot guide explains how to capture heap snapshot, compare them over time, and identify objects that continue to accumulate.
Quick Fix While You Work on Real One
Sometimes real fix take days. Meanwhile, you want server to stay up. These step help, but think of them as bandage, not cure.
Restart PHP-FPM workers: PHP-FPM can restart each worker after set number of request. This give any leaked memory back to system. On Ubuntu 24.04 with PHP 8.3, edit pool file:
sudo nano /etc/php/8.3/fpm/pool.d/www.confSet this line, then save file:
pm.max_requests = 500Reload PHP-FPM:
sudo systemctl reload php8.3-fpmIf you use another PHP version, change 8.3 to match. Start with number that fit your traffic, and lower it if memory still climb, but not too low. You can also set “memory_limit” in “/etc/php/8.3/fpm/php.ini” so one request cannot use too much RAM.
Set memory limit with systemd: Ubuntu use systemd, so you can set hard limit and stop one leaky process from taking down whole machine:
sudo systemctl set-property php8.3-fpm.service MemoryMax=1GWhen service reach limit, systemd stop it and your restart rule start it again. This is better than letting kernel pick process to kill. Test on less important service first, because limit that is too low can cause endless restart.
Which Tool Should You Use?
| Tool | Best for | Slows the app? | Safe on a live server? |
free / ps / pidstat | Confirming leak exists | No | Yes |
ps -C php-fpm8.3 | Spotting growing PHP-FPM worker | No | Yes |
memory_get_usage() | Finding growth in PHP code | Almost none | Yes |
| Heap snapshots | Finding growth in Node.js | Pauses while saving | Yes, with care |
How to Prevent Memory Leaks in Future
Fixing one leak feels great. Not making next one feels even better.
- Run long tests. Run your app under steady load for several hours on test server. Leak hide in short test.
- Log peak memory. Use “
register_shutdown_function” line above on test server and look for pages that use far more than rest. - Use review checklist. For each pull request, ask what code load, open, or cache, and where it is released.
- Watch trends, not spikes. Memory graph over several days shows leak long before OOM killer does.

How ServerAvatar Can Help
Spotting slow leak is easier when you can see your memory history, instead of checking over SSH now and then. ServerAvatar gives you server and app resource monitoring for your Ubuntu servers in one dashboard, and lets you manage service without terminal. It will not find faulty line of code, but it helps you notice problem sooner.
Key Takeaways
- Confirm leak by watching trend with “
pidstat” or “/proc/<PID>/status” before you look at code. - Watch PHP-FPM workers with “
ps -C php-fpm8.3” and log “memory_get_usage()” to find where growth starts. - Read big data in chunks or with generators. Command-line PHP has no memory limit on Ubuntu by default, so test with care.
- Use “
pm.max_requests” or systemd “MemoryMax” only as short-term protection, never as final fix.
Conclusion
Measure first, find cause second, fix third, and then test last. Most PHP leak come down to one big array or one cache with no limit. Next step is small. Pick PHP-FPM worker that use most memory on your Ubuntu server and track its RSS for few hours. If line keeps going up, you know where to start. And if you want easier way to watch your servers without many SSH sessions, ServerAvatar is worth a try.
FAQs
How to check memory usage of process in Ubuntu?
Run “ps aux --sort=-%mem” to list process by memory use. For one process, run “grep VmRSS /proc/<PID>/status”. The “RSS” number is real RAM process is using right now.
What is difference between memory leak and high memory usage?
High usage can be normal. It may be cache, or it may be big job. Leak is memory that keeps growing over time or over requests and never come back, even when load stay same.
What “Allowed memory size exhausted” mean in PHP?
It means one PHP request went over “memory_limit” setting, so PHP stopped it. It is not always leak. It can come from one heavy task, like large import. If it keeps happening on small request, look for leak.
How does Linux OOM killer decide what to kill?
The kernel gives each process a score. The score depends mostly on how much memory the process uses. The kernel then stops a process with a high score to free memory. To see what it killed, run “sudo dmesg -T | grep -i "out of memory”.
Can restarting service fix memory leak?
Restart clears leaked memory, but leak comes back because code is same. Treat restart, “pm.max_requests”, and systemd limits as short-term help while you fix real cause.
About the author
Meghna Meghwani is a technical writer focused on Linux, Ubuntu, VPS hosting, server management, WordPress, PHP, Node.js, cloud hosting, and DevOps. She creates beginner-friendly tutorials, practical hosting guides, troubleshooting articles, and server security content designed to help developers and businesses manage applications and servers more efficiently.
