Skip to content

Set up zram compressed swap on a memory-constrained Linux server

Learn how to set up zram, a compressed swap device kept in RAM, on a Linux server that is short on memory. This guide shows you how to size it, pick a compression algorithm, tune the kernel for it, and measure whether it actually helped.

This guide shows Linux admins how to set up zram, a compressed swap device, on a server that keeps running short on memory. Normal swap is disk space where the kernel parks memory it can’t keep in RAM, and every trip to disk costs milliseconds. zram keeps that swap in RAM instead and compresses each page (a 4 KiB block of memory), often to about a third of its size, so paging costs a little CPU rather than slow disk reads and writes. The catch is the arithmetic: every compressed page still uses real RAM, so a 16 GiB zram device on an 8 GiB server does not give you 24 GiB. You will create the device with zram-generator, a small systemd tool that sets it up at every boot, and start it at half of your RAM. Then you will choose between the lzo-rle and zstd compression algorithms, tune two kernel settings for RAM-backed swap, and read the real compression ratio to see whether it helped.

What you’ll accomplish

  • Create a persistent, correctly sized zram swap device with zram-generator and one config file.
  • Choose between lzo-rle and zstd depending on whether you have CPU to spare or RAM to save.
  • Layer zram above existing disk swap with priorities, so zram absorbs pressure first.
  • Set vm.swappiness and vm.page-cluster to suit a RAM-backed device, not a disk.
  • Read the real compression ratio from zramctl and mm_stat and decide from data.

Prerequisites

  • A kernel with the zram module available. Check with modinfo zram; it is a module on effectively every mainstream distribution kernel.
  • A systemd-based distribution — zram-generator is a systemd generator.
  • The package: apt install systemd-zram-generator on Debian and Ubuntu, dnf install zram-generator-defaults on Fedora and the RHEL family. Arch ships zram-generator.
  • root or sudo, and util-linux for zramctl (present by default).
  • Honest caveats. Older distributions still ship the shell-script approach — Debian’s zram-tools, with /etc/default/zramswap and a zramswap.service. It works, but install both and you get two services fighting over /dev/zram0; pick one. And this is a host-level change: a container or unprivileged LXC guest cannot load a kernel module or create a block device, so zram belongs on the host and guests inherit the effect.

How it works

zram creates a block device — /dev/zram0 — whose storage is a pool of compressed pages in RAM. Once mkswap and swapon have run against it, the kernel treats it like any other swap device, except that instead of writing a reclaimed 4 KiB page to a partition, the swap layer hands it to the zram driver, which compresses it into kernel memory. No block I/O is involved.

That changes the economics. Disk swap trades latency for RAM: 100 µs to 10 ms per page, and you get the full 4 KiB back. zram trades CPU for RAM: a few microseconds per page, and you get back only the difference between the original page and its compressed form. A page that compresses 3:1 nets about 2.7 KiB; a page that does not compress nets nothing, and you paid CPU for it.

Flow diagram showing a reclaimed anonymous page routed by swap priority either to the zram path where it is compressed and stored in a RAM pool, or to the disk swap path where it is written to a partition, with the compression ratio and CPU cost annotated on the zram branch and the disk latency cost on the other

Priority makes the two coexist. Every swap device has one, visible in the PRIO column of swapon --show, and the kernel fills higher-priority devices first. Give zram 100 and your disk swap 10: pressure lands in zram until it is exhausted, then spills to disk. Fast tier first, slow tier as an overflow valve.

The numbers that matter are in zramctl. DISKSIZE is the advertised capacity — a number you chose, not memory that exists. DATA is the uncompressed size of what is stored, COMPR the compressed size of the same data, and TOTAL the RAM actually consumed, metadata and per-page allocator overhead included. DATA divided by COMPR is your real ratio; TOTAL is what you subtract from free memory.

Algorithm choice is the second lever. lzo-rle is the kernel default on most builds: very fast, modest ratio, optimised for runs of zeros (common in freshly allocated heap). zstd compresses considerably better — often 20–40% smaller on real workloads — at meaningfully more CPU per page. With idle cores zstd is usually right; on a host already pinned at high CPU, lzo-rle or lz4 hurts less.

Writeback is the escape hatch. zram can be given a real backing device (writeback-device in the config, or /sys/block/zram0/backing_dev) and told to push idle or incompressible pages out to it, freeing the RAM they occupied. It exists for the pages that make zram a bad deal, and it needs a dedicated block device.

Step-by-step

  1. Inspect what you have now. You need real RAM, real free memory, and any existing swap before changing anything.

    free -h
    swapon --show

    Expected: free -h prints Mem: with total and available, plus a Swap: row. swapon --show lists devices with NAME TYPE SIZE USED PRIO, or nothing if no swap exists. Note available — you compare against it later.

  2. Confirm the module and the available algorithms. Load zram once by hand to read which compressors this kernel offers.

    sudo modprobe zram
    cat /sys/block/zram0/comp_algorithm

    Expected: something like lzo lzo-rle lz4 lz4hc 842 [zstd], where the bracketed entry is the current default. If zstd is absent, do not put it in the config — the service will fail to start.

  3. Install zram-generator. Use whichever line matches your distribution.

    sudo apt install systemd-zram-generator
    sudo dnf install zram-generator-defaults

    Expected: a generator appears at /usr/lib/systemd/system-generators/zram-generator. On Fedora a default config also lands at /usr/lib/systemd/zram-generator.conf — leave it alone and override from /etc/.

  4. Write the config. The generator reads /etc/systemd/zram-generator.conf, one section per device, named after the device. zram-size is an expression in megabytes where ram is total RAM, so min(ram / 2, 4096) means “half of RAM, capped at 4 GiB”.

    sudo tee /etc/systemd/zram-generator.conf >/dev/null <<'EOF'
    [zram0]
    # half of RAM, never more than 4 GiB
    zram-size = min(ram / 2, 4096)
    compression-algorithm = zstd
    swap-priority = 100
    fs-type = swap
    EOF

    Expected: cat /etc/systemd/zram-generator.conf shows exactly those lines. Start at half of RAM. A device equal to RAM is defensible once you have measured a ratio above 3:1; larger than RAM is a bet that you never fill it, and losing it means the compressed pool eats the RAM it was meant to save.

  5. Reload and start the unit. The generator runs during daemon-reload and synthesises systemd-zram-setup@zram0.service from your config.

    sudo systemctl daemon-reload
    sudo systemctl start systemd-zram-setup@zram0.service

    Expected: both commands return silently, and systemctl status systemd-zram-setup@zram0.service shows Active: active (exited). The unit is a one-shot that configures the device and finishes, so exited is success.

  6. Verify the device and the swap entry. These two commands are the proof.

    zramctl
    swapon --show

    Expected output on an 8 GiB host:

    NAME       ALGORITHM DISKSIZE DATA COMPR TOTAL STREAMS MOUNTPOINT
    /dev/zram0 zstd            4G   4K   64B   12K       8 [SWAP]
    NAME       TYPE      SIZE USED PRIO
    /dev/zram0 partition   4G   0B  100
    /swapfile  file        4G   0B   -2

    PRIO 100 on zram is what you were after; a negative priority is what the kernel assigns when nothing was specified.

  7. Tune the vm knobs for an in-RAM device. Two changes matter. Swapping is now cheap, so the usual advice to keep vm.swappiness low is inverted — you want the kernel to prefer compressing anonymous pages over evicting page cache it would re-read from disk. And swap readahead is pointless: with no seek to amortise, pulling in neighbouring pages just wastes CPU decompressing pages nobody asked for. vm.page-cluster=0 reads one page per fault.

    sudo tee /etc/sysctl.d/99-zram.conf >/dev/null <<'EOF'
    # in-RAM swap is cheap, so bias reclaim towards it
    vm.swappiness = 180
    # no seek to amortise, so no swap readahead
    vm.page-cluster = 0
    EOF
    sudo sysctl --system

    Expected: sysctl --system prints the files it read, including * Applying /etc/sysctl.d/99-zram.conf ..., then echoes vm.swappiness = 180 and vm.page-cluster = 0. If you see sysctl: setting key "vm.swappiness": Invalid argument, your kernel is older than 5.8 and caps swappiness at 100 — use 100. Leave vm.vfs_cache_pressure at 100 unless you have separately measured that dentry and inode cache is what crowds you out; it is unrelated to zram. Our guide to swappiness covers what that dial does and does not control.

  8. Demote existing disk swap. If a disk swap file or partition is already active, give it an explicit low priority so it is only ever an overflow tier: add pri=10 to the options field of its /etc/fstab line.

    sudo sed -i 's|^/swapfile none swap sw |/swapfile none swap sw,pri=10 |' /etc/fstab
    sudo swapoff /swapfile && sudo swapon -a
    swapon --show

    Expected: the /swapfile row now shows PRIO 10 while zram stays at 100. If your fstab line differs, edit it by hand rather than trusting the sed.

  9. Make it survive a reboot. There is nothing to enable. The generator runs on every boot, re-reads your config, synthesises the unit under /run/systemd/generator/ and wires it into swap.target itself — systemctl enable on it fails with Unit ... is transient or generated. The config file is the persistence. Confirm by rebooting.

    sudo reboot

    Once the box is back:

    zramctl && swapon --show && sysctl vm.swappiness vm.page-cluster

    Expected: /dev/zram0 is present with PRIO 100, and both sysctls report the values you set. If zram is missing, re-check the config file path first.

Validate it works

Setup is not evidence. Put the box under bounded pressure with an explicit byte count, not a percentage, so you cannot accidentally invoke the OOM killer:

sudo apt install stress-ng
stress-ng --vm 2 --vm-bytes 1500M --vm-keep --timeout 60s --metrics-brief

Expected: stress-ng prints a successful run completed line after 60 seconds. While it runs, in a second shell:

watch -n 2 zramctl

Expected: DATA climbs into the hundreds of megabytes and COMPR stays well below it. Divide DATA by COMPR for your real ratio — DATA 900M against COMPR 260M is about 3.4:1, a good deal. If the two columns are within 10% of each other, your pages are not compressible and zram is buying almost nothing.

Confirm the traffic is served by zram and not the disk:

vmstat 1 10

Expected: si and so show sustained non-zero values while stress-ng runs. Cross-check with iostat -x 1 in another shell: the device holding your disk swap should stay near-idle. Non-zero si/so plus a quiet disk means zram is absorbing the pressure; a busy swap device means the priorities are wrong. Our iostat walkthrough covers those columns.

Finally read the raw counters, more precise than the rounded zramctl display:

cat /sys/block/zram0/mm_stat

Expected: one line of whitespace-separated integers — orig_data_size, compr_data_size, mem_used_total (bytes), then mem_limit, mem_used_max, same_pages (all-identical-byte pages stored as one reference), and later fields counting huge_pages: pages that could not be compressed and are stored whole. A large huge_pages value means this workload is a poor fit.

The comparison that settles it: run your real workload with zram enabled, then stopped (sudo systemctl stop systemd-zram-setup@zram0.service && sudo swapoff /dev/zram0), and compare the metric you care about — p99 latency, batch wall-clock — not the memory numbers.

Troubleshooting

  • The device never comes up. Three causes. Wrong config path — the generator reads /etc/systemd/zram-generator.conf, not /etc/zram-generator.conf. A malformed zram-size: the expression language accepts ram, arithmetic and min()/max(), in megabytes, so a bare 4G is invalid. Or a missing algorithm — a kernel built without CONFIG_ZRAM_BACKEND_ZSTD (or the older CONFIG_CRYPTO_ZSTD) offers no zstd. journalctl -u systemd-zram-setup@zram0.service names which.
  • The box got slower, not faster. If zramctl shows TOTAL approaching a large share of RAM, you sized the device past what the machine can back and the compressed pool now competes with the workload for memory — halve zram-size and restart the unit. If TOTAL is modest but CPU is pegged, compression is the bottleneck: check per-core usage with mpstat -P ALL 1 under pressure and switch compression-algorithm to lzo-rle.
  • zramctl shows a huge TOTAL relative to DATA. The stored pages are incompressible. Already-compressed content — JPEG buffers, gzipped payloads, encrypted data — does not shrink, and zram stores those whole plus per-page metadata, so TOTAL can exceed DATA. Confirm with huge_pages in mm_stat. Either accept a smaller device, or configure a writeback-device so those pages go to real storage instead of squatting in RAM.
  • The OOM killer still fires. Expected, and worth stating plainly: zram is not more memory. It buys the difference between compressed and uncompressed size, nothing more, and the compressed pool itself is unswappable kernel memory. If dmesg | grep -i oom shows kills, the machine needs more RAM or less resident memory.
  • The config disappears after a package upgrade. You edited the distribution’s file instead of your own. On Fedora, zram-generator-defaults owns /usr/lib/systemd/zram-generator.conf and will replace it. Local configuration belongs in /etc/systemd/zram-generator.conf, which the package never touches. Check ownership with rpm -qf or dpkg -S on the path you edited.

When this is the wrong approach

If the machine is short on RAM often enough that you are reading this, the cheapest fix is usually more RAM or a larger instance, weighed against the CPU you are about to spend forever. zram is at its best where you genuinely cannot add memory — small VPS instances, edge boxes, embedded appliances — or where pressure is bursty and rare and you only need the burst to be survivable.

Skip it on latency-sensitive services that cannot afford a compression pass in the fault path; a hard real-time control loop should not be swapping at all. Skip it on hosts already CPU-bound, where you trade the resource you are short of for the one you are less short of. On database hosts zram treats the symptom — if Postgres or MySQL is swapping, the honest fix is shrinking the working set or the buffer pool to fit RAM. Kubernetes nodes are their own case: node swap is off by default and needs the NodeSwap feature configured deliberately, so adding zram without kubelet swap support accomplishes nothing.

The authoritative references are the kernel’s zram documentation and the zram-generator README, which documents every config key including the writeback options this guide only sketches.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.