Skip to content

Zram swap

Introduction

When creating a virtual machine you can utilize swapfile on a disk as a precaution in case the VM runs low on RAM. In such configuration Linux system will use disk space as extra RAM. However, this has an undesirable effect that when disk is used as RAM the whole system can slow down. Generally if your VM is using swap then it's a good indicator to increase RAM. But if you don't have a possibility to increase RAM, then a method to prevent system slow down is to use zram as swap. Zram in this case can be treated as swap partition kept in RAM that will contain compressed data. This compression has some small performance penalty but allows to utilize more RAM than VM physically have. This post will show how to create swap using zram.

OS used: Debian 12
Software used: zram-tools 0.3.3.1

Zram installation

First install package with zram utilities:

$ sudo apt install zram-tools

Zram status

List all swap partitions:

$ cat /proc/swaps

Filename          Type            Size            Used        Priority
/dev/zram0        partition       8118268         0           100

Check zram status:

$ sudo zramctl

NAME       ALGORITHM DISKSIZE  DATA  COMPR  TOTAL STREAMS MOUNTPOINT
/dev/zram0 lz4             8G  1.9G 318.6M 424.9M      16 [SWAP]
  • DISKSIZE = 8G - this zram device will store up to 8 GiB of uncompressed data.
  • DATA = 1.9G - 1.9 GiB (uncompressed) of data is being stored in this zram device
  • COMPR = 318.6M - the 1.9 GiB uncompressed data was compressed to 318.6 MiB
  • TOTAL = 424.9M - total used space including metadata, the 1.9 GiB of uncompressed data is using up 424.9 MiB of physical RAM

Zram configuration

By default zram in Debian 12 uses 256MB. I prefer to set 512MB for my VM's.

Edit SIZE value in the following file to increase zram:

$ sudo vim /etc/default/zramswap
/etc/default/zramswap
(...)
SIZE=512
(...)

After editing reboot the system.

Next check if new swap size was set correctly using following command:

$ sudo swapon --show

Bonus - Disabling swapfile

If your system has already created swapfile you can disable it using following procedure:

  • Comment or delete entries regarding swap in /etc/fstab
  • Disable swap:
    $ sudo swapoff /swapfile
    
    /swapfile - path to swapfile
  • Reboot system
  • List all swap partitions:
    $ cat /proc/swaps