Linux · Systems fluency

How does swap work and when should you use it?

MediumswapmemoryzramUpdated Oct 2026
Quiz this track

Short answer

Swap moves less-used memory pages to disk so the kernel can use RAM for active work. It protects against sudden memory spikes but is not a substitute for enough memory, because swapping is orders of magnitude slower than RAM.

Swap can be a partition or a file. The kernel decides what to move based on pressure and swappiness. High swap-in and swap-out rates with slow response usually indicate memory pressure, while a small amount of swap usage can be normal.

sh
swapon --show
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

Operational considerations

  • Add the swapfile to fstab to persist it across reboots
  • vm.swappiness tunes the tendency to reclaim anonymous pages
  • zram provides compressed RAM-backed swap with low latency
  • Hibernation needs swap at least as large as memory and is often disabled in production
  • SSD write endurance matters for heavy swap, though modern drives tolerate far more writes

Monitor si and so in vmstat. Sustained swapping means the workload does not fit in memory. The correct response is usually to reduce the working set, add memory, or fix a leak rather than to enlarge swap indefinitely.

A swapfile on a filesystem that does not support sparse files or has restrictive mount options may fail to activate. Verify with swapon --show after configuration.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Does swap usage always mean the system is unhealthy?
  2. 2What does vm.swappiness control?
  3. 3When would you use zram instead of disk swap?
  4. 4How do you tell whether a system is actively swapping?

Say it in the interview

Swap lets the kernel move less-used pages out of RAM. It can absorb spikes, but sustained swapping is a sign the working set does not fit. I monitor swap-in and swap-out rather than just usage. The fix for persistent pressure is usually less memory demand or more RAM, not an ever-larger swapfile.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Linux mock interview and get scored feedback on depth, clarity and confidence.