The t1.micro instance comes with only 602MB of memory. Especially under high load, it is quite easy to deplete the available memory – and since no swap space is enabled by default, this can quickly lead to a server becoming unresponsive. Swap space can also allow the kernel to move unused data out of memory, putting the main memory to better use. None the less, swap should not be seen as a replacement for memory, but rather an extension – a way to get a bit more out of the available memory.
Ideally, swap space would be allocated to an ephemeral volume, since the data does not need to persist, and there is no charge for I/O operations. However, since the t1.micro instance does not support ephemeral disks (and is, arguably, the instance most in need of swap space) we will look at setting up swap space on an EBS volume, below.
We start by creating an EBS volume – the smallest size is 1GB, which should be more than enough.
Attach the EBS volume to the instance – note the device you set it to (in my case,
Setup the swap area (the -f option is to force the command to proceed – omit it if you are unsure about the target):
mkswap -f /dev/xvdg
In order to have the swap space available after a boot, we edit
/etc/fstab, adding the line below:
/dev/xvdg swap swap defaults 0 0
Finally, we can turn on swap (without a reboot), but issuing the command below.
You can verify that the swap space is active with the ‘free’ command. As an example, the output below is from one of my t1.micro instances that has been running for 15 days. The last line shows swap (1GB), and a few (20) megabytes have been used.
free -m total used free shared buffers cached Mem: 602 576 25 0 48 347 -/+ buffers/cache: 181 421 Swap: 1023 20 1003
You can disable swap using the swapoff command, for example:
Keep in mind that if your swap space is being heavily used, it is probably affecting the performance of your application significantly. Also, with an EBS volume, you will be incurring a cost for every I/O operation. There is nothing wrong with swapping out pages, as long as it isn’t occuring frequently. You can configure the ‘swappiness’ of your system, by echoing out a value from 0 to 100 into /proc/sys/vm/swappiness. Low numbers reduce the system’s tendency to swap. One view point is that the lower numbers increase perceived responsiveness for a desktop, but higher numbers allow memory to be best used on a server environment.