Automatically manage swap / memory

Solution 1:

The Linux kernel is... iffy in terms of swap support. Swap is a second-class citizen, from the perspective of many developers. What I mean by that is that the algorithm used to eject and fetch pages is fairly simple, and can break down when there are a lot of frequently-used pages.

A decent solution would probably be to use zswap. What this does is set a chunk of memory to be compressed memory, to which pages are ejected. To do this, edit the kernel boot parameters to add zswap.enabled=1 zswap.compressor=lz4 zswap.max_pool_percent=20 zswap.zpool=z3fold. The easiest way to do this on a Ubuntu system is to add it to the /etc/default/grub file, as part of the GRUB_CMDLINE_LINUX_DEFAULT key. This will effectivly increase the amount of data that can be stored in RAM, reducing disk IO and preventing lockups.

Lastly, you ask about having more swap space dynamically created. Linux is fully capable of adding and removing swapfiles at will, which means that a script could check swap availability, and then add swapfiles if needed. However, there isn't much point to this if your using the full swap space very often.

To increase swap space (without repartitioning your disk), you can use a swapfile. To do this, run sudo dd if=/dev/zero of=/swapfile count=1M bs=1024 status=progress, which copies 1 million blocks of 1024 bytes (ie, 1 gigabyte) into a file. Then, run sudo chmod 0600 /swapfile and sudo mkswap /swapfile to prepare the file for use as swap. Add it to /etc/fstab to have it always available, by appending the following line to that file: /swapfile swap swap defaults 0 0. To finish the process, call sudo swapon -a, which activates the swapfile.

Source: I myself use swapfiles and zswap, and referenced my bash_histroy and the Arch wiki for the commands.