
September 11, 2026
13 min read
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.
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:
- No swap, 4 GB+ RAM, monitored alerts — Acceptable for dedicated database servers where predictable latency matters and you can scale RAM quickly.
- 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).
- Batch jobs on same host as web — Swap prevents queue workers from triggering OOM during large Excel imports via Laravel Excel.
- Heavy swap thrashing already — Adding more swap alone will not help. Upgrade RAM or split services across hosts.
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.
| Setting | Typical use | Web server impact | Risk profile |
|---|---|---|---|
| 60 (default) | Desktop Ubuntu | Frequent swap I/O under moderate load | Higher latency spikes |
| 10 | PHP-FPM / Nginx VPS | Cache reclaimed first; swap only when needed | Balanced for 2–4 GB RAM |
| 1 | Database-focused VM | Minimal swapping of DB buffers | OOM if RAM exhausted |
| 0 | Real-time or strict latency | Swap avoided until critical | OOM 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.
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 = 8at ~80 MB each ≈ 640 MB peak - Redis —
maxmemory 128mbwithallkeys-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.
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 /swapfilebefore 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" andvmstatsi/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=10for PHP-FPM workloads. - Size MySQL, PHP-FPM, and Redis caps so peak usage leaves 300–500 MB headroom before swap thrashing.
- Read
dmesgand 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
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.

