Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Linux Swap and Memory Management

By Kokil Thapa | Last reviewed: September 2026

Linux swap and memory management decide whether your production server survives a traffic spike or kills PHP-FPM mid-request. RAM is fast but finite. When a Laravel queue worker, MySQL buffer pool, and Redis cache compete on a 2 GB VPS, the kernel must choose: reclaim page cache, move cold pages to swap, or invoke the OOM killer. I have debugged this pattern on shared EC2 hosts running multiple legal-tech portals. The fix is rarely "buy more RAM" alone. You need a clear picture of how Linux accounts for memory, when swap helps, and when it hurts latency. This guide walks through inspection commands, swap setup, swappiness tuning, and production habits that keep small VPS hosts stable under load.

What is Linux swap and how does the kernel manage memory?

Physical RAM holds running processes, kernel structures, and the page cache. The kernel tracks memory in pages, typically 4 KB each. Active pages stay in RAM. Inactive anonymous pages (heap, stack) and file-backed pages can be reclaimed or swapped.

Swap is disk space the kernel uses as overflow for RAM. It can live on a dedicated partition or a swap file. Swap is slower than RAM—often 100× or more on NVMe—but it prevents hard failures when memory pressure builds. The kernel's memory management subsystem balances speed against survival.

Three memory types matter on a web server:

  • Anonymous memory — PHP-FPM worker heaps, JavaScript build processes, application buffers. Not tied to a file on disk until swapped.
  • File-backed cache — Linux caches read files (PHP sources, static assets, MySQL data files) in the page cache. The kernel can drop these instantly because the file still exists on disk.
  • Shared memory — OPcache segments, Memcached, shared libraries mapped by multiple processes.
Linux Memory HierarchyPhysical RAMProcesses + page cachePage CacheReclaimable file pagesMemory Pressure HandlerReclaim cache, swap pages, or OOM killSwap SpacePartition or fileOOM KillerLast resort
How Linux swap and memory management routes pressure from RAM through reclaim, swap, or OOM termination.

When you run free -h, the "available" column is the number that matters. It estimates how much memory can be given to new allocations without swapping. Do not panic at high "used" RAM on Linux. An idle server with 1.8 GB of 2 GB "used" may still have 1.2 GB available because most usage is reclaimable cache. That distinction trips up many first-time VPS owners.

For deeper process-level inspection, pair free with the guide on diagnosing high CPU and memory usage on Linux. Application metrics from Laravel Horizon or MySQL SHOW GLOBAL STATUS tell you who consumes RAM; kernel tools tell you whether the host can cope.

How do you check current memory and swap usage on Linux?

Start every investigation with a snapshot. These commands work on Ubuntu 22.04 and 24.04 LTS hosts I use for client deployments.

Essential inspection commands

free -h
swapon --show
cat /proc/swaps
cat /proc/meminfo | head -20
vmstat 1 5

The free -h output labels total, used, free, shared, buff/cache, and available. Watch available, not free. If available drops under 100 MB on a 2 GB box while swap fills, you are in trouble.

vmstat 1 5 prints si (swap in) and so (swap out) per second. Sustained non-zero swap activity under normal load means RAM is undersized or a process leaks memory. Occasional swap during a backup or composer install is tolerable on small hosts.

Per-process memory

ps aux --sort=-%mem | head -15
pmap -x $(pgrep -n php-fpm8.3)
systemctl status php8.3-fpm mysql redis-server

PHP-FPM pools define pm.max_children. Each child can consume 50–150 MB on a Laravel 12 app with OPcache warm. Multiply before you blame swap. MySQL's innodb_buffer_pool_size often dominates RAM on database co-located VPS plans. Redis maxmemory caps are essential when caching sessions.

On production legal-tech portals I maintain, a sudden swap spike after deploy usually traces to opcache reset plus cache warm-up, not a permanent leak. Confirm with a 15-minute vmstat window before changing kernel settings.

When should you add swap on a Linux VPS?

Swap is insurance, not a RAM substitute. It buys time during spikes and prevents the OOM killer from terminating mysqld during a nightly backup. It cannot make a chronically undersized server fast.

Use this decision framework:

  1. No swap, 4 GB+ RAM, monitored alerts — Acceptable for dedicated database servers where predictable latency matters and you can scale RAM quickly.
  2. 1–2 GB RAM VPS running LAMP or LEMP — Add 1–2 GB swap file. This matches most Nepal-hosted budget VPS plans (Rs 800–2,500/month, ~USD 6–19).
  3. Batch jobs on same host as web — Swap prevents queue workers from triggering OOM during large Excel imports via Laravel Excel.
  4. Heavy swap thrashing already — Adding more swap alone will not help. Upgrade RAM or split services across hosts.
Swap Decision FlowRAM pressure rising?Reclaim page cacheStill under pressure?Swap inactive pagesSwap space available?Yes: survive spikeLatency may riseNo: OOM killerProcess terminatedMonitor si/so with vmstat during peaks
Linux swap and memory management decision path from cache reclaim through swap to OOM when disk overflow is exhausted.

If you host multiple sister sites on one EC2 instance—as I do with Deployer 7 releases for notary and translation portals—aggregate peak memory across all PHP pools before sizing swap. One site quiet while another runs a marketing import still shares one kernel.

How do you create and enable a swap file on Ubuntu?

A swap file is easier to resize than repartitioning. Below is the pattern I use on Ubuntu 24.04 with ext4 root volumes. Adjust size to roughly equal RAM on hosts under 4 GB.

Create a 2 GB swap file

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

If fallocate fails on certain filesystems, use dd instead:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

Verify activation:

swapon --show
free -h

Persist vm.swappiness in /etc/sysctl.d/99-swappiness.conf so reboots keep your tuning. Document the change in your runbook alongside log rotation and disk space practices—swap files consume disk budget too.

For step-by-step VPS context, see the dedicated walkthrough on adding a swap file on a small VPS. If disk layout is tight, review LVM flexible disk management before carving space from the root volume.

What is swappiness and how should you tune it for web servers?

Swappiness controls how aggressively the kernel swaps anonymous pages versus dropping cache. It ranges from 0 to 100. Default on Ubuntu is often 60, which is too eager for latency-sensitive PHP-FPM workloads.

Check and set:

cat /proc/sys/vm/swappiness
sudo sysctl vm.swappiness=10
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl -p /etc/sysctl.d/99-swappiness.conf

A value of 10 keeps hot application memory in RAM while still allowing swap under genuine pressure. Values of 1 or 0 reduce swapping further but raise OOM risk on tiny VPS hosts with no headroom.

SettingTypical useWeb server impactRisk profile
60 (default)Desktop UbuntuFrequent swap I/O under moderate loadHigher latency spikes
10PHP-FPM / Nginx VPSCache reclaimed first; swap only when neededBalanced for 2–4 GB RAM
1Database-focused VMMinimal swapping of DB buffersOOM if RAM exhausted
0Real-time or strict latencySwap avoided until criticalOOM unless RAM is generous

The kernel also exposes vfs_cache_pressure (default 100). Raising it to 150 nudges the kernel to reclaim inode/dentry cache sooner, freeing RAM for applications without touching swappiness. I apply this lightly on content-heavy WordPress 7.1 hosts where many small PHP files inflate cache usage.

Swappiness 60 vs 10 on Web VPSswappiness=60PHP workers swapped earlyHigher p95 response timeDisk I/O during normal loadswappiness=10Cache dropped firstWorkers stay in RAM longerSwap reserved for spikesRecommended: swappiness=10 + 1–2 GB swapOn 2 GB Laravel or WordPress VPS hostsValidate with vmstat si/so columns after change
Swappiness tuning effect on Linux swap and memory management for PHP-FPM production servers.

Official kernel documentation on VM sysctl parameters explains swappiness, min_free_kbytes, and overcommit behaviour. The swapoff man page covers safe removal when migrating to larger RAM.

How do you prevent OOM kills and size memory for Laravel and MySQL?

The OOM killer selects a process to terminate when RAM and swap cannot satisfy new allocations. Victims often include high-RSS workers or orphaned Node build processes left on production servers without Node 26 LTS installed locally.

Read OOM events

sudo dmesg -T | grep -i 'out of memory'
sudo journalctl -k | grep -i oom

Logs show the killed process name and score. If php-fpm8.3 disappears during peak traffic, reduce pm.max_children or add RAM before chasing kernel tweaks.

Application-level caps

On a 2 GB VPS running Laravel 12, PHP 8.3, MySQL 9.7 or 8.4 LTS, and Redis 8.10, rough sizing looks like this:

  • MySQL innodb_buffer_pool_size — 512M (never default to 1G on a 2G box)
  • PHP-FPM — pm.max_children = 8 at ~80 MB each ≈ 640 MB peak
  • Redis — maxmemory 128mb with allkeys-lru
  • OS + Nginx + queues — reserve 400–500 MB headroom
  • Swap — 2 GB file as buffer for deploys and backups

Projects like Adventure Third Pole Trek run Laravel with Livewire, queues, and supplier CRM logic. Booking spikes allocate more transient memory than a brochure site. Size for peak concurrent admin sessions, not idle averages.

2 GB VPS Memory BudgetMySQL buffer pool 512 MBPHP-FPM workers up to 640 MBRedis 128 MBOS + Nginx 450 MBSwap file 2 GB on diskSafety net, not primary RAMTotal RAM planned to ~1.7 GB peakLeaves margin before swap thrashing
Example RAM budget showing where Linux swap and memory management fits on a typical Laravel VPS.

Systemd can cap services with MemoryMax= in unit drop-ins. That contains runaway workers but may cause graceful restarts instead of whole-system OOM. See systemd service management on Linux for unit overrides on PHP-FPM and queue workers.

cgroup v2 on modern Ubuntu exposes memory limits per slice. Cloud panels rarely show this; SSH inspection remains essential. If you lack time to tune yourself, Linux system administration support covers swap setup, sysctl tuning, and ongoing monitoring.

What are common swap and memory mistakes on production servers?

These recur across client rescue calls and sister-site maintenance windows.

  • Ignoring "available" in free output — Chasing phantom shortages wastes money on RAM upgrades.
  • Swap on slow network storage — EBS or NFS-backed swap destroys latency. Keep swap on local SSD root volumes.
  • Oversized MySQL buffer pool — The classic 2 GB VPS failure mode. MySQL grabs RAM PHP needs minutes later.
  • Zero swap on small hosts — Saves disk but guarantees hard OOM during harmless spikes like composer update.
  • Removing swap without swapoff — Always run sudo swapoff /swapfile before deleting the file.
  • Skipping post-deploy checks — After PHP version changes, reload FPM and watch vmstat. Opcache behaviour shifts memory curves.

Pair memory work with Linux performance tuning basics and application speed optimization when swap thrashing is a symptom, not the root cause. WooCommerce 11.1 shops on shared hosting face the same maths—admin AJAX and image regeneration spike RAM briefly.

For hosts you migrate rather than tune, review website migration planning so the target VPS has RAM and swap configured before cutover DNS, not after users hit 502 errors.

Ubuntu documents swap setup in the official swap file guide. Cross-check your fstab entry and file permissions against that reference after manual changes.

When estimating whether a host can carry another site, use the Nepal EMI calculator or hosting cost spreadsheets alongside technical sizing—budget and RAM limits often move together on Nepal VPS plans.

Long-term, automate backups and watch disk because swap competes with logs and database dumps. The guide on automating database backups on Linux fits into the same maintenance window as swap verification after kernel updates.

On Quick And Easy Nepalese Grocery, delivery-zone logic and session carts stay in Redis with explicit memory caps. That design choice prevents anonymous PHP session bloat from consuming RAM that should serve checkout API calls.

If you co-locate staging and production on one VM—a budget pattern I discourage—remember both environments share one kernel memory pool. Staging php artisan migrate --seed can swap production FPM workers to disk. Split environments when revenue justifies it.

Transparent huge pages sometimes interact badly with database workloads. Most Laravel VPS defaults work fine untouched. Document before disabling features you do not understand; measure with vmstat first.

Finally, wire alerts when available memory drops below 15% for five minutes. Manual SSH checks do not scale across a dozen sister sites. Even a simple cron posting to email beats discovering OOM at 2 AM during a queue backlog.

Key Takeaways

  • Watch free -h "available" and vmstat si/so—not raw "used" RAM—before changing hardware.
  • Add a 1–2 GB swap file on VPS hosts under 4 GB RAM; set vm.swappiness=10 for PHP-FPM workloads.
  • Size MySQL, PHP-FPM, and Redis caps so peak usage leaves 300–500 MB headroom before swap thrashing.
  • Read dmesg and journal OOM entries to identify which process dies under pressure.
  • Swap is emergency capacity, not a performance strategy—upgrade RAM or split services if si/so stays high.
  • Document sysctl and fstab changes alongside deploy runbooks so rollbacks and migrations stay predictable.

People Also Ask

Is swap bad for SSD life on a Linux VPS?

Modern SSDs handle swap writes better than spinning disks of a decade ago. Occasional swap during spikes creates negligible wear on cloud NVMe volumes. Chronic thrashing hurts performance long before it kills SSD hardware. Fix chronic thrashing with more RAM, not by disabling swap on a 2 GB host.

How much swap should a 2 GB RAM server have?

Match swap to RAM: 2 GB swap on a 2 GB VPS is a practical default for web stacks. Some admins use 1 GB when disk is tight. The combined RAM plus swap should exceed peak working set during your heaviest scheduled job, such as a database backup or report export.

Can you run Linux without swap?

Yes, and many high-RAM database servers do. On small VPS hosts running PHP, MySQL, and Redis together, zero swap increases OOM kill risk during harmless spikes. Production web servers below 4 GB RAM should keep swap enabled with conservative swappiness.

Why does free show almost no free memory even when the server is healthy?

Linux uses unused RAM for page cache to speed disk reads. That cache is reclaimable the moment applications need memory. The "available" column estimates reclaimable cache plus free pages. High cache usage with high available memory is normal healthy behaviour, not a leak.

Build a memory-safe production host

Linux swap and memory management is cheap insurance on VPS hosts that run Laravel, WordPress, or WooCommerce alongside MySQL and Redis. Measure with free, vmstat, and OOM logs. Add a correctly permissioned swap file, set swappiness to 10, and cap application pools so peak usage fits inside physical RAM most hours of the day. Swap should catch spikes—not carry everyday load.

If your server swaps constantly or kills workers during routine traffic, the kernel is telling you the sizing story. I tune these stacks regularly on support and maintenance engagements and shared deploy pipelines. For a full health pass—memory, disk, PHP-FPM, and queue configuration—contact us or explore domain and hosting setup with right-sized VPS plans from the start. Read more Linux guides on the blog, review shipped work in the portfolio, or browse free online tools while you plan your next infrastructure change.

Frequently Asked Questions

Linux swap is disk space the kernel uses as overflow when physical RAM fills. The memory manager tracks RAM in pages, reclaims file-backed cache first, moves cold anonymous pages to swap, and only then invokes the OOM killer. Swap is slower than RAM but prevents hard failures under pressure.

Start with free -h and watch the available column, not free or raw used. Confirm swap with swapon --show and cat /proc/swaps. Run vmstat 1 5 to see si and so swap activity per second. For process-level detail, use ps aux --sort=-%mem, pmap on php-fpm8.3, and systemctl status on PHP-FPM, MySQL, and Redis. Sustained non-zero swap I/O under normal load signals undersized RAM or a leak.

Most used RAM on Linux is often reclaimable buff/cache, not locked application memory. The available column estimates how much RAM new allocations can use without swapping. An idle 2 GB VPS showing 1.8 GB used may still have 1.2 GB available. Chasing phantom shortages and buying RAM based on used alone is a common mistake on first-time VPS setups.

Swap is insurance, not a RAM substitute. Add a 1–2 GB swap file on 1–2 GB LAMP or LEMP VPS hosts, especially when batch jobs share the web server. Skip swap only on 4 GB+ monitored database servers where predictable latency matters. If swap thrashing is already chronic, upgrade RAM or split services instead of enlarging swap alone.

Match swap to RAM: a 2 GB swap file on a 2 GB VPS is the practical default for PHP, MySQL, and Redis stacks. Use 1 GB when disk is tight. Combined RAM plus swap should cover peak working set during your heaviest job, such as a database backup or Laravel Excel import.

On Ubuntu 22.04 or 24.04, run fallocate -l 2G /swapfile, chmod 600 /swapfile, mkswap /swapfile, and swapon /swapfile. Add /swapfile none swap sw 0 0 to /etc/fstab for persistence. If fallocate fails, use dd if=/dev/zero of=/swapfile bs=1M count=2048 instead. Verify with swapon --show and free -h, then document the change in your runbook.

Swappiness is a 0–100 kernel setting controlling how eagerly anonymous pages swap versus cache reclaim. Ubuntu defaults to 60, which is too eager for PHP-FPM. Set vm.swappiness=10 in /etc/sysctl.d/99-swappiness.conf for web servers: cache drops first, swap only under genuine pressure.

Yes, and many high-RAM database servers do. On small VPS hosts running PHP, MySQL, and Redis together, zero swap increases OOM kill risk during harmless spikes like composer update or cache warm-up after deploy. Production web servers below 4 GB RAM should keep swap enabled with conservative swappiness.

Occasional swap during traffic spikes or backups creates negligible wear on modern cloud NVMe volumes. Chronic thrashing hurts latency long before it meaningfully shortens SSD hardware life. Fix persistent swap activity with more RAM or service splitting, not by disabling swap on a 2 GB host where OOM kills become likely.

vmstat si reports swap-in pages per second read from disk into RAM; so reports swap-out pages written to disk. Occasional spikes during composer install or nightly backup are tolerable on small hosts. Sustained non-zero si and so under normal load means RAM is undersized, a process is leaking, or application caps like PHP-FPM pm.max_children are set too high.

Read sudo dmesg -T | grep -i 'out of memory' and journalctl -k for the killed process. On a 2 GB box running Laravel 12, PHP 8.3, MySQL 9.7 or 8.4 LTS, and Redis 8.10, cap innodb_buffer_pool_size at 512M, PHP-FPM pm.max_children around 8 at roughly 80 MB each, Redis maxmemory at 128mb with allkeys-lru, and reserve 400–500 MB OS headroom plus a 2 GB swap file for deploy spikes.

Each Laravel 12 worker with warm OPcache can consume 50–150 MB. On a 2 GB VPS, pm.max_children of 8 at roughly 80 MB each equals about 640 MB peak. Multiply pool size before blaming swap. After PHP version changes or deploys, reload FPM and watch vmstat for 15 minutes because opcache reset and cache warm-up can cause temporary swap spikes mistaken for permanent leaks.

Recurring failures include ignoring available in free output, placing swap on slow network storage like EBS or NFS, setting an oversized MySQL buffer pool on a 2 GB VPS, running zero swap on small hosts, deleting swap files without swapoff first, and skipping post-deploy vmstat checks. Co-locating staging and production on one VM also lets migrate --seed spike swap for live PHP-FPM workers.

vfs_cache_pressure defaults to 100 and controls how aggressively the kernel reclaims inode and dentry cache. Raising it to 150 nudges the kernel to free directory and file metadata cache sooner, returning RAM to applications without lowering swappiness. I apply this lightly on content-heavy WordPress 7.1 hosts where many small PHP files inflate cache usage, but measure with vmstat before and after any sysctl change.

Always run sudo swapoff /swapfile before deleting or resizing the swap file; removing it while active corrupts kernel state. After swapoff, delete or recreate the file, run mkswap and swapon again, and update /etc/fstab. When migrating to a larger-RAM host, configure RAM and swap on the target VPS before DNS cutover, not after users hit 502 errors from OOM on the new server.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: