Setting Up zram on Raspberry Pi

Setting up zram on Raspberry Pi

The Five-Minute Fix That Keeps Swap Off Your SD Card

Setting up zram on Raspberry Pi is the fastest single change you can make to reduce SD card wear and improve system stability under memory pressure. It takes about five minutes, survives reboots, and works on every Pi model from the Zero 2 W to the Pi 5. I’m sure a lot of you have watched a Pi grind to a halt during a memory spike and wondered why something that “wasn’t doing much” suddenly became unresponsive. Nine times out of ten, swap is hitting the SD card. zram fixes that.

By default, Raspberry Pi OS creates a 100MB swapfile on the SD card. When RAM fills up, the kernel starts writing pages to that swapfile. SD cards handle sequential writes reasonably well, but random I/O – which is what swap looks like from the storage controller’s perspective – is where they fall apart. The result is sluggishness, write wear, and in worst-case scenarios, the kind of interrupted write that leaves the filesystem in an inconsistent state.

zram sidesteps all of that by creating a compressed swap device in RAM itself. No flash writes. No I/O bottleneck. Compressed data stored in memory, decompressed on demand.

Key Takeaways

  • zram creates a compressed swap space in RAM, eliminating SD card swap writes entirely
  • zram-tools is the easiest installation method on Raspberry Pi OS Bookworm
  • lz4 compression is the right default for Pi – fastest decompression, lowest CPU overhead
  • 50% of RAM is a safe starting size for most workloads
  • Disable dphys-swapfile after enabling zram or both will run simultaneously
  • Kernel tuning parameters make zram significantly more effective

How zram Actually Works

Swap in RAM Sounds Contradictory – Here Is Why It Is Not

The confusion people run into is this: if RAM is full, how does storing swap in RAM help? All right, here is the thing. zram does not reserve a fixed chunk of RAM upfront and leave it sitting empty. It creates a compressed block device backed by RAM. When the kernel decides to swap a memory page, instead of writing it to a 100MB file on the SD card, it compresses the page and stores the compressed result in the zram device.

A typical memory page compresses to roughly one third of its original size using lz4. That means 1GB of zram capacity effectively holds around 3GB of uncompressed memory pages. The trade-off is CPU cycles spent on compression and decompression. On a Pi, that trade-off is almost always worth it – the CPU is nearly always faster than the SD card, so compression overhead is lower than the latency penalty of hitting flash storage.

The practical result is a system that handles memory pressure gracefully instead of locking up while the kernel hammers the SD card with swap I/O.

Who Benefits Most From zram

zram is useful on every Pi, but the benefit scales with how tight RAM is relative to workload. Systems that benefit most include:

  • Pi Zero 2 W and Pi 3 with 512MB or 1GB RAM running multiple services
  • Pi 4 with 1GB or 2GB RAM running a desktop environment or Node.js applications
  • Any headless Pi running services that experience periodic memory spikes such as package updates, cron jobs, and log rotation
  • Any Pi running from SD card where swap writes are directly causing wear

Pi 4 and Pi 5 with 4GB or 8GB RAM running light workloads will see less dramatic improvement, but the SD card wear reduction still applies. Even an idle system with plenty of RAM can have the kernel push a few pages to swap during memory reclaim. Those writes add up over weeks of uptime.

Before You Start

Check Your Current Swap Setup

Before installing zram, see what swap is currently doing on your system:

# Show current swap devices and usage
cat /proc/swaps

# Show RAM and swap totals
free -h

On a fresh Raspberry Pi OS Bookworm install you will typically see one entry: a file-based swap at /var/swap, 100MB, managed by dphys-swapfile. That is the one you are replacing.

Update the system before proceeding:

sudo apt update && sudo apt full-upgrade -y

Installing zram with zram-tools

The Recommended Method for Raspberry Pi OS Bookworm

zram-tools is available directly from the Raspberry Pi OS package repository and is the most straightforward installation method. It handles kernel module loading, device creation, and systemd service setup automatically.

sudo apt install zram-tools -y

Once installed, open the configuration file:

sudo nano /etc/default/zramswap

The default file is heavily commented. The key settings to configure are:

# Compression algorithm
# lz4 = fastest, lowest CPU overhead - recommended for all Pi models
# zstd = better compression ratio, slightly more CPU - good for Pi 4/5 with 4GB+
ALGO=lz4

# Size as percentage of total RAM (takes priority over SIZE)
# 50% is a safe default for most workloads
PERCENT=50

# Swap priority - higher number = used before lower-priority swap
# Set high so zram is always preferred over any disk-based swap
PRIORITY=100

Save and exit, then enable and start the service:

sudo systemctl enable zramswap
sudo systemctl start zramswap

Choosing the Right Size

PERCENT=50 is the right starting point for most setups. Because lz4 achieves roughly 3:1 compression on typical workloads, 50% of RAM as zram capacity effectively gives you 1.5x your physical RAM in usable virtual memory before anything hits storage. For a 1GB Pi, that is 512MB of zram that can hold approximately 1.5GB of compressed pages. For a 4GB Pi, 2GB of zram covers most realistic memory pressure scenarios.

ModelRAMRecommended PERCENTEffective capacity
Pi Zero 2 W512MB75~1.1GB
Pi 3 B / B+1GB50~1.5GB
Pi 4 (1GB)1GB50~1.5GB
Pi 4 (2GB)2GB50~3GB
Pi 4 / 5 (4GB+)4GB+25-50~3-6GB

Disabling the Default Swapfile

This Step Is Not Optional

Installing zram does not automatically disable the existing dphys-swapfile swap. If you skip this step, both will run simultaneously. The kernel will use zram first due to its higher priority, but dphys-swapfile remains active and will still write to the SD card under extreme memory pressure or during certain kernel memory reclaim operations.

# Turn off the current swapfile immediately
sudo dphys-swapfile swapoff

# Disable the service from starting on boot
sudo systemctl disable dphys-swapfile

# Stop the service
sudo systemctl stop dphys-swapfile

After disabling dphys-swapfile, the /var/swap file remains on disk but is no longer used. You can delete it to reclaim the space: sudo rm /var/swap

Kernel Tuning Parameters

Making zram Significantly More Effective

zram installed with default kernel parameters works, but it does not work as well as it should. The default kernel swap settings were tuned for systems with disk-backed swap, not compressed RAM swap. A few sysctl changes tell the kernel to treat swap more aggressively – which is exactly what you want when swap is fast and lives in RAM rather than on a slow SD card.

Open the sysctl config:

sudo nano /etc/sysctl.d/99-zram.conf

Add these lines:

vm.swappiness=100
vm.vfs_cache_pressure=500
vm.dirty_background_ratio=1
vm.dirty_ratio=50
vm.watermark_boost_factor=0
vm.watermark_scale_factor=125
vm.page-cluster=0

Apply immediately without rebooting:

sudo sysctl -system
ParameterValueEffect
vm.swappiness100Kernel swaps aggressively – correct when swap is fast RAM-based zram
vm.vfs_cache_pressure500Reclaims filesystem cache more readily, freeing RAM for active processes
vm.dirty_background_ratio1Starts writing dirty pages at 1% – keeps write bursts small and frequent
vm.dirty_ratio50Forces synchronous writes only at 50% dirty – prevents sudden large flushes
vm.watermark_boost_factor0Disables memory watermark boost – reduces unnecessary reclaim activity
vm.watermark_scale_factor125Earlier memory reclaim before pressure becomes critical
vm.page-cluster0Swap one page at a time rather than in clusters – optimal for zram

vm.swappiness=100 sounds alarming if you are used to the conventional advice of setting it low. That advice applies to disk swap. With zram, high swappiness is correct – swapping to compressed RAM is fast and does not wear anything out.

Verifying zram Is Working

Confirm the Setup Before Declaring Victory

After enabling zram and disabling dphys-swapfile, verify the configuration is correct:

# Check active swap devices - should show only /dev/zram0, not /var/swap
cat /proc/swaps

# Show zram device details including compression ratio
zramctl

# Show overall RAM and swap totals
free -h

The output of cat /proc/swaps should look like this, with no /var/swap entry:

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

The output of zramctl after the system has been running under some load shows the compression ratio in action:

NAME       ALGORITHM DISKSIZE  DATA  COMPR  TOTAL STREAMS MOUNTPOINT
/dev/zram0 lz4            2G  432M  165M   173M       4 [SWAP]

That output shows 432MB of memory pages compressed down to 165MB – a 2.6:1 ratio. The system is effectively using 432MB of virtual swap while only consuming 173MB of actual RAM for the zram device.

Check the Service Is Enabled for Boot

# Confirm zramswap starts on boot
sudo systemctl is-enabled zramswap

# Confirm dphys-swapfile does not start on boot
sudo systemctl is-enabled dphys-swapfile

You want to see enabled for zramswap and disabled for dphys-swapfile. If either is wrong, revisit the enable and disable commands above.

Choosing a Compression Algorithm

lz4 vs zstd – Which Is Right for Your Pi

lz4 is the right default for every Pi. It decompresses extremely fast with minimal CPU overhead. On single-core or low-clock-speed Pis such as the Zero 2 W and Pi 3, lz4 is the only sensible choice. Compression ratio is typically 2.5:1 to 3:1 on real workloads.

zstd achieves better compression – typically 3:1 to 4:1 – at the cost of more CPU during compression. On a Pi 4 or Pi 5 with 4GB or more RAM and a workload that compresses well such as web servers and lightweight databases, zstd can be worth testing. Run with lz4 first and only switch if you are running into memory limits that zstd’s better ratio would address.

To check which algorithms your kernel supports and switch if needed:

# See available algorithms (active one shown in brackets)
cat /sys/block/zram0/comp_algorithm

# After changing ALGO= in /etc/default/zramswap, apply it:
sudo systemctl restart zramswap

Troubleshooting

zramswap service fails to start

sudo systemctl status zramswap
journalctl -u zramswap -no-pager

The most common cause is the zram kernel module not loading. Check if it is available:

sudo modprobe zram
lsmod | grep zram

If modprobe fails, run sudo apt full-upgrade to ensure you have the latest kernel, then reboot and try again.

Both zram and /var/swap are showing in /proc/swaps

dphys-swapfile was not fully disabled. Run through the disable steps again and confirm with sudo systemctl is-enabled dphys-swapfile. Reboot to clear any state from a previous boot cycle.

zramctl shows no compression – DATA and COMPR are equal

Normal when the system has not yet used any swap. zram only compresses data when the kernel actually swaps pages into it. Put the system under realistic load and check again.

System still feels sluggish under memory pressure

Confirm the sysctl parameters applied correctly:

sysctl vm.swappiness
# Should return vm.swappiness = 100

If it returns 60 (the default), the parameters did not apply. Confirm the file is in /etc/sysctl.d/ with a .conf extension, then run sudo sysctl -system again.

Does zram Replace the Need for More RAM?

Honest answer: no, but it makes the RAM you have go significantly further. zram defers the point at which the system runs out of usable memory. It does not add physical RAM. If your workload consistently requires more memory than your Pi has, zram buys headroom but does not eliminate the underlying constraint.

Where zram genuinely removes the problem rather than delaying it: workloads with occasional memory spikes such as package updates, cron jobs, and startup sequences that would previously cause the kernel to thrash the SD card. With zram, those spikes are absorbed in compressed RAM and the SD card never sees them.

If zramctl consistently shows the zram device more than 80% full during normal operation, your workload has outgrown the available RAM. At that point the realistic options are a Pi model with more RAM, pruning services, or accepting that some swap will occasionally hit storage.

FAQ

Does zram work on all Raspberry Pi models?

Yes. The zram kernel module is included in all Raspberry Pi OS kernels from Bullseye onward, covering all 32-bit and 64-bit variants. It works on every Pi model from the Zero 2 W through the Pi 5.

Will zram slow down my Pi due to CPU overhead?

In most cases no. The CPU cost of lz4 compression is lower than the latency cost of reading and writing swap to an SD card. On heavily loaded single-core Pis the overhead is more noticeable, but even then the system is faster than it would be hitting SD card swap. Use htop to measure actual CPU impact on your specific workload if you are concerned.

Can I run zram alongside a disk swapfile as a fallback?

Yes. Set zram priority to 100 and disk swap to a lower number. The disk swap only activates if zram fills completely. This is reasonable for workloads where running completely out of virtual memory would be worse than occasional SD card writes.

Does zram help if I am already booting from USB SSD?

Yes, though the benefit is smaller. USB SSD swap is dramatically faster than SD card swap, so you are not taking the same write-latency hit. zram still reduces SSD wear and eliminates swap I/O entirely during memory spikes, keeping the system more responsive. The kernel tuning parameters are also worth applying regardless of swap backing device.

What happens to zram data during a reboot?

zram is volatile by design – its contents are lost on reboot, just like regular RAM. The systemd service recreates the zram device fresh on each boot. Any data that needs to survive a reboot should be on persistent storage, not in swap.

Should I use zram or zswap?

zram is the right choice for Raspberry Pi. zswap is a kernel feature that compresses swap pages in RAM as a cache in front of a disk-based swap partition – it still ultimately requires a disk swap backend. zram replaces disk swap entirely. On a Pi where the goal is to eliminate SD card writes, zram is the correct tool.

Next Steps

zram handles swap. For a complete write-reduction strategy across your Raspberry Pi setup:

References

Was this helpful?

Yes
No
Thanks for your feedback!