How to Setup ZRAM on RPi
After posting my article on Reddit about setting up Pi-Hole and PiVPN, I learned about ZRAM from fellow redditor u/Bubbagump210. I’m basing this article off of his post.
Zram allows one to create compressed RAM drives – including swap drives. So, what we will be going over below is running a swap drive under ZRAM. When regular RAM feels memory pressure, it shuffles data from regular RAM to the ZRAM swap – which is also actually RAM but compressed.
Open a terminal window or SSH into your RPi.
Make sure your RPi is up-to-date with the following commands:
sudo apt-get update
sudo apt-get upgrade
Install ZRAM by running the following command, and then typing ‘Y’ to proceed.
sudo apt install zram-tools
By default, this package will create a 256MB swap drive. If you want to bump that up a tad higher, then you will need to edit /etc/default/zramswap. Edit the file with the following line.
sudo nano /etc/default/zramswap
We will need to add the ‘Allocation’ variable. To increase your swap drive to 512MB, add the following line.
Press “Ctrl-X” to exit the editor, “Y” to confirm you want to save your changes, then “Enter” to save it.
Run the following two commands to enable and start ZRAM
sudo systemctl enable zramswap
sudo systemctl start zramswap
If you open top, you should now see your new swap space at the size allocated above.
How to check your compression ratio? Run the command below.
On this rpi, my output currently is:
790528 189901 507904 0 507904 18 0 2
The first value is the uncompressed data size, the second value is the compressed data size. (More details found here)
So a 76% reduction in size – not bad.
Certainly there is a tiny performance hit and buying more RAM is a technically better solution, but for fixed RAM cases like a Pi or free tier VM, this works.
Note, this initially didn’t work for me on Raspbian Stretch. I updated my RPi to Raspbian Buster and it worked just fine.