Ubuntu freeze when low memory

I believe this is the same question as this one, even though you have swap enabled: https://unix.stackexchange.com/q/373312/306023

Basically the kernel (or kswapd0) is evicting every active process's code (executable) pages in order to free more RAM, thus on every context switch when a process resumes execution, it needs to be re-read from disk into memory and only then can it resume execution.

This needs to happen so many times per second, coupled with the fact that disk are way slower than RAM, that the OS is seen as effectively freezing up. It's as if RAM gets temporarily replaced by the disk, and all of this is because the kernel makes the mistake ofis evicting the running processes's file-backed executable pages too, instead of just the inactive ones.

If you want to try and see what happens if the kernel doesn't evict those, you can recompile the kernel with this patch, seen in this question. What should happen is that the OS should freeze for at most 1 second now instead of minutes(or permanently) and there should be little to no disk thrashing.