EMZETT.
Login

Swap and memory on Linux: free, top and zram

In short: Linux uses free memory as cache and moves rarely used data into swap when needed; with free, top and vmstat you recognise real memory shortage, zram and a swapfile help.

In more detail: A frequent scare: free shows almost no free memory. That is normal, because Linux fills unused RAM with file cache (page cache), which it releases immediately when needed. What matters is available memory (available).

In Depth

Reading memory

free -h
#               total   used   free  shared  buff/cache  available
# Mem:            15Gi   4.2Gi  800Mi  300Mi   10Gi        10Gi
# Swap:          2.0Gi     0B   2.0Gi

available = what programs could get. With top/htop sort by RES (actually used); ps aux --sort=-%mem | head. vmstat 1 shows si/so (swap in/out): permanently high values mean memory shortage (thrashing). /proc/meminfo and smem give details.

Swap

Swap (partition or file) takes up rarely used pages so that RAM remains for active data, and enables hibernation. Setting up as a file:

sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile && sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Swappiness (vm.swappiness, default 60) controls the tendency to swap out; 10 to 30 common for desktops. Swap on SSD slightly increases wear but is mostly uncritical.

zram and OOM

zram compresses swap in RAM (Fedora, Ubuntu variants, ChromeOS): fast, ideal for small computers/Raspberry Pi. If memory and swap are exhausted, the OOM killer steps in and terminates processes (message in journalctl -k: “Out of memory: Killed process”). Remedies: more RAM, find memory hogs (browser tabs, memory leaks), set limits (systemd-run -p MemoryMax=2G, cgroups, Docker --memory), earlyoom/systemd-oomd for gentle intervention.

Tips

  • Servers: better a small amount of swap than none; monitoring with alarm.
  • Databases tolerate swapping badly (never swap Redis).
  • VMs/containers: consider host memory and limits.
  • When buying/upgrading: more RAM often brings more than swap.
  • High buff/cache is no problem; echo 3 > /proc/sys/vm/drop_caches is rarely sensible.

See also: Memory management and OOM killer, Virtual memory and paging, Task Manager and processes, Raspberry Pi