{"id":3589,"date":"2025-12-28T16:58:29","date_gmt":"2025-12-28T13:58:29","guid":{"rendered":"https:\/\/www.dchost.com\/blog\/managing-ram-swap-and-the-oom-killer-on-vps-servers\/"},"modified":"2026-11-04T19:42:57","modified_gmt":"2026-11-04T16:42:57","slug":"managing-ram-swap-and-the-oom-killer-on-vps-servers","status":"publish","type":"post","link":"https:\/\/www.dchost.com\/blog\/en\/managing-ram-swap-and-the-oom-killer-on-vps-servers\/","title":{"rendered":"VPS RAM, Swap and OOM Killer Management"},"content":{"rendered":"<div class=\"dchost-blog-content-wrapper\"><p>On a <a href=\"https:\/\/www.dchost.com\/vps\">VPS<\/a>, applications, databases and background jobs may share one memory budget. A rising memory graph or new swap usage calls for investigation, but does not by itself mean the Linux Out-of-Memory (OOM) killer will terminate a process. Understanding RAM, swap and workload limits helps you distinguish normal memory usage from pressure that can cause failures. A failure may also come from a service limit or a runtime allocation error while the VPS still has available memory.<\/p>\n<p>This guide covers memory diagnosis, swap files, kernel reclaim settings, OOM selection, service limits and application budgets. Kernel explanations use Linux 6.12; the illustrative <code>free<\/code> accounting uses procps-ng 4.0.4. Check the versions and permissions in your own environment. Validate configuration changes in a separate test environment first; service restarts and memory-limit changes can interrupt work.<\/p>\n<div id=\"toc_container\" role=\"navigation\" aria-label=\"Table of Contents\" data-nosnippet class=\"toc_transparent no_bullets toc_numbered toc_title_center\"><p class=\"toc_title\">\u0130\u00e7indekiler<\/p><ul class=\"toc_list\"><li><a href=\"#How_Linux_Memory_Really_Works_on_a_VPS\"><span class=\"toc_number toc_depth_1\">1.<\/span> How Linux Memory Really Works on a VPS<\/a><ul><li><a href=\"#Key_concepts_RAM_virtual_memory_cache_and_buffers\"><span class=\"toc_number toc_depth_2\">1.1.<\/span> Key concepts: RAM, virtual memory, cache and buffers<\/a><\/li><li><a href=\"#Reading_free_-m_without_panicking\"><span class=\"toc_number toc_depth_2\">1.2.<\/span> Reading free -m without panicking<\/a><\/li><li><a href=\"#Essential_tools_to_inspect_memory_on_a_VPS\"><span class=\"toc_number toc_depth_2\">1.3.<\/span> Essential tools to inspect memory on a VPS<\/a><\/li><\/ul><\/li><li><a href=\"#Understanding_Swap_on_a_VPS\"><span class=\"toc_number toc_depth_1\">2.<\/span> Understanding Swap on a VPS<\/a><ul><li><a href=\"#What_swap_is_and_what_it_is_not\"><span class=\"toc_number toc_depth_2\">2.1.<\/span> What swap is (and what it is not)<\/a><\/li><li><a href=\"#Checking_existing_swap\"><span class=\"toc_number toc_depth_2\">2.2.<\/span> Checking existing swap<\/a><\/li><li><a href=\"#Choosing_a_swap_size_for_the_workload\"><span class=\"toc_number toc_depth_2\">2.3.<\/span> Choosing a swap size for the workload<\/a><\/li><li><a href=\"#Creating_a_swap_file\"><span class=\"toc_number toc_depth_2\">2.4.<\/span> Creating a swap file<\/a><\/li><li><a href=\"#Tuning_swappiness_for_better_behavior\"><span class=\"toc_number toc_depth_2\">2.5.<\/span> Tuning swappiness for better behavior<\/a><\/li><\/ul><\/li><li><a href=\"#The_Linux_OOM_Killer_What_It_Does_and_Why\"><span class=\"toc_number toc_depth_1\">3.<\/span> The Linux OOM Killer: What It Does and Why<\/a><ul><li><a href=\"#When_does_the_OOM_killer_trigger\"><span class=\"toc_number toc_depth_2\">3.1.<\/span> When does the OOM killer trigger?<\/a><\/li><li><a href=\"#How_the_OOM_killer_decides_what_to_kill\"><span class=\"toc_number toc_depth_2\">3.2.<\/span> How the OOM killer decides what to kill<\/a><\/li><li><a href=\"#Detecting_past_OOM_events\"><span class=\"toc_number toc_depth_2\">3.3.<\/span> Detecting past OOM events<\/a><\/li><\/ul><\/li><li><a href=\"#Preventing_OutofMemory_Errors_in_Real_Workloads\"><span class=\"toc_number toc_depth_1\">4.<\/span> Preventing Out\u2011of\u2011Memory Errors in Real Workloads<\/a><ul><li><a href=\"#Rightsizing_PHPFPM_Nodejs_and_other_application_servers\"><span class=\"toc_number toc_depth_2\">4.1.<\/span> Right\u2011sizing PHP\u2011FPM, Node.js and other application servers<\/a><ul><li><a href=\"#PHPFPM_workers\"><span class=\"toc_number toc_depth_3\">4.1.1.<\/span> PHP\u2011FPM workers<\/a><\/li><li><a href=\"#Nodejs_and_similar_runtimes\"><span class=\"toc_number toc_depth_3\">4.1.2.<\/span> Node.js and similar runtimes<\/a><\/li><\/ul><\/li><li><a href=\"#Databases_MySQLPostgreSQL_memory_budgets\"><span class=\"toc_number toc_depth_2\">4.2.<\/span> Databases: MySQL\/PostgreSQL memory budgets<\/a><\/li><li><a href=\"#Using_systemd_and_cgroups_to_fence_off_memory_hogs\"><span class=\"toc_number toc_depth_2\">4.3.<\/span> Using systemd and cgroups to fence off memory hogs<\/a><\/li><li><a href=\"#Applicationlevel_limits_PHP_workers_and_queues\"><span class=\"toc_number toc_depth_2\">4.4.<\/span> Application\u2011level limits: PHP, workers and queues<\/a><\/li><li><a href=\"#Security_and_abuse_scenarios\"><span class=\"toc_number toc_depth_2\">4.5.<\/span> Security and abuse scenarios<\/a><\/li><\/ul><\/li><li><a href=\"#Monitoring_and_Alerting_Before_Memory_Becomes_a_Problem\"><span class=\"toc_number toc_depth_1\">5.<\/span> Monitoring and Alerting Before Memory Becomes a Problem<\/a><ul><li><a href=\"#Simple_baseline_checks\"><span class=\"toc_number toc_depth_2\">5.1.<\/span> Simple baseline checks<\/a><\/li><li><a href=\"#Setting_up_real_monitoring_with_alerts\"><span class=\"toc_number toc_depth_2\">5.2.<\/span> Setting up real monitoring with alerts<\/a><\/li><li><a href=\"#What_to_monitor_specifically_for_OOM_prevention\"><span class=\"toc_number toc_depth_2\">5.3.<\/span> What to monitor specifically for OOM prevention<\/a><\/li><\/ul><\/li><li><a href=\"#When_to_Upgrade_RAM_or_Rethink_Your_Architecture\"><span class=\"toc_number toc_depth_1\">6.<\/span> When to Upgrade RAM or Rethink Your Architecture<\/a><ul><li><a href=\"#Signals_that_it_is_time_to_add_RAM\"><span class=\"toc_number toc_depth_2\">6.1.<\/span> Signals that it is time to add RAM<\/a><\/li><li><a href=\"#Rethinking_architecture_not_just_RAM_size\"><span class=\"toc_number toc_depth_2\">6.2.<\/span> Rethinking architecture, not just RAM size<\/a><\/li><\/ul><\/li><li><a href=\"#Putting_It_All_Together_A_Practical_Checklist\"><span class=\"toc_number toc_depth_1\">7.<\/span> Putting It All Together: A Practical Checklist<\/a><\/li><li><a href=\"#Conclusion_Calm_Predictable_Memory_Management_on_Your_VPS\"><span class=\"toc_number toc_depth_1\">8.<\/span> Conclusion: Calm, Predictable Memory Management on Your VPS<\/a><\/li><li><a href=\"#Primary_Technical_References\"><span class=\"toc_number toc_depth_1\">9.<\/span> Primary Technical References<\/a><\/li><\/ul><\/div>\n<h2><span id=\"How_Linux_Memory_Really_Works_on_a_VPS\">How Linux Memory Really Works on a VPS<\/span><\/h2>\n<p>Nearly full RAM is not, by itself, evidence of either a healthy cache or a memory problem. Linux uses memory for application pages, kernel structures and caches. Assess available memory, reclaim activity, service limits and application latency together to distinguish ordinary use from pressure.<\/p>\n<h3><span id=\"Key_concepts_RAM_virtual_memory_cache_and_buffers\">Key concepts: RAM, virtual memory, cache and buffers<\/span><\/h3>\n<ul>\n<li><strong>Physical RAM:<\/strong> Memory available to the VPS for resident application pages, caches and kernel structures. Workload limits can be lower than the VPS total.<\/li>\n<li><strong>Virtual memory:<\/strong> The address space and mappings an application sees. It is not RAM plus swap: mappings can be file-backed, shared or not yet backed by allocated physical pages.<\/li>\n<li><strong>Page cache:<\/strong> File data held in RAM. Clean reclaimable pages can be discarded; dirty pages may need writeback before reuse. Not every cached or reclaimable page is immediately available.<\/li>\n<li><strong>Buffers:<\/strong> Kernel buffering, including temporary block-device data; interpret the exact counter definition used by your tool rather than treating every cache category as interchangeable.<\/li>\n<\/ul>\n<h3><span id=\"Reading_free_-m_without_panicking\">Reading <code>free -m<\/code> without panicking<\/span><\/h3>\n<p>Check the installed procps version with <code>free --version<\/code>, then request MiB units:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">free -m\n<\/code><\/pre>\n<p>The following is an <strong>illustrative procps-ng 4.0.4 example in MiB<\/strong>, not a measurement from a server:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">              total        used        free      shared  buff\/cache   available\nMem:           4096        3072         256          64        1536        1024\nSwap:          2048         128        1920\n<\/code><\/pre>\n<p>In procps-ng 4.0.4, RAM <strong>used = total \u2212 available<\/strong>: 4096 \u2212 1024 = 3072 MiB. Do not expect <code>used + free + buff\/cache<\/code> to equal <code>total<\/code>; <code>shared<\/code> is not another independent amount to add. Older procps releases may calculate <code>used<\/code> differently. <strong>Available<\/strong> estimates how much memory can be used for new applications without swapping, accounting for reclaim limits. The 1024 MiB estimate suggests headroom at that moment; use trends and workload\/cgroup limits before concluding that there is no memory pressure. <code>free -h<\/code> scales units automatically; <code>-m<\/code> means MiB, not decimal MB.<\/p>\n<h3><span id=\"Essential_tools_to_inspect_memory_on_a_VPS\">Essential tools to inspect memory on a VPS<\/span><\/h3>\n<ul>\n<li><strong><code>htop<\/code>:<\/strong> An interactive process viewer; use its sort control, commonly <code>F6<\/code>, to select RES.<\/li>\n<li><strong><code>top<\/code>:<\/strong> Press <code>M<\/code> to sort by memory usage in procps top.<\/li>\n<li><strong><code>vmstat 1<\/code>:<\/strong> The first report\u2019s rates are averages since boot; later reports cover each sampling interval. Process and memory fields are instantaneous in either case. On supporting versions, <code>vmstat -y 1<\/code> omits the initial report. <code>si\/so<\/code> show swap in\/out per second; <code>-S<\/code> affects their units. They are separate from block-I\/O <code>bi\/bo<\/code>.<\/li>\n<li><strong><code>ps aux --sort=-%mem | head<\/code>:<\/strong> A quick procps process ranking. RSS\/RES sums can count shared pages repeatedly; use PSS from <code>\/proc\/PID\/smaps_rollup<\/code> where supported and permitted, or the relevant cgroup totals, for a better shared-memory budget.<\/li>\n<\/ul>\n<p>If you want a deeper monitoring setup with charts and alerts, check our guide on <a href=\"https:\/\/www.dchost.com\/blog\/en\/vps-resource-monitoring\/\">monitoring VPS resource usage with htop, iotop, Netdata and Prometheus<\/a>. It shows how to turn these snapshots into continuous visibility.<\/p>\n<h2><span id=\"Understanding_Swap_on_a_VPS\">Understanding Swap on a VPS<\/span><\/h2>\n<p>Swap provides backing storage for eligible memory pages outside their current RAM placement. This guide\u2019s file example uses disk-backed swap; compressed RAM arrangements such as zram behave differently. Swapping need not wait until every byte of RAM is exhausted. Storage latency, active working-set size and reclaim choices determine the effect; NVMe branding alone does not establish acceptable performance.<\/p>\n<h3><span id=\"What_swap_is_and_what_it_is_not\">What swap is (and what it is not)<\/span><\/h3>\n<ul>\n<li><strong>Swap is not performance magic<\/strong>. If your workloads actively need 8 GB at once and you only have 4 GB RAM, adding 8 GB swap will not make the server perform like it has 12 GB RAM. Sustained swapping can make it slow.<\/li>\n<li><strong>Swap is a safety net<\/strong>. It can help absorb short spikes and background memory usage, potentially giving you time to react to leaks or misconfigurations before an OOM event.<\/li>\n<li><strong>Swap can reduce crashes<\/strong>. Suitable swap can reduce OOM risk for some short spikes, but it does not remove cgroup limits or every allocation constraint.<\/li>\n<\/ul>\n<h3><span id=\"Checking_existing_swap\">Checking existing swap<\/span><\/h3>\n<p>On most Linux VPS distributions, you can inspect swap with:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">swapon --show\nfree -m\n<\/code><\/pre>\n<p>If you see no swap configured, consider whether a small swap file suits the workload and whether your VPS environment permits it.<\/p>\n<h3><span id=\"Choosing_a_swap_size_for_the_workload\">Choosing a swap size for the workload<\/span><\/h3>\n<p>There is no one-size-fits-all rule. Treat these <strong>illustrative starting ranges<\/strong> as examples to test against active working-set demand, storage capacity and latency requirements. They are not minimum requirements or a RAM multiplier to apply automatically:<\/p>\n<table>\n<thead>\n<tr>\n<th>RAM<\/th>\n<th>Illustrative swap<\/th>\n<th>Decision criteria<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Up to and including 2 GiB<\/td>\n<td>1\u20132 GiB<\/td>\n<td>Test short peaks, storage space and recovery behavior.<\/td>\n<\/tr>\n<tr>\n<td>Above 2 GiB, up to and including 8 GiB<\/td>\n<td>2\u20134 GiB<\/td>\n<td>Measure active swap I\/O and application latency.<\/td>\n<\/tr>\n<tr>\n<td>Above 8 GiB<\/td>\n<td>4\u20138 GiB<\/td>\n<td>Less, more or no swap may fit the workload; size database budgets to avoid sustained swapping.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>For latency-sensitive databases and in-memory caches, size the active working set and concurrency first. A large swap file does not itself produce I\/O; frequently moving needed pages does. Occupied swap can contain cold pages long after a peak, so it need not return to zero to indicate recovery.<\/p>\n<p>Do not use <code>swapoff<\/code> just to clear an occupancy graph. Moving pages back requires memory and can fail when capacity is insufficient; plan and test swap changes with the workload.<\/p>\n<h3><span id=\"Creating_a_swap_file\">Creating a swap file<\/span><\/h3>\n<p>This <strong>new 2 GiB swap-file example is for a normal local ext4\/XFS filesystem<\/strong>. Use a root shell and confirm sufficient disk space and permission to activate swap. Stop if <code>\/swapfile<\/code> already exists or is a symlink; do not reformat an existing file. Run each line separately and stop on any error. <code>conv=excl<\/code> refuses an existing destination:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">umask 077\ndd if=\/dev\/zero of=\/swapfile bs=1M count=2048 status=progress conv=excl\nchmod 600 \/swapfile\nmkswap \/swapfile\nswapon \/swapfile\n<\/code><\/pre>\n<p>On a filesystem verified to support preallocated swap files, <code>fallocate -l 2G \/swapfile<\/code> can replace the creation line; do not run both creation methods. XFS supports preallocated swap files from Linux 4.18. Do not use <code>truncate<\/code> or a sparse copy to create a file with holes. This general recipe does not cover Btrfs\/COW, compressed, snapshotted or network filesystems. Btrfs requires NODATACOW, no holes and suitable device\/profile placement; follow the version-appropriate <a href=\"https:\/\/btrfs.readthedocs.io\/en\/latest\/Swapfile.html\" rel=\"nofollow noopener\" target=\"_blank\">Btrfs swapfile documentation<\/a> separately.<\/p>\n<p>Only after activation succeeds and <code>swapon --show<\/code> lists the new file, back up the existing <code>\/etc\/fstab<\/code> and add this line if no entry for the path exists. On systemd, run <code>systemctl daemon-reload<\/code> after editing. Confirm the containing filesystem will be available at boot, and verify activation after a planned maintenance reboot:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">\/swapfile   none    swap    sw    0   0\n<\/code><\/pre>\n<h3><span id=\"Tuning_swappiness_for_better_behavior\">Tuning <code>swappiness<\/code> for better behavior<\/span><\/h3>\n<p>In Linux 6.12, <strong>swappiness ranges from 0 to 200<\/strong>, with a kernel default of 60; a distribution may configure another value. It represents the relative I\/O cost of swap versus filesystem paging, not a RAM-use percentage or a fixed trigger threshold. At 100 the assumed costs are equal; lower values treat swap as more expensive. The appropriate value depends on the workload and storage:<\/p>\n<ul>\n<li><strong>10\u201320:<\/strong> Candidate values to evaluate for a web workload; compare latency and swap activity before retaining them.<\/li>\n<li><strong>60:<\/strong> The Linux 6.12 default. Do not assume the default is unsuitable for servers; evaluate it against the workload.<\/li>\n<li><strong>0:<\/strong> Does not disable swap. The kernel does not initiate swap until free and file-backed pages fall below a zone\u2019s high watermark.<\/li>\n<li><strong>Above 100:<\/strong> May suit in-memory swap such as zram or relatively fast swap storage; validate the actual cost trade-off.<\/li>\n<\/ul>\n<p>Check current value:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">cat \/proc\/sys\/vm\/swappiness\n<\/code><\/pre>\n<p>Record the current value, then test 20 as an example:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">sysctl -w vm.swappiness=20\n<\/code><\/pre>\n<p>If results worsen, restore the recorded number with <code>sysctl -w vm.swappiness=OLD_VALUE<\/code>, replacing the placeholder. To persist a tested value, use a local file such as <code>\/etc\/sysctl.d\/90-vps-memory.conf<\/code> and check other definitions and load order. Saving the file does not itself change the running kernel value; verify the targeted setting now and after a planned reboot:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">vm.swappiness = 20\n<\/code><\/pre>\n<p>Another reclaim control is <code>vm.vfs_cache_pressure<\/code>, which concerns inode\/dentry caches rather than a swap threshold. Linux 6.12 defaults to 100. Setting it to 0 prevents pressure-driven reclaim of those caches and can contribute to OOM; very high values can also be costly. Leave it unchanged unless measurements justify a separate experiment.<\/p>\n<h2><span id=\"The_Linux_OOM_Killer_What_It_Does_and_Why\">The Linux OOM Killer: What It Does and Why<\/span><\/h2>\n<p>The kernel OOM killer tries to free memory when an allocation cannot be satisfied within the applicable constraints and reclaim cannot resolve the situation. It does not require every byte of global RAM and swap to be exhausted. A memory cgroup limit or allowed NUMA\/cpuset\/memory-policy scope can be the relevant constraint.<\/p>\n<h3><span id=\"When_does_the_OOM_killer_trigger\">When does the OOM killer trigger?<\/span><\/h3>\n<p>Typical situations on a VPS:<\/p>\n<ul>\n<li>A memory leak in an application or background worker increases memory demand until available capacity or a service boundary is reached.<\/li>\n<li>Too many PHP\u2011FPM or Node.js workers are started, each using more memory than expected.<\/li>\n<li>A database (MySQL\/PostgreSQL) is configured for a much larger server than the actual VPS.<\/li>\n<li>A runaway cron job or script loads a huge dataset into memory.<\/li>\n<\/ul>\n<p>Not every failed allocation triggers an OOM kill: some callers receive an allocation error or handle the failure another way. A cgroup-local OOM searches within that group\u2019s scope, even when the VPS still has available memory. Separately, an enabled <code>systemd-oomd<\/code> uses cgroup v2 and PSI to act before kernel OOM; a runtime heap error is another distinct failure. Diagnose the mechanism from logs and counters before changing capacity.<\/p>\n<h3><span id=\"How_the_OOM_killer_decides_what_to_kill\">How the OOM killer decides what to kill<\/span><\/h3>\n<p>In the ordinary Linux 6.12 victim scan, the baseline uses resident pages (RSS), swap entries and page-table memory, then applies <code>oom_score_adj<\/code>. A positive adjustment increases the selection preference; a negative adjustment reduces it. It is separate from CPU scheduler <code>nice<\/code> priority. Being root or business-critical does not provide a separate automatic score discount in this version.<\/p>\n<ul>\n<li>Only eligible candidates in the relevant allocation scope are considered; cgroup\/NUMA constraints can narrow that scope.<\/li>\n<li>Global init, kernel threads and tasks with <code>oom_score_adj=-1000<\/code> are excluded from the ordinary selection path. Special settings or tasks already exiting can lead to different handling.<\/li>\n<li>The largest RSS value is not a guaranteed prediction. Inspect <code>\/proc\/PID\/oom_score<\/code> and <code>\/proc\/PID\/oom_score_adj<\/code> for the actual numeric PID, but do not treat a snapshot as a complete forecast of constrained selection.<\/li>\n<\/ul>\n<p>A systemd override such as <code>OOMScoreAdjust=-500<\/code> can lower the preference for a critical service. The allowed range is \u22121000 to +1000; it reserves no RAM, and \u22121000 is not protection against other managers or administrative signals. Record and test the old setting before changing it; making every service ineligible can worsen recovery.<\/p>\n<p>The killed process is not necessarily the process that caused the pressure. Correlate the victim, allocating task, cgroup path and concurrent workload; the kernel\u2019s selection does not encode your business priorities.<\/p>\n<h3><span id=\"Detecting_past_OOM_events\">Detecting past OOM events<\/span><\/h3>\n<p>Use the following searches as starting points, with the permissions needed to read the logs. They are not a complete event history:<\/p>\n<ul>\n<li><code>dmesg | grep -Ei \"out of memory|oom|killed process\"<\/code><\/li>\n<li><code>journalctl -k | grep -Ei \"out of memory|oom|killed process\"<\/code> on a systemd system<\/li>\n<li><code>journalctl -u systemd-oomd<\/code> if that userspace OOM service is in use<\/li>\n<li><code>\/var\/log\/kern.log<\/code> or <code>\/var\/log\/messages<\/code> where the distribution\u2019s logging setup writes them<\/li>\n<\/ul>\n<p>An abbreviated, illustrative kernel log line is:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">Out of memory: Killed process 1234 (php-fpm) total-vm:1024000kB, anon-rss:512000kB, ...\n<\/code><\/pre>\n<p>The line identifies a victim; it does not prove the root cause. <code>total-vm<\/code> is virtual address-space size, while <code>anon-rss<\/code> is one resident-memory category, not total process memory. Read surrounding records for the allocation constraint, cgroup and other tasks, and correlate them with application\/service logs. Retention and access restrictions can hide past events.<\/p>\n<h2><span id=\"Preventing_OutofMemory_Errors_in_Real_Workloads\">Preventing Out\u2011of\u2011Memory Errors in Real Workloads<\/span><\/h2>\n<p>Use measurements to fit expected load within the stack\u2019s memory budget. Three useful layers are <strong>process sizing<\/strong>, <strong>service\/cgroup limits<\/strong> and <strong>capacity planning<\/strong>; none removes the need to handle allocation failures and recover interrupted work.<\/p>\n<h3><span id=\"Rightsizing_PHPFPM_Nodejs_and_other_application_servers\">Right\u2011sizing PHP\u2011FPM, Node.js and other application servers<\/span><\/h3>\n<p>Dynamic applications usually have multiple worker processes. Each worker consumes memory; too many workers cause pressure even if CPU is fine.<\/p>\n<h4><span id=\"PHPFPM_workers\">PHP\u2011FPM workers<\/span><\/h4>\n<p>For PHP sites (WordPress, Laravel, WooCommerce, etc.), PHP\u2011FPM settings are critical. A common pattern is:<\/p>\n<ul>\n<li>Measure process memory under representative peak requests. A 60\u2013150 MB range is only a hypothetical example, not a typical requirement; account for shared pages and transient peaks.<\/li>\n<li>Reserve memory for the operating system, database, caches and background tasks first. Do not separately allocate 70\u201380% of the same RAM to PHP and another large percentage to the database.<\/li>\n<li>Choose <code>pm.max_children<\/code> within the remaining PHP budget and test concurrency. For illustration, 20 workers at an assumed 60\u2013150 MB each require 1.2\u20133 GB before other services; this arithmetic is not a measured sizing recommendation.<\/li>\n<\/ul>\n<p>We explain these calculations in detail in our article on <a href=\"https:\/\/www.dchost.com\/blog\/en\/php-memory-time-file-upload-limits\/\">choosing the right PHP memory_limit and related PHP settings<\/a>; pairing those PHP limits with sane <code>pm.max_children<\/code> helps control two different sources of memory demand; confirm the combined result under load.<\/p>\n<h4><span id=\"Nodejs_and_similar_runtimes\">Node.js and similar runtimes<\/span><\/h4>\n<ul>\n<li>Size worker count from throughput and measured per-instance memory rather than starting many idle processes.<\/li>\n<li><code>--max-old-space-size<\/code> limits V8\u2019s old-space heap in MiB, not total RSS. Young-generation memory, Buffers and native allocations need additional budget; use a cgroup limit if a service total must be bounded.<\/li>\n<li>Use a process manager such as PM2 or systemd for lifecycle handling, while fixing leaks and bounding in-memory caches. Automatic restarts do not fix a leak.<\/li>\n<\/ul>\n<p>For Java\/Kotlin, <code>-Xms<\/code> sets the initial\/minimum Java heap and <code>-Xmx<\/code> its maximum. Metaspace, thread stacks, native\/direct buffers and GC overhead are outside that simple heap budget. Check the JDK\u2019s container awareness and distinguish a JVM heap error from a kernel OOM kill.<\/p>\n<h3><span id=\"Databases_MySQLPostgreSQL_memory_budgets\">Databases: MySQL\/PostgreSQL memory budgets<\/span><\/h3>\n<p>Configuration copied from a larger <a href=\"https:\/\/www.dchost.com\/dedicated-server\">dedicated server<\/a> can exceed a smaller VPS\u2019s budget. For example, a 4 GiB buffer pool leaves no RAM budget for other needs on a 4 GiB VPS. Exact startup or runtime behavior depends on allocation, limits and swap; a buffer setting is not the database process\u2019s entire memory usage.<\/p>\n<ul>\n<li>Reserve a measured database budget within the same total used for the other services.<\/li>\n<li>Size <code>innodb_buffer_pool_size<\/code> or <code>shared_buffers<\/code> inside that budget, leaving room for other allocations.<\/li>\n<li>Account for MySQL connection\/thread buffers and concurrent operations. PostgreSQL <code>work_mem<\/code> is a base allowance per query operation, so several operations and sessions can multiply it; it is not a server-wide cap.<\/li>\n<\/ul>\n<p>For e\u2011commerce and larger catalog sites, see our deeper dives such as <a href=\"https:\/\/www.dchost.com\/blog\/en\/mysql-indexing-and-query-optimization-for-woocommerce\/\">MySQL indexing and query optimization for WooCommerce<\/a> and our <a href=\"https:\/\/www.dchost.com\/blog\/en\/postgresql-vps-memory-wal-pgbouncer\/\">friendly VPS playbook for PostgreSQL performance<\/a>. Measure whether query and index changes reduce the relevant pressure before choosing a capacity upgrade.<\/p>\n<h3><span id=\"Using_systemd_and_cgroups_to_fence_off_memory_hogs\">Using systemd and cgroups to fence off memory hogs<\/span><\/h3>\n<p>The following example targets systemd 243+ with an enabled memory controller in <strong>cgroup v2<\/strong>. Parent-cgroup limits also apply. Verify the actual unit, user and executable paths; these settings manage the service group, not just a single language heap.<\/p>\n<p>This is a service configuration fragment for a Laravel background worker, not a complete application deployment. The unprivileged <code>app<\/code> account, application path, PHP binary and queue configuration must already exist and be tested; use your real values. The 384\/512 MiB limits are illustrative. Preserve other required unit settings and validate the resulting unit before a planned restart:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">[Unit]\nStartLimitIntervalSec=60s\nStartLimitBurst=3\n\n[Service]\nType=simple\nUser=app\nWorkingDirectory=\/var\/www\/app\nExecStart=\/usr\/bin\/php \/var\/www\/app\/artisan queue:work\nMemoryHigh=384M\nMemoryMax=512M\nOOMPolicy=kill\nRestart=on-failure\nRestartSec=5s\n<\/code><\/pre>\n<ul>\n<li><strong>MemoryHigh:<\/strong> Applies reclaim pressure and throttling above the boundary; it does not itself invoke an OOM kill and can be exceeded.<\/li>\n<li><strong>MemoryMax:<\/strong> If usage cannot be contained, the kernel may invoke OOM within the cgroup. Some allocations fail instead, and temporary overshoot is possible. Swap is controlled separately by <code>MemorySwapMax<\/code>.<\/li>\n<li><strong>OOMPolicy:<\/strong> Accepts <code>continue<\/code>, <code>stop<\/code> or <code>kill<\/code>, not <code>restart<\/code>. Here <code>kill<\/code> requests group-wide termination after an OOM kill.<\/li>\n<li><strong>Restart:<\/strong> <code>on-failure<\/code> controls a subsequent restart, with a five-second delay and start-rate limit in this example. It does not make an interrupted job safe to replay.<\/li>\n<\/ul>\n<p>Validate the assembled unit with <code>systemd-analyze verify \/etc\/systemd\/system\/worker.service<\/code>, then use a planned change window for reload\/restart and application checks. Inspect effective properties with <code>systemctl show worker.service -p MemoryHigh -p MemoryMax -p MemorySwapMax -p OOMPolicy -p Restart<\/code>, alongside the cgroup\u2019s <code>memory.events<\/code> counters. Test job retry\/idempotency and failure recovery in isolation. To roll back, restore only the settings changed for this example, preserving unrelated unit configuration; do not rely on automatic restart to recover a workload that cannot fit.<\/p>\n<p>Overcommit is a separate policy: Linux modes 0, 1 and 2 provide heuristic, permissive and bounded commitment accounting. Mode 2 limits commitment using swap plus a configured RAM allowance from <code>vm.overcommit_ratio<\/code> or <code>vm.overcommit_kbytes<\/code>; inspect <code>CommitLimit<\/code> and <code>Committed_AS<\/code> in <code>\/proc\/meminfo<\/code>. It can make allocations fail earlier and is not automatically the best database setting or a solution to cgroup limits.<\/p>\n<h3><span id=\"Applicationlevel_limits_PHP_workers_and_queues\">Application\u2011level limits: PHP, workers and queues<\/span><\/h3>\n<p>Even with system\u2011level protections, it is smart to put <strong>limits inside the application stack<\/strong>:<\/p>\n<ul>\n<li>Choose <code>memory_limit<\/code> for PHP\u2019s tracked script allocations; it is not a total process RSS or child-process limit, and exceeding it is distinct from a kernel OOM kill.<\/li>\n<li>Use <code>pm.max_requests<\/code> or a framework-supported worker recycling policy to contain accumulation while investigating the leak; restarting does not repair its cause.<\/li>\n<li>For image processing and reporting, bound input size, operation complexity, concurrency and in-memory queues.<\/li>\n<\/ul>\n<p>Combining language\u2011level limits with systemd cgroups gives you several layers of defenses against accidental OOMs.<\/p>\n<h3><span id=\"Security_and_abuse_scenarios\">Security and abuse scenarios<\/span><\/h3>\n<p>Untrusted input can also cause memory problems: huge XML or JSON payloads, unbounded file uploads, or intentionally expensive queries. Pairing good RAM practices with hardening (firewalls, rate limiting, WAF) reduces the chance that an attacker can push your VPS into OOM territory. Our <a href=\"https:\/\/www.dchost.com\/blog\/en\/vps-ssh-hardening\/\">VPS security hardening checklist<\/a> covers many of these defensive layers.<\/p>\n<h2><span id=\"Monitoring_and_Alerting_Before_Memory_Becomes_a_Problem\">Monitoring and Alerting Before Memory Becomes a Problem<\/span><\/h2>\n<p>Time-series monitoring can reveal both trends and short peaks, giving you evidence for configuration and capacity decisions. It complements incident logs and application checks; it cannot guarantee intervention before every sudden allocation failure.<\/p>\n<h3><span id=\"Simple_baseline_checks\">Simple baseline checks<\/span><\/h3>\n<p>Start with a regular habit:<\/p>\n<ul>\n<li>Check <code>free -m<\/code> and <code>htop<\/code> during peak traffic.<\/li>\n<li>Track which processes consistently use the most RAM.<\/li>\n<li>Note swap usage and whether <code>vmstat<\/code> shows frequent swap in\/out activity.<\/li>\n<\/ul>\n<p>Investigate falling <code>available<\/code>, sustained swap I\/O, rising memory-stall time or approaching cgroup limits when they correlate with workload impact. Swap usage that stays above zero may simply contain cold pages; its occupancy alone does not establish a leak or current pressure.<\/p>\n<h3><span id=\"Setting_up_real_monitoring_with_alerts\">Setting up real monitoring with alerts<\/span><\/h3>\n<p>For continuous visibility, use appropriate exporters or agents for host, process and cgroup metrics. Prometheus can collect the data and Grafana can display it; an uptime probe checks service reachability and does not itself provide all process-memory counters. With the necessary collectors, you can:<\/p>\n<ul>\n<li>Graph total, available, cache and swap occupancy over time using documented counter definitions.<\/li>\n<li>Track key service\/cgroup totals and process memory, accounting for shared pages.<\/li>\n<li>Start with a workload-specific rule, such as <code>MemAvailable\/MemTotal &lt; 20%<\/code> for ten minutes, then calibrate against latency and expected peaks. A fixed RAM percentage or 512 MiB of occupied swap is not an OOM boundary.<\/li>\n<\/ul>\n<p>If you want a practical walk\u2011through, see our guide on <a href=\"https:\/\/www.dchost.com\/blog\/en\/vps-monitoring-prometheus-grafana-uptime-kuma\/\">VPS monitoring and alerts with Prometheus, Grafana and Uptime Kuma<\/a>. Test alert delivery and missing-data handling; a spike may develop faster than the evaluation interval.<\/p>\n<h3><span id=\"What_to_monitor_specifically_for_OOM_prevention\">What to monitor specifically for OOM prevention<\/span><\/h3>\n<ul>\n<li><strong>Memory headroom:<\/strong> Use available memory plus service and parent-cgroup limits, not just free RAM.<\/li>\n<li><strong>Swap activity:<\/strong> Compare occupancy with interval <code>si\/so<\/code>, I\/O latency and application response time.<\/li>\n<li><strong>Per-service memory:<\/strong> Include databases, PHP-FPM, Redis, Node and background workers in one budget.<\/li>\n<li><strong>OOM events:<\/strong> Correlate kernel and systemd-oomd logs with increases in <code>memory.events<\/code> counters.<\/li>\n<li><strong>PSI where supported:<\/strong> <code>\/proc\/pressure\/memory<\/code> reports time stalled on memory; it is not a RAM-use percentage. Track it alongside user-visible performance.<\/li>\n<\/ul>\n<h2><span id=\"When_to_Upgrade_RAM_or_Rethink_Your_Architecture\">When to Upgrade RAM or Rethink Your Architecture<\/span><\/h2>\n<p>Even with perfect tuning, there is a point where your workload simply needs more RAM than a given VPS can offer. The key is to recognise this early, using data rather than guessing.<\/p>\n<h3><span id=\"Signals_that_it_is_time_to_add_RAM\">Signals that it is time to add RAM<\/span><\/h3>\n<ul>\n<li>Representative load repeatedly leaves insufficient available memory or approaches a correctly chosen service limit, with measurable latency or errors.<\/li>\n<li>Sustained swap I\/O or memory stalls correlate with slowdown; occupied swap alone is insufficient evidence.<\/li>\n<li>OOM events continue under legitimate load after application, database and worker budgets have been checked; rule out an overly restrictive cgroup first.<\/li>\n<li>Controlled load tests identify memory as the limiting resource before CPU or other I\/O.<\/li>\n<\/ul>\n<p>For realistic load simulations, our article on <a href=\"https:\/\/www.dchost.com\/blog\/en\/load-test-hosting-with-k6-jmeter-and-locust\/\">load testing hosting with k6, JMeter and Locust<\/a> explains how to find such limits in a controlled way instead of discovering them in production.<\/p>\n<h3><span id=\"Rethinking_architecture_not_just_RAM_size\">Rethinking architecture, not just RAM size<\/span><\/h3>\n<p>Sometimes the right move is to change how you deploy rather than endlessly scaling RAM on one VPS:<\/p>\n<ul>\n<li>Separate database and application servers when both are competing heavily for memory.<\/li>\n<li>Introduce dedicated cache layers (Redis, Memcached) to offload repeated queries and session storage.<\/li>\n<li>Move heavy analytics, reporting or image processing jobs to a separate background VPS.<\/li>\n<\/ul>\n<p>A workload can move from one VPS to separate roles, larger servers or colocation when measurements justify the cost and management effort. The same memory-budgeting principles apply, but splitting services adds network and operational dependencies; extra machines alone do not fix unbounded allocation or a leak.<\/p>\n<h2><span id=\"Putting_It_All_Together_A_Practical_Checklist\">Putting It All Together: A Practical Checklist<\/span><\/h2>\n<p>Adapt this checklist to the kernel, service manager and control features available in your environment:<\/p>\n<ol>\n<li><strong>Get visibility<\/strong>\n<ul>\n<li>Use the appropriate procps tools and monitoring collectors; verify versions and permissions.<\/li>\n<li>Measure quiet periods and representative peaks, including process\/cgroup memory and application latency.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Evaluate swap safely<\/strong>\n<ul>\n<li>Check existing swap and environment permissions. Test a workload-appropriate size rather than assuming a required RAM multiplier.<\/li>\n<li>Validate filesystem compatibility and activation before persistence; evaluate swappiness by reclaim cost and measured results.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Tune key services<\/strong>\n<ul>\n<li>Fit PHP-FPM concurrency and script allocations into one shared service budget.<\/li>\n<li>Include database global and concurrent-operation memory.<\/li>\n<li>Distinguish Node\/JVM heap flags from total process memory.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Contain risky workloads<\/strong>\n<ul>\n<li>Use supported cgroup v2 <code>MemoryHigh<\/code> and <code>MemoryMax<\/code>, accounting for parent and swap limits.<\/li>\n<li>Choose valid OOM\/restart policies and test interrupted-job recovery; investigate leaks even if workers are recycled.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Set useful alerts<\/strong>\n<ul>\n<li>Calibrate available-memory and PSI conditions against workload impact.<\/li>\n<li>Correlate occupied swap with active swap I\/O.<\/li>\n<li>Notify on relevant kernel\/cgroup\/userspace OOM events and test delivery.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Review regularly<\/strong>\n<ul>\n<li>Re-evaluate after deployments or traffic changes, recording previous settings and a rollback path.<\/li>\n<li>Review resource budgets alongside backups and security updates. Our guide on <a href=\"https:\/\/www.dchost.com\/blog\/en\/first-24-hours-on-a-new-vps-updates-firewall-and-users-step-by-step\/\">what to do in the first 24 hours on a new VPS<\/a> provides a broader baseline.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<h2><span id=\"Conclusion_Calm_Predictable_Memory_Management_on_Your_VPS\">Conclusion: Calm, Predictable Memory Management on Your VPS<\/span><\/h2>\n<p>Memory management connects the application\u2019s active working set with kernel reclaim, swap, service boundaries and recovery behavior. Interpreting available memory and pressure correctly helps you investigate a failure; understanding the OOM scope prevents a victim process from being mistaken automatically for the cause.<\/p>\n<p>Combine measured RAM budgets, a deliberate swap decision, supported service limits and tested alerts. Record current settings, choose one change and compare results under representative load before adopting it. Add capacity or split services when the evidence justifies it, with an explicit recovery and rollback plan. This improves control of memory-related failures without promising that tuning can eliminate every OOM event.<\/p>\n<h2><span id=\"Primary_Technical_References\">Primary Technical References<\/span><\/h2>\n<ul>\n<li><a href=\"https:\/\/docs.kernel.org\/6.12\/admin-guide\/sysctl\/vm.html\" rel=\"nofollow noopener\" target=\"_blank\">Linux 6.12 \u2014 VM sysctl<\/a><\/li>\n<li><a href=\"https:\/\/docs.kernel.org\/6.12\/admin-guide\/cgroup-v2.html\" rel=\"nofollow noopener\" target=\"_blank\">Linux 6.12 \u2014 cgroup v2<\/a><\/li>\n<li><a href=\"https:\/\/gitlab.com\/procps-ng\/procps\/-\/blob\/v4.0.4\/man\/free.1\" rel=\"nofollow noopener\" target=\"_blank\">procps-ng 4.0.4 \u2014 free<\/a><\/li>\n<li><a href=\"https:\/\/man7.org\/linux\/man-pages\/man8\/vmstat.8.html\" rel=\"nofollow noopener\" target=\"_blank\">procps-ng \u2014 vmstat<\/a><\/li>\n<li><a href=\"https:\/\/man7.org\/linux\/man-pages\/man8\/swapon.8.html\" rel=\"nofollow noopener\" target=\"_blank\">util-linux \u2014 swapon<\/a><\/li>\n<li><a href=\"https:\/\/www.freedesktop.org\/software\/systemd\/man\/latest\/systemd.resource-control.html\" rel=\"nofollow noopener\" target=\"_blank\">systemd \u2014 Resource Control<\/a><\/li>\n<li><a href=\"https:\/\/www.freedesktop.org\/software\/systemd\/man\/latest\/systemd.service.html\" rel=\"nofollow noopener\" target=\"_blank\">systemd \u2014 Service Configuration<\/a><\/li>\n<\/ul>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Interpret available memory and swap activity on a Linux VPS. Follow a scoped swap-file example and plan kernel settings, service limits, application budgets and OOM recovery.<\/p>\n","protected":false},"author":1,"featured_media":12520,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[184],"tags":[],"class_list":["post-3589","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts\/3589","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/comments?post=3589"}],"version-history":[{"count":8,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts\/3589\/revisions"}],"predecessor-version":[{"id":12601,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts\/3589\/revisions\/12601"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/media\/12520"}],"wp:attachment":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/media?parent=3589"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/categories?post=3589"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/tags?post=3589"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}