SWAP (swap) is a virtual memory mechanism that moves some data from RAM to HDD (hard disk drive), SSD (solid-state drive) storage

In Linux the RAM (random access memory) is divided into sections called pages. Swapping is a process whereby pages of memory are copied to a specially configured disk partition, called swap space (swap partition, can be a file or a hard disk partition), to free up RAM. The combined size of the physical memory and swap partition is the amount of virtual memory available.

Swapping is necessary for the following reasons:

  • when the system needs more memory (i.e. an application or process asks the system for more memory) than there is free RAM, the kernel offloads ("swaps out") the least used pages and allocates the freed memory to the current application or process
  • A significant number of pages used by programs at startup are used only during initialization and never again. Accordingly, the system can swap out these pages, thus freeing (unloading) RAM.

Disadvantages of SWAP:

  • Compared to RAM, the hard disk is much slower. To estimate read/write times, RAM uses nanoseconds, while hard disk uses milliseconds, i.e. the same operations on a hard disk take tens of thousands more time than on RAM. Consequently, the more pages swapped, the slower your system runs.

Often, it is the database which suffers first from the lack of free memory. You may encounter problems like:

  • Constant site crash: Database connection error - means, for example, that MySQL has crashed;
  • Examining the /var/log/mysql.log reveals the error InnoDB: Fatal error: cannot allocate memory for the buffer pool. It indicates that the database does not have enough memory allocated to it to create a buffer.

If the file or swap partition is stored on SSD you should understand that searching and reading data is done through RAM which in its turn increases the response time

Therefore, if you are facing a RAM shortage, we recommend upgrade to a higher plan.

Checking for swap availability on your system:

swapon -s  
Filename Type Size Used Priority  
/swapfile file 40956 40956 -1

Check additionally with the command:

free -m  
              total used free shared buff/cache available
Mem: 488 160 7 40 320 259  
Swap: 39 39 0  

We see that the SWAP is ready and will be used if needed.

In case of absence, you can create a file for swap

dd if=/dev/zero of=/swap.file bs=1M count=512  

This command will create a /swap.file of 512 megabytes. To increase this size, change count

Set permissions on it so that no one can read or write to the file except the owner, root

chmod 600 /swap.file  

Format the file to swap

mkswap /swap.file  

Edit the /etc/fstab file

To make swap available at boot time, add it to /etc/fstab

Add line

/swap.file swap swap defaults 0 0

Then you can reboot the server and check for swap with free -m

Updated Dec. 28, 2018