Cyrus Stoller home about consulting

Adding a swapfile to your VPS

RevTilt is hosted on a 512MB droplet on Digital Ocean. The low amount of RAM is usually fine, given the traffic, but it’s become a problem during deployment. I wasn’t able to deploy without stopping my server first, which defeats the purpose of having setup zero downtime deployment. This is largely because the zero downtime deploys spin up two instances of the application side by side until Unicorn kills the old master process. Without adding a swapfile to my VPS, my deployments had been failing due to an inability to allocate enough memory. For a more detailed explanation of how this work you may want to checkout these blog posts and this presentation.

By adding a swapfile processes are no longer randomly terminated due to “out of memory” errors. Instead, the system just slows down as a whole while it waits for the I/O to disk. This is not a substitute for having the appropriate amount of RAM on your server. Paging is many orders of magnitude slower than using RAM. If your server has an SSD then it’s not quite as bad, but it’s still substationally worse than adding more RAM. This is meant to serve as an emergency fallback. In my case, I only make use of the swapfile when I deploy, which isn’t too often.

I like this technique because it lets me continue using zero downtime deployment in low memory environments. I’m not recommending you skimp on your server specs. It’s not worth it.

Ok, let’s get started.

$ sudo install -o root -g root -m 0600 /dev/null /swapfile

This creates an empty swapfile for your system to use. This is more concise than using:

$ sudo touch /swapfile
$ sudo chmod 0600 /swapfile

Next, you need to specify how big your swapfile is going to be.

$ sudo dd if=/dev/zero of=/swapfile bs=1k count=512k

This creates a swapfile that is 512 MB. You can adjust this to meet the needs of your system. Read this FAQ put together by Ubuntu to learn more about setting an appropriate file size.

Now, tell your Linux system about this file.

$ sudo mkswap /swapfile # make it a swap file
$ sudo swapon /swapfile # activate it
# $ sudo swapoff /swapfile # to deactivate it

We need to make sure that it will be available after reboot, so we add it to the filesystem.

$ echo "/swapfile swap swap auto 0 0" | sudo tee -a /etc/fstab

In the fstab, you specify: device name, mount point, fs-type, options, dump-freq, and pass-num.

And lastly, tell your system to use this swapfile as a last resort by setting the swappiness.

$ sudo sysctl -w vm.swappiness=10
$ echo vm.swappiness = 10 | sudo tee -a /etc/sysctl.conf

If you want to keep your /etc/sysctl.conf clean you can create a new file in /etc/sysctl.d named /etc/sysctl.d/10-swapfile.conf. For more discussion about how to use this technique when setting up a system like Discourse check out this thread.

Category Tutorial