Adding Swap Space to a Node
You might wonder why swap is even needed, because this isn’t enabled by default on any node in AWS or on any other cloud provider. The most likely reasons are the added complexity and the risk of wasting storage. And with instances now available with 200+ GB of RAM, why would anyone still need swap?
Swap space can be a sensible option for small nodes with 1-2 GB of memory, such as t2.micro, but because of the performance penalty, this is not suitable for production workloads. For experiments, dev testing, or QA, though, small instances are a cost-effective choice for most use cases (t2.micro is even free within certain limits during the first year).
Note: If you add swap to an EBS-backed node in AWS, keep the EBS storage limitations in mind.
A few commands are enough to add swap (1 GB in this example):
# dd if=/dev/zero of=/swapfile bs=1024 count=1048576
# mkswap /swapfile
# swapon /swapfile
# echo -e "/swapfile\t\tswap\t\t\tswap\tdefaults\t0 0" >> /etc/fstab
These commands create a 1 GB file in the root directory, format it as swap, tell the kernel to use it, and register it in /etc/fstab so it is enabled on every boot.
Creating the swap space may not be the whole job. You may also want to adjust the “swappiness” behavior, which controls when memory pages get moved to swap to free up RAM for running applications. This is governed by the kernel parameter /proc/sys/vm/swappiness.
This parameter holds a number that represents the minimum amount of free memory the kernel tries to preserve before it starts swapping out pages. For example, a value of 10 means no pages are swapped until free memory falls below 10%. From the console you can set it with sysctl:
# sysctl vm.swappiness=10
To make this setting survive reboots, add it to the system configuration:
# echo "vm.swappiness=10" >> /etc/sysctl.conf
Hope you found this useful. Have a nice day!