One way to guard against out-of-memory errors in applications is to add some swap space.
What is Swap?
Swap is a portion of hard drive storage that has been set aside for the operating system to temporarily store data that it can no longer hold in RAM. This lets you increase the amount of information that your server can keep in its working memory, with some caveats. The swap space on the hard drive will be used mainly when there is no longer sufficient space in RAM to hold in-use application data.
Swap space can take the form of either a dedicated swap partition or a swap file. Swap should not be seen as a replacement to physical memory. Since swap space is a section of the hard drive, it has a slower access time than physical memory. If your system constantly runs out of memory, you should add more RAM.
How to calculate Swap size?
The size of swap file depends on how much RAM your system has.
- Systems with less than 2GB RAM – 2 times the amount of RAM
- Systems with 2GB to 8GB RAM – the same size as the amount of RAM
- Systems with more than 8GB RAM – at least 4GB
Why is Swap needed?
- If your system has RAM less than 1 GB, you must use swap as most applications would exhaust the RAM soon.
- If your system uses resource heavy applications like video editors, it would be a good idea to use some swap space as your RAM may be exhausted here.
- If you use hibernation, then you must add swap because the content of the RAM will be written to the swap partition. This also means that the swap size should be at least the size of RAM.
- Avoid strange events like a program going nuts and eating RAM.
Does it necessary to create a Swap if RAM size is more than 16GB, 32GB, 64GB?
If you have 32GB or 64 GB of RAM, chances are that your system would perhaps never use the entire RAM and hence it would never use the swap partition. Allocating a couple of GB for swap will provide an extra layer of ‘stability’ if a faulty program starts misusing RAM.