# Creating swap space and preventing out-of-memory (OOM) errors

https://www.hostimor.com/en/knowledgebase/article/create-swap-space-prevent-oom

Swap space is a safety margin that often keeps the kernel from forcibly killing a process when memory suddenly fills up. This guide covers creating a swap file, the right kernel settings and, most importantly, how to rein in the service that is eating your memory.

## What swap does and what it does not do

Swap is an area set aside on disk: the kernel moves memory pages that have not been used for a while there to free up RAM. When memory runs out completely and there is no swap, or the swap is full too, the kernel's OOM killer (out-of-memory killer) steps in and terminates the process using the most memory, which is often the database.

Swap is not a substitute for RAM. Even on an SSD, disk access is many times slower than RAM; a server that swaps constantly keeps running but slows down noticeably. Think of swap as a buffer against sudden memory spikes and as a margin that buys you time to notice the problem.

## Check the current state

The operating system template you use may already have swap configured, so check before adding more:

```
swapon --show
free -h
cat /proc/swaps
# File system type of the root file system (ext4, xfs, btrfs)
findmnt -no FSTYPE /
df -h /
```

If `swapon --show` returns nothing and the Swap line in the `free -h` output shows 0, the server has no swap. Take your disk space into account as well: a swap file takes up real space on disk, and on a small disk 2 GB is a noticeable share.

## Creating a swap file

On virtual servers, a swap file is more flexible than a separate partition: you can resize it later or remove it when needed. For ext4 and XFS, the steps are:

```
sudo fallocate -l 2G /swapfile
# If fallocate fails, create the file with dd instead:
# sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
# Add it to fstab so it stays active after a reboot
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
# Test the fstab line right away
sudo swapoff /swapfile && sudo swapon -a
swapon --show
```

`chmod 600` matters: the swap file can contain data moved out of memory, passwords included, and only root should be able to read it. On some file systems `fallocate` can produce a file that counts as sparse; if `swapon` reports "swapfile has holes", delete the file and create it again with `dd`. The last two commands check now that the fstab line will be read correctly at the next boot.

### If you use btrfs

Because btrfs uses copy-on-write, an ordinary file cannot be used as swap. The `mkswapfile` command in btrfs-progs 6.1 and later creates the file with the right attributes. A btrfs subvolume that contains an active swap file cannot be snapshotted, so keep the file in a separate subvolume:

```
sudo btrfs subvolume create /swap
sudo btrfs filesystem mkswapfile --size 2G /swap/swapfile
sudo swapon /swap/swapfile
echo '/swap/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
```

## How much swap should you set aside?

| RAM | Recommended swap | Note |
| --- | --- | --- |
| 1–2 GB | Same as RAM (1–2 GB) | Small packages benefit most from a buffer against sudden spikes |
| 4 GB | 2 GB | Enough of a buffer for servers running both web and database |
| 8 GB | 2–4 GB | With correct memory settings, swap is rarely used |
| 16 GB or more | 4 GB | A larger swap usually only prolongs the slowdown |

Servers do not use hibernation, so the old "twice the RAM" rule does not apply.

## swappiness and vfs_cache_pressure

`vm.swappiness` (0–200, default 60) sets how willing the kernel is to swap under memory pressure. On servers, a low value such as 10 makes the kernel drop the file cache first and keep application memory in RAM. `vm.vfs_cache_pressure` (default 100) sets how quickly the directory and inode caches are reclaimed; 50 keeps these caches longer.

```
# Apply immediately (lost on reboot)
sudo sysctl vm.swappiness=10
# Make it permanent
printf 'vm.swappiness=10\nvm.vfs_cache_pressure=50\n' | sudo tee /etc/sysctl.d/99-swap.conf
sudo sysctl --system
sysctl vm.swappiness vm.vfs_cache_pressure
```

## Detecting OOM events

If a service stopped on its own, the kernel log is the first place to look:

```
sudo journalctl -k | grep -i -E 'out of memory|oom-kill'
sudo dmesg -T | grep -i -E 'out of memory|oom'
# Entries from the previous boot (if the journal is persistent)
sudo journalctl -k -b -1 | grep -i 'out of memory'
```

An entry looks like `Out of memory: Killed process 812 (mariadbd) total-vm:...` and shows the name of the killed process and its memory use at that moment. The killed process is not always the culprit: the kernel picks the process holding the most memory, while a different service may be the one bloating memory. Look at the process table just above the entry and at the `sar -r` history (see the [resource monitoring guide](https://www.hostimor.com/en/knowledgebase/article/linux-server-resource-monitoring-steal-time)). The phrase `Memory cgroup out of memory`, on the other hand, means that a memory limit defined for a service or container was exceeded, not the server's memory.

## Fix the root cause: memory settings for your services

Swap buys you time; the lasting fix is to make the services' total memory needs fit in RAM.

### PHP-FPM: pm.max_children

Each PHP-FPM child process uses its own memory, and `pm.max_children` is the upper limit on how many can run at once. The calculation is simple: the memory you can give PHP ÷ the average memory per process. Measure the average while there is traffic; a value measured at idle comes out too low.

```
# On Debian/Ubuntu the process name is php-fpmX.Y; store the version in a variable (or: ls /run/php/)
PHPV=$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;')
ps --no-headers -o rss -C "php-fpm$PHPV" | awk '{s+=$1; n++} END {printf "%d processes, average %.0f MB\n", n, s/n/1024}'
# On AlmaLinux the process name is php-fpm
ps --no-headers -o rss -C php-fpm | awk '{s+=$1; n++} END {printf "%d processes, average %.0f MB\n", n, s/n/1024}'
```

For example, on a server with 4 GB of RAM, if you reserve 1.5 GB for the operating system and MariaDB, about 2.5 GB is left for PHP; if you measured 60 MB per process, `pm.max_children = 40` is a reasonable upper limit. Change the value in the pool file (Debian/Ubuntu: `/etc/php/X.Y/fpm/pool.d/www.conf`, AlmaLinux: `/etc/php-fpm.d/www.conf`) and restart PHP-FPM. When the limit is reached, the PHP-FPM log shows the warning "server reached pm.max_children setting"; instead of the server crashing, new requests wait briefly in the queue.

### MariaDB/MySQL: innodb_buffer_pool_size

The InnoDB buffer pool is the database's largest memory item. A good starting point is 50–70% of RAM on a server that runs only the database, and 25–40% when the web server and the database share the same server.

```
sudo mariadb -e "SELECT ROUND(@@innodb_buffer_pool_size/1024/1024) AS MB;"
```

Set the new value in a separate configuration file:

```
# Debian/Ubuntu: /etc/mysql/mariadb.conf.d/60-tuning.cnf
# AlmaLinux: /etc/my.cnf.d/tuning.cnf
[mysqld]
innodb_buffer_pool_size = 1G
```

After saving the file, restart the service with `sudo systemctl restart mariadb` and confirm the new value with the first command.

### Java and Node.js

For Java applications, set the heap limit explicitly with `-Xmx` (for example `-Xmx1g`); otherwise the JVM picks a share of RAM on its own (usually a quarter). For Node.js, `NODE_OPTIONS=--max-old-space-size=512` (in MB) sets a similar limit. In both cases the process uses somewhat more memory in total than this limit, so leave headroom in your calculation.

### Limiting a service's memory with systemd

To contain a service that leaks memory or grows out of control without affecting the whole server, use systemd's `MemoryMax` setting:

```
sudo systemctl edit myapp.service
```

Add these lines in the editor that opens:

```
[Service]
MemoryHigh=900M
MemoryMax=1G
Restart=on-failure
```

Then restart the service and confirm that the limit is in place:

```
sudo systemctl restart myapp.service
systemctl show myapp.service -p MemoryHigh -p MemoryMax
systemctl status myapp.service
```

`systemctl edit` saves the settings you type between the comment lines in the editor to `/etc/systemd/system/myapp.service.d/override.conf` and reloads the systemd configuration by itself. When `MemoryHigh` is exceeded, the service is throttled and part of its memory is reclaimed; `MemoryMax` is a hard limit, and when it is exceeded only that service's processes are killed. Thanks to `Restart=on-failure`, the service then starts again on its own.

## Removing or resizing swap

To remove or resize the swap file, first turn it off and delete its fstab line:

```
# First check with free -h that the data in swap will fit in RAM
sudo swapoff /swapfile
sudo sed -i '\|^/swapfile |d' /etc/fstab
sudo rm /swapfile
```

`swapoff` moves the data in swap back into RAM; if there is not enough RAM, an OOM event can occur during this step. To resize, follow these steps and then create the file again with the new size.

> ****When should you upgrade RAM?****
> 
> If the si/so values in the `vmstat 1` output stay above zero for most of the day even after you have fixed the memory settings, your workload does not fit in the current RAM. Constant swap use is a sign that you need more RAM; you can grow your package with the steps in the [resource upgrade guide](https://www.hostimor.com/en/knowledgebase/article/resource-upgrade-cpu-ram-disk).

## Frequently asked questions

### Why do I still get OOM errors when I have swap?

There are three likely reasons: the swap is full too (check with `free -h`), memory was consumed faster than the kernel could write to swap, or the limit that was hit is not the server's but the memory limit of a service or Docker container. In the last case, you will see `Memory cgroup out of memory` in the log; the fix is to review that service's limit or its memory use.

### Does turning swap off completely improve performance?

Usually not. Without swap, the kernel has to keep even long-untouched memory pages in RAM, and under memory pressure the OOM killer steps in sooner. A small swap area with low swappiness is a better balance for most servers.

### Does swapping wear out the SSD?

Occasional swap writes add a negligible load. Constant, heavy swapping is a performance problem first; in that case, limit the service that consumes the memory or add more RAM.

## Related articles

- [Resource monitoring and steal time on a Linux server](https://www.hostimor.com/en/knowledgebase/article/linux-server-resource-monitoring-steal-time)
- [Upgrading CPU, RAM and disk resources](https://www.hostimor.com/en/knowledgebase/article/resource-upgrade-cpu-ram-disk)
- [Installing Nginx, PHP-FPM and MariaDB on Ubuntu](https://www.hostimor.com/en/knowledgebase/article/install-lemp-nginx-php-fpm-mariadb-ubuntu)
- [Disk full: freeing up space](https://www.hostimor.com/en/knowledgebase/article/disk-full-freeing-up-space)
- [Choosing CPU, RAM and SSD for a virtual server](https://www.hostimor.com/en/how-to-choose-cpu-ram-and-ssd-resources-for-a-virtual-server)
