Ctrl K

EC2 Swap File Setup

Add a persistent swap file to a small EC2 instance so memory spikes degrade into a slowdown instead of a hard OOM freeze that kills SSH access.

Small EC2 instances (e.g. ~4 GB RAM) often ship with no swap at all. With zero swap, any memory spike past physical RAM triggers an instant OOM and the kernel can freeze hard - SSH and the app both go unreachable. A typical trigger is a deploy where several services cold-start and load into memory at the same time. A swap file turns that hard freeze into a survivable slowdown, so the box degrades gracefully instead of dying. This doc sets up a 4 GB swap file.

Add the swap file

One-time setup; persists across reboots via fstab.

# 1. allocate a 4 GB file
sudo fallocate -l 4G /swapfile

# 2. lock down permissions (root-only; swapon refuses a world-readable file)
sudo chmod 600 /swapfile

# 3. format it as swap
sudo mkswap /swapfile

# 4. enable it now
sudo swapon /swapfile

# 5. make it survive reboots (add to fstab)
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Verify

free -h        # Swap line should now show 4.0Gi total
swapon --show  # lists /swapfile, type file, size 4G

htop also shows the Swap bar once it is active.

Used = 0 is normal and good. Swap is a fallback, not something you want actively used. As long as RAM is sufficient the kernel will not touch it; you will only see it fill under real memory pressure - which is exactly when it saves the box from freezing.

Tuning notes (optional)

  • The default vm.swappiness (60) is fine. If you want the kernel to lean harder on RAM and treat swap as a last resort, lower it: sudo sysctl vm.swappiness=10 (persist it with a file in /etc/sysctl.d/). Not needed for a plain fallback setup.
  • Sizing: 4 GB is a reasonable cushion on a ~4 GB box. If memory pressure persists under normal load, the real fix is right-sizing the instance RAM, not a bigger swap file - swap is slow disk.
  • Keep heavy batch work (large backfills, model-loading worker pools) off a small box entirely; run it on a bigger machine and let the instance serve steady-state load only.

Remove the swap file

If you ever need to undo the setup:

sudo swapoff /swapfile
sudo sed -i '\#/swapfile none swap sw 0 0#d' /etc/fstab
sudo rm /swapfile