Technology

VPS RAM, Swap and OOM Killer Management

On a VPS, 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.

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 free 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.

How Linux Memory Really Works on a VPS

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.

Key concepts: RAM, virtual memory, cache and buffers

  • Physical RAM: Memory available to the VPS for resident application pages, caches and kernel structures. Workload limits can be lower than the VPS total.
  • Virtual memory: 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.
  • Page cache: 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.
  • Buffers: Kernel buffering, including temporary block-device data; interpret the exact counter definition used by your tool rather than treating every cache category as interchangeable.

Reading free -m without panicking

Check the installed procps version with free --version, then request MiB units:

free -m

The following is an illustrative procps-ng 4.0.4 example in MiB, not a measurement from a server:

              total        used        free      shared  buff/cache   available
Mem:           4096        3072         256          64        1536        1024
Swap:          2048         128        1920

In procps-ng 4.0.4, RAM used = total − available: 4096 − 1024 = 3072 MiB. Do not expect used + free + buff/cache to equal total; shared is not another independent amount to add. Older procps releases may calculate used differently. Available 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. free -h scales units automatically; -m means MiB, not decimal MB.

Essential tools to inspect memory on a VPS

  • htop: An interactive process viewer; use its sort control, commonly F6, to select RES.
  • top: Press M to sort by memory usage in procps top.
  • vmstat 1: The first report’s rates are averages since boot; later reports cover each sampling interval. Process and memory fields are instantaneous in either case. On supporting versions, vmstat -y 1 omits the initial report. si/so show swap in/out per second; -S affects their units. They are separate from block-I/O bi/bo.
  • ps aux --sort=-%mem | head: A quick procps process ranking. RSS/RES sums can count shared pages repeatedly; use PSS from /proc/PID/smaps_rollup where supported and permitted, or the relevant cgroup totals, for a better shared-memory budget.

If you want a deeper monitoring setup with charts and alerts, check our guide on monitoring VPS resource usage with htop, iotop, Netdata and Prometheus. It shows how to turn these snapshots into continuous visibility.

Understanding Swap on a VPS

Swap provides backing storage for eligible memory pages outside their current RAM placement. This guide’s 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.

What swap is (and what it is not)

  • Swap is not performance magic. 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.
  • Swap is a safety net. It can help absorb short spikes and background memory usage, potentially giving you time to react to leaks or misconfigurations before an OOM event.
  • Swap can reduce crashes. Suitable swap can reduce OOM risk for some short spikes, but it does not remove cgroup limits or every allocation constraint.

Checking existing swap

On most Linux VPS distributions, you can inspect swap with:

swapon --show
free -m

If you see no swap configured, consider whether a small swap file suits the workload and whether your VPS environment permits it.

Choosing a swap size for the workload

There is no one-size-fits-all rule. Treat these illustrative starting ranges 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:

RAMIllustrative swapDecision criteria
Up to and including 2 GiB1–2 GiBTest short peaks, storage space and recovery behavior.
Above 2 GiB, up to and including 8 GiB2–4 GiBMeasure active swap I/O and application latency.
Above 8 GiB4–8 GiBLess, more or no swap may fit the workload; size database budgets to avoid sustained swapping.

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.

Do not use swapoff 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.

Creating a swap file

This new 2 GiB swap-file example is for a normal local ext4/XFS filesystem. Use a root shell and confirm sufficient disk space and permission to activate swap. Stop if /swapfile already exists or is a symlink; do not reformat an existing file. Run each line separately and stop on any error. conv=excl refuses an existing destination:

umask 077
dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress conv=excl
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

On a filesystem verified to support preallocated swap files, fallocate -l 2G /swapfile can replace the creation line; do not run both creation methods. XFS supports preallocated swap files from Linux 4.18. Do not use truncate 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 Btrfs swapfile documentation separately.

Only after activation succeeds and swapon --show lists the new file, back up the existing /etc/fstab and add this line if no entry for the path exists. On systemd, run systemctl daemon-reload after editing. Confirm the containing filesystem will be available at boot, and verify activation after a planned maintenance reboot:

/swapfile   none    swap    sw    0   0

Tuning swappiness for better behavior

In Linux 6.12, swappiness ranges from 0 to 200, 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:

  • 10–20: Candidate values to evaluate for a web workload; compare latency and swap activity before retaining them.
  • 60: The Linux 6.12 default. Do not assume the default is unsuitable for servers; evaluate it against the workload.
  • 0: Does not disable swap. The kernel does not initiate swap until free and file-backed pages fall below a zone’s high watermark.
  • Above 100: May suit in-memory swap such as zram or relatively fast swap storage; validate the actual cost trade-off.

Check current value:

cat /proc/sys/vm/swappiness

Record the current value, then test 20 as an example:

sysctl -w vm.swappiness=20

If results worsen, restore the recorded number with sysctl -w vm.swappiness=OLD_VALUE, replacing the placeholder. To persist a tested value, use a local file such as /etc/sysctl.d/90-vps-memory.conf 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:

vm.swappiness = 20

Another reclaim control is vm.vfs_cache_pressure, 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.

The Linux OOM Killer: What It Does and Why

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.

When does the OOM killer trigger?

Typical situations on a VPS:

  • A memory leak in an application or background worker increases memory demand until available capacity or a service boundary is reached.
  • Too many PHP‑FPM or Node.js workers are started, each using more memory than expected.
  • A database (MySQL/PostgreSQL) is configured for a much larger server than the actual VPS.
  • A runaway cron job or script loads a huge dataset into memory.

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’s scope, even when the VPS still has available memory. Separately, an enabled systemd-oomd 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.

How the OOM killer decides what to kill

In the ordinary Linux 6.12 victim scan, the baseline uses resident pages (RSS), swap entries and page-table memory, then applies oom_score_adj. A positive adjustment increases the selection preference; a negative adjustment reduces it. It is separate from CPU scheduler nice priority. Being root or business-critical does not provide a separate automatic score discount in this version.

  • Only eligible candidates in the relevant allocation scope are considered; cgroup/NUMA constraints can narrow that scope.
  • Global init, kernel threads and tasks with oom_score_adj=-1000 are excluded from the ordinary selection path. Special settings or tasks already exiting can lead to different handling.
  • The largest RSS value is not a guaranteed prediction. Inspect /proc/PID/oom_score and /proc/PID/oom_score_adj for the actual numeric PID, but do not treat a snapshot as a complete forecast of constrained selection.

A systemd override such as OOMScoreAdjust=-500 can lower the preference for a critical service. The allowed range is −1000 to +1000; it reserves no RAM, and −1000 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.

The killed process is not necessarily the process that caused the pressure. Correlate the victim, allocating task, cgroup path and concurrent workload; the kernel’s selection does not encode your business priorities.

Detecting past OOM events

Use the following searches as starting points, with the permissions needed to read the logs. They are not a complete event history:

  • dmesg | grep -Ei "out of memory|oom|killed process"
  • journalctl -k | grep -Ei "out of memory|oom|killed process" on a systemd system
  • journalctl -u systemd-oomd if that userspace OOM service is in use
  • /var/log/kern.log or /var/log/messages where the distribution’s logging setup writes them

An abbreviated, illustrative kernel log line is:

Out of memory: Killed process 1234 (php-fpm) total-vm:1024000kB, anon-rss:512000kB, ...

The line identifies a victim; it does not prove the root cause. total-vm is virtual address-space size, while anon-rss 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.

Preventing Out‑of‑Memory Errors in Real Workloads

Use measurements to fit expected load within the stack’s memory budget. Three useful layers are process sizing, service/cgroup limits and capacity planning; none removes the need to handle allocation failures and recover interrupted work.

Right‑sizing PHP‑FPM, Node.js and other application servers

Dynamic applications usually have multiple worker processes. Each worker consumes memory; too many workers cause pressure even if CPU is fine.

PHP‑FPM workers

For PHP sites (WordPress, Laravel, WooCommerce, etc.), PHP‑FPM settings are critical. A common pattern is:

  • Measure process memory under representative peak requests. A 60–150 MB range is only a hypothetical example, not a typical requirement; account for shared pages and transient peaks.
  • Reserve memory for the operating system, database, caches and background tasks first. Do not separately allocate 70–80% of the same RAM to PHP and another large percentage to the database.
  • Choose pm.max_children within the remaining PHP budget and test concurrency. For illustration, 20 workers at an assumed 60–150 MB each require 1.2–3 GB before other services; this arithmetic is not a measured sizing recommendation.

We explain these calculations in detail in our article on choosing the right PHP memory_limit and related PHP settings; pairing those PHP limits with sane pm.max_children helps control two different sources of memory demand; confirm the combined result under load.

Node.js and similar runtimes

  • Size worker count from throughput and measured per-instance memory rather than starting many idle processes.
  • --max-old-space-size limits V8’s 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.
  • 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.

For Java/Kotlin, -Xms sets the initial/minimum Java heap and -Xmx its maximum. Metaspace, thread stacks, native/direct buffers and GC overhead are outside that simple heap budget. Check the JDK’s container awareness and distinguish a JVM heap error from a kernel OOM kill.

Databases: MySQL/PostgreSQL memory budgets

Configuration copied from a larger dedicated server can exceed a smaller VPS’s 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’s entire memory usage.

  • Reserve a measured database budget within the same total used for the other services.
  • Size innodb_buffer_pool_size or shared_buffers inside that budget, leaving room for other allocations.
  • Account for MySQL connection/thread buffers and concurrent operations. PostgreSQL work_mem is a base allowance per query operation, so several operations and sessions can multiply it; it is not a server-wide cap.

For e‑commerce and larger catalog sites, see our deeper dives such as MySQL indexing and query optimization for WooCommerce and our friendly VPS playbook for PostgreSQL performance. Measure whether query and index changes reduce the relevant pressure before choosing a capacity upgrade.

Using systemd and cgroups to fence off memory hogs

The following example targets systemd 243+ with an enabled memory controller in cgroup v2. 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.

This is a service configuration fragment for a Laravel background worker, not a complete application deployment. The unprivileged app 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:

[Unit]
StartLimitIntervalSec=60s
StartLimitBurst=3

[Service]
Type=simple
User=app
WorkingDirectory=/var/www/app
ExecStart=/usr/bin/php /var/www/app/artisan queue:work
MemoryHigh=384M
MemoryMax=512M
OOMPolicy=kill
Restart=on-failure
RestartSec=5s
  • MemoryHigh: Applies reclaim pressure and throttling above the boundary; it does not itself invoke an OOM kill and can be exceeded.
  • MemoryMax: 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 MemorySwapMax.
  • OOMPolicy: Accepts continue, stop or kill, not restart. Here kill requests group-wide termination after an OOM kill.
  • Restart: on-failure 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.

Validate the assembled unit with systemd-analyze verify /etc/systemd/system/worker.service, then use a planned change window for reload/restart and application checks. Inspect effective properties with systemctl show worker.service -p MemoryHigh -p MemoryMax -p MemorySwapMax -p OOMPolicy -p Restart, alongside the cgroup’s memory.events 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.

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 vm.overcommit_ratio or vm.overcommit_kbytes; inspect CommitLimit and Committed_AS in /proc/meminfo. It can make allocations fail earlier and is not automatically the best database setting or a solution to cgroup limits.

Application‑level limits: PHP, workers and queues

Even with system‑level protections, it is smart to put limits inside the application stack:

  • Choose memory_limit for PHP’s tracked script allocations; it is not a total process RSS or child-process limit, and exceeding it is distinct from a kernel OOM kill.
  • Use pm.max_requests or a framework-supported worker recycling policy to contain accumulation while investigating the leak; restarting does not repair its cause.
  • For image processing and reporting, bound input size, operation complexity, concurrency and in-memory queues.

Combining language‑level limits with systemd cgroups gives you several layers of defenses against accidental OOMs.

Security and abuse scenarios

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 VPS security hardening checklist covers many of these defensive layers.

Monitoring and Alerting Before Memory Becomes a Problem

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.

Simple baseline checks

Start with a regular habit:

  • Check free -m and htop during peak traffic.
  • Track which processes consistently use the most RAM.
  • Note swap usage and whether vmstat shows frequent swap in/out activity.

Investigate falling available, 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.

Setting up real monitoring with alerts

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:

  • Graph total, available, cache and swap occupancy over time using documented counter definitions.
  • Track key service/cgroup totals and process memory, accounting for shared pages.
  • Start with a workload-specific rule, such as MemAvailable/MemTotal < 20% 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.

If you want a practical walk‑through, see our guide on VPS monitoring and alerts with Prometheus, Grafana and Uptime Kuma. Test alert delivery and missing-data handling; a spike may develop faster than the evaluation interval.

What to monitor specifically for OOM prevention

  • Memory headroom: Use available memory plus service and parent-cgroup limits, not just free RAM.
  • Swap activity: Compare occupancy with interval si/so, I/O latency and application response time.
  • Per-service memory: Include databases, PHP-FPM, Redis, Node and background workers in one budget.
  • OOM events: Correlate kernel and systemd-oomd logs with increases in memory.events counters.
  • PSI where supported: /proc/pressure/memory reports time stalled on memory; it is not a RAM-use percentage. Track it alongside user-visible performance.

When to Upgrade RAM or Rethink Your Architecture

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.

Signals that it is time to add RAM

  • Representative load repeatedly leaves insufficient available memory or approaches a correctly chosen service limit, with measurable latency or errors.
  • Sustained swap I/O or memory stalls correlate with slowdown; occupied swap alone is insufficient evidence.
  • OOM events continue under legitimate load after application, database and worker budgets have been checked; rule out an overly restrictive cgroup first.
  • Controlled load tests identify memory as the limiting resource before CPU or other I/O.

For realistic load simulations, our article on load testing hosting with k6, JMeter and Locust explains how to find such limits in a controlled way instead of discovering them in production.

Rethinking architecture, not just RAM size

Sometimes the right move is to change how you deploy rather than endlessly scaling RAM on one VPS:

  • Separate database and application servers when both are competing heavily for memory.
  • Introduce dedicated cache layers (Redis, Memcached) to offload repeated queries and session storage.
  • Move heavy analytics, reporting or image processing jobs to a separate background VPS.

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.

Putting It All Together: A Practical Checklist

Adapt this checklist to the kernel, service manager and control features available in your environment:

  1. Get visibility
    • Use the appropriate procps tools and monitoring collectors; verify versions and permissions.
    • Measure quiet periods and representative peaks, including process/cgroup memory and application latency.
  2. Evaluate swap safely
    • Check existing swap and environment permissions. Test a workload-appropriate size rather than assuming a required RAM multiplier.
    • Validate filesystem compatibility and activation before persistence; evaluate swappiness by reclaim cost and measured results.
  3. Tune key services
    • Fit PHP-FPM concurrency and script allocations into one shared service budget.
    • Include database global and concurrent-operation memory.
    • Distinguish Node/JVM heap flags from total process memory.
  4. Contain risky workloads
    • Use supported cgroup v2 MemoryHigh and MemoryMax, accounting for parent and swap limits.
    • Choose valid OOM/restart policies and test interrupted-job recovery; investigate leaks even if workers are recycled.
  5. Set useful alerts
    • Calibrate available-memory and PSI conditions against workload impact.
    • Correlate occupied swap with active swap I/O.
    • Notify on relevant kernel/cgroup/userspace OOM events and test delivery.
  6. Review regularly
    • Re-evaluate after deployments or traffic changes, recording previous settings and a rollback path.
    • Review resource budgets alongside backups and security updates. Our guide on what to do in the first 24 hours on a new VPS provides a broader baseline.

Conclusion: Calm, Predictable Memory Management on Your VPS

Memory management connects the application’s 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.

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.

Primary Technical References

Frequently Asked Questions

There is no required RAM multiplier or universal minimum. The guide’s ranges—1–2 GiB swap up to 2 GiB RAM, 2–4 GiB above 2 through 8 GiB RAM, and 4–8 GiB above that—are illustrative starting examples to test. Measure active working-set demand, available disk space, swap I/O and application latency. Less, more or no swap can fit a workload. Occupied swap alone does not prove current pressure, and swap does not remove cgroup limits.

A VPS can run without swap when the workload and recovery design support it. Swap can provide headroom for eligible pages, but it does not guarantee time to react or prevent every OOM. Judge the choice using active demand, latency and service limits. Do not run swapoff merely to clear an occupancy graph: bringing pages back requires memory and can fail. Linux 6.12 swappiness=0 does not disable swap; it changes reclaim behavior.

Kernel logs identify a victim, which is not necessarily the task that caused the pressure. Search dmesg or journalctl -k with appropriate access, then read surrounding records for allocation constraints and the cgroup. Correlate them with service metrics and application logs; retention may limit the history. If systemd-oomd is active, examine its logs too, since it can terminate workloads before kernel OOM. Distinguish virtual-size and resident-memory fields rather than treating total-vm as RAM usage.

Potential causes include excessive worker concurrency, unbounded caches or input processing, memory leaks, and database global or concurrent-operation allocations that exceed the shared budget. A restrictive cgroup can also cause a local OOM while host memory remains available. Determine the actual mechanism from logs and counters. PHP or Node heap limits are not total process caps; systemd MemoryMax may trigger cgroup OOM rather than a controlled restart. Limits and monitoring reduce some risks but do not guarantee prevention.

Consider additional RAM or separate service roles when representative legitimate load still needs more working memory after budgets and configuration have been checked. Look for insufficient available memory, sustained swap I/O or PSI stalls correlated with latency and errors. First rule out an overly restrictive cgroup or a leak; a fixed percentage or swap that stays occupied is not enough evidence. Test the new design and retain service limits, monitoring and a recovery plan.
↑