Three numbers decide how a VPS handles memory pressure, and on a 2 GB instance the default values of all three are wrong for a web workload: vm.swappiness ships at 60, vm.dirty_background_ratio at 10 and vm.dirty_ratio at 20. Raising only the dirty limits, a common forum recipe, makes write stalls worse; lowering swappiness to zero on a small box invites the OOM killer. Start by reading the live values and the per-cgroup reclaim counters before changing anything.
sysctl vm.swappiness vm.dirty_ratio vm.dirty_background_ratio vm.vfs_cache_pressure
cat /proc/vmstat | grep -E 'pgscan|pgsteal|pgmajfault|nr_dirty|nr_writeback'
cat /sys/fs/cgroup/memory.stat 2>/dev/null | head -12
The measurement targets below apply to any KVM guest, but they matter most when you are squeezing a full stack into a small slice. The managed vs unmanaged VPS comparison is useful context here, because a managed plan generally arrives with these values already tuned for web hosting while an unmanaged image gives you stock kernel defaults.
What swappiness does and does not do
Swappiness is a weight, not a threshold. It biases the ratio of anonymous page reclaim to file-backed page reclaim. At 60 the kernel treats a cold anonymous page and a cold file page roughly equally; at 10 it strongly prefers dropping clean file cache. For a PHP or Python application this is usually what you want, because application heap is expensive to fault back in while page cache is cheap to rebuild from disk.
What swappiness does not control is whether swap is used at all under real pressure. If anonymous memory exceeds RAM, pages go out regardless of the value. Setting it to 0 on kernels before 5.8 meant “never swap anonymous memory unless absolutely forced”, which on a small VPS converts slow page reclaim into a hard OOM kill. Pick 10 for a general web node and measure:
# /etc/sysctl.d/60-vps-memory.conf
vm.swappiness = 10
vm.vfs_cache_pressure = 50
The dirty page problem is a stall, not a bandwidth problem
Dirty pages are filesystem writes sitting in RAM waiting to reach the block device. With dirty_background_ratio=10 on 2 GB, that is roughly 200 MB of buffer before background writeback even starts. On a budget VPS with a shared or network-backed volume, 200 MB of outstanding writes at a few thousand IOPS takes long enough that the next sync write blocks. That is the classic “the site hangs for two seconds every few minutes” signature.
The fix is to convert the ratios into absolute byte limits so behaviour does not change when you resize the plan, and to start background writeback early:
# absolute limits scale predictably on resized plans
vm.dirty_background_bytes = 33554432 # 32 MB
vm.dirty_bytes = 100663296 # 96 MB
vm.dirty_expire_centisecs = 3000 # 30s
vm.dirty_writeback_centisecs = 500
Do not set both dirty_ratio and dirty_bytes: the kernel uses one or the other and the byte form wins when non-zero. Verify with sysctl vm.dirty_bytes and watch nr_dirty and nr_writeback in /proc/vmstat during a copy.
Measuring stall time instead of guessing
Two counters expose the cost directly. pgscan_direct means reclaim ran synchronously in the allocating task’s context — the task itself paid the price. pgsteal versus pgscan tells you reclaim efficiency. Write stalls show up in the PSI memory and IO files.
# 5-minute window, sample counters before and after
snap() { awk '/pgscan_direct|pgsteal_direct|pgmajfault/{print $1,$2}' /proc/vmstat; }
snap > /tmp/a; cat /proc/pressure/memory; cat /proc/pressure/io
sleep 300
snap > /tmp/b; paste /tmp/a /tmp/b | awk '{print $1, $4-$2}'
A healthy 2 GB web node doing steady traffic shows pgscan_direct growth in the low hundreds per five minutes and some avg10 in /proc/pressure/memory below 1. Growth in the tens of thousands, or a full value above 2, means the working set does not fit. No sysctl value fixes that; you either reduce the working set or buy RAM. This is the same arithmetic covered in the cloud VPS scaling model, where resizing RAM is a reboot rather than a migration.
File cache versus application memory on small instances
On a 2 GB box, page cache and application heap compete, and the split changes visibly once you lower swappiness and set absolute dirty limits. A typical WordPress-plus-MariaDB stack on a 2 vCPU / 2 GB plan lands somewhere near this shape after tuning:
| Consumer | Before tuning | After tuning | Driver |
|---|---|---|---|
| MariaDB buffer pool | 256 MB | 384 MB | explicit config |
| PHP-FPM workers (10x) | ~380 MB | ~330 MB | pm.max_children, memory_limit |
| Page cache | ~800 MB | ~700 MB | dirty limits, writeback |
| Swap used | 0 | 60–150 MB | swappiness 10 |
| MemAvailable | 120 MB | 250–300 MB | net effect |
These are representative shapes rather than benchmark results, and the exact numbers depend on your theme, extensions and traffic mix. The point is where the extra MemAvailable comes from: giving the kernel permission to page cold anonymous memory out, and getting dirty data off RAM earlier — not from shrinking the database.
zram as a first line of defence
If your provider’s disk is network-attached, swap I/O costs milliseconds rather than microseconds. A compressed RAM block device fronting swap gives you several hundred MB of effective anonymous capacity at memory speed. Set it up as a priority-100 swap device alongside a disk swapfile at priority 10 so cold pages stay compressed in RAM first.
modprobe zram
echo 512M > /sys/block/zram0/disksize
mkswap /dev/zram0 && swapon -p 100 /dev/zram0
swapon --show # shows priorities and sizes
Keep vm.swappiness at 10–20 with zram, not 100; with swappiness 100 the kernel happily pushes hot pages into a compressed device that still costs CPU to compress and decompress. Track /sys/block/zram0/mm_stat — the ratio of orig_data_size to compr_data_size is typically 2.5–3.5:1 for PHP and database heaps, so 512 MB of zram buys roughly 1.3 GB of effective swap.
Per-service limits beat global tuning
Global sysctls cannot stop one process from consuming all RAM. On cgroup v2, set a memory.high per service so the kernel throttles reclaim inside that cgroup instead of stalling the whole box:
# /etc/systemd/system/php8.3-fpm.service.d/mem.conf
[Service]
MemoryHigh=768M
MemoryMax=1024M
MemorySwapMax=256M
systemctl daemon-reload && systemctl restart php8.3-fpm
cat /sys/fs/cgroup/system.slice/php8.3-fpm.service/memory.events
memory.high causes reclaim in the offending cgroup and surfaces as elevated high counts in memory.events, which is a far more useful signal than a system-wide OOM. memory.max is the hard wall; set it 25 % above the high watermark so bursts complete but leaks still die inside the service, not the kernel.
A tuning order that does not backfire
- Snapshot current sysctls and
/proc/vmstatcounters; nothing below is reversible without them. - Cap the big consumers with cgroup memory limits first — this is the only step that bounds worst-case behaviour.
- Set absolute
dirty_byteslimits sized to about 1.5× your disk’s throughput × 2 seconds. - Lower swappiness to 10 and raise
vfs_cache_pressureonly if you see inode/dentry cache growth inslabtop. - Add zram at priority 100 when the backing disk is remote.
- Re-measure
pgscan_directand PSI memory for a full traffic cycle before declaring success.
Apply memory sysctls to /etc/sysctl.d/ and confirm with sysctl --system that no earlier file overrides yours — file precedence is lexical, so 60-vps-memory.conf beats a stock 50-default.conf. If a value silently reverts, check for another file setting the same key with grep -r swappiness /etc/sysctl.d /usr/lib/sysctl.d.
When the numbers say buy RAM
If pgmajfault grows by more than a few thousand per hour at steady traffic, or PSI memory full avg60 stays above 5 after all of the above, the working set genuinely exceeds the instance. Tuning shifts page reclaim around; it does not create memory. Size the next plan from MemAvailable plus your observed peak anonymous usage, not from a rule of thumb — and if the load is bursty rather than growing, check whether the plan’s dedicated versus shared resource model is actually the constraint before paying for another tier of RAM.


Leave a Reply
You must be logged in to post a comment.