Why Linux Needs Swap Space in a VM – Virtual Memory Explained

swap

Linux VM running nginx (or any other light-weight daemon with stable resource usage). VM is allocated 2GB of memory with 200-300MB used by OS and services with the rest for file cache and buffers. In one specific use-case I expect an easy 500MB overhead.

Q: Why would this setup need swap space?

The standard answer of "To prevent memory exhaustion" doesn't make sense to me here for 2 reasons: 1: the demand for memory is well established and does not need to support an unexpected or sudden significant increase. 2: Swap only delays OOM situation in any case. The same thing can be accomplished by assigning more memory to the VM in the first place, especially since it's thin provisioned any nobody will miss out on it as long as it's unused.

The other common answer to support hibernation doesn't apply to a server in a VM.

I see no reason for swap on such a server; am I missing something?

Best Answer

You shouldn’t think of “having swap” or not, you should consider your overall memory allocation strategy and determine whether or not swap is necessary. There are two main aspects to this.

The primary purpose of swap nowadays isn’t to extend physical memory, it’s to provide a backing store for otherwise non-reclaimable pages (e.g. memory allocations and anonymous mmaps). If you run without swap, you force the kernel to keep anonymous memory in physical memory, which reduces its ability to cope with varying memory needs. Obviously if you know your workload always fits in the available physical memory, this shouldn't be an issue.

The second aspect to consider is the kernel’s overcommit strategy. By default, memory allocations mostly succeed, regardless of the memory load. If you’re trying to control your workload though, it’s often helpful to run in checking mode (/proc/sys/vm/overcommit_memory set to 2); then commits are limited to the sum of swap, and physical memory not allocated for huge pages adjusted by the overcommit ratio (which is 50% by default). If you run without swap, nothing can ever allocate more than half the physical memory by default; adding swap increases that limit linearly, with less risk than increasing the overcommit ratio. (This often trips people up when attempting to run large-ish JVMs on typical server setups.)

I mentioned there are two main aspects, which are described above, but it occurs to me that there can be another point to consider in some cases (it’s really a variant of the first point): tmpfs file systems can easily get your system in trouble if there’s no swap...

For more on all this, I recommend reading the proc(5) manpage’s sections on overcommit, and Chris Down’s recent blog post in defence of swap.

Related Question