23

In discussions about swap files ("should I create one?") I often see an obscure mention along the lines "in certain situations swap file can do more harm than good". That comes up often in conjunction with "if you have X GB of RAM or more you don't need a swap", usually backed by credible arguments. Then there are obviously countering arguments such as expressed here.

I can imagine a background-running application or service foo whose correct functionality depends on instant memory access. Dropping the memory space foo uses to swap would slow down the access to it slowing foo itself down causing warnings, errors or even a total failure.

However that's how far I get, the actual facts remain elusive. For example my Linux box has 64GB of RAM which allows me to run multiple VMs simultaneously. At this point many Linux users decide to not swap at all, but I've reserved 16GB just in case - drive space is cheap but the classic swap = 2x RAM seems exaggerated.

  1. Can someone give some real life examples from the UNIX/Linux world when having a swap file in a system with large amounts of RAM actually can cause / did cause unwanted consequences, and what those consequences could be / would have been?
  2. Does having a separate swap partition instead of a swap file change the situation?
  3. Prompted by user10489's answer: *NIX-like OS:s don't have a separate hiberfile similar to what Windows uses?

To clarify: RAM/swap ratio or whether or not swap should be allocated in the first place is out of scope of the question.

Peregrino69
  • 2,417
  • 2
    swap shouldn't be used nowadays. Use zram instead – phuclv Sep 20 '21 at 12:50
  • @phuclv Strictly speaking out of the scope of the question, but thanks for the hint anyway, I'll check it out :-) ... and after a quick peek it's working in RAM, so doesn't it rather expedite problems in OOM situation? – Peregrino69 Sep 20 '21 at 12:52
  • 1
    it's just like swap, a special kind of swap, so it helps greatly in OOM situations. It takes almost zero memory when swap is not needed, and when memory is lacking then it compresses unused pages to make room for other more useful pages instead of killing processes. See How do I use swap space for emergencies only?. Of course if so much memory is used that if fills up both zram and free memory then the same thing happens when you fill up the swap partition: OOM occurs – phuclv Sep 20 '21 at 13:32
  • @phuclv At this point I'm taking your word for it :-D I need to read up. Thank you anyway for pointing it out :-) – Peregrino69 Sep 20 '21 at 13:50
  • 4
    please clarify if you mean swap partition or actually mean swap file. – ron Sep 20 '21 at 15:13
  • 1
    @ron As the title states, swap file. Question 2 is whether a separate swap partition changes the picture :-) In practice I'm interested what issues either one might have caused in real life - I've only heard statements "this caused terrible problems" without any clarification on the nature of the stated problems. – Peregrino69 Sep 20 '21 at 15:14
  • 6
    @ron, honest question: does the distinction (swap file vs. swap partition) actually matter that much? – ilkkachu Sep 20 '21 at 20:29
  • May draw your attention to two other questions I wrote a while back: https://unix.stackexchange.com/questions/499485/how-do-i-use-swap-space-for-emergencies-only an example of swap going wrong on a desktop https://unix.stackexchange.com/questions/556441/what-specifically-can-swap-do-that-ram-cant an attempt to get those who say "you must have swap" to explain practically why. – Philip Couling Sep 20 '21 at 21:14
  • I've played with all the swap parameters and zswap/zram. zram does nothing that swap doesn't also do -- it just extends the pain a little longer before you get around to buying more ram. In both cases, ultimately, it makes your computer slower instead of crashing something with the OOM killer. zram vs. swap is really an argument if your cpu is faster than your disk or not, and that answer changes month to month as new products come on the market. – user10489 Sep 21 '21 at 05:05
  • 7
    "swap = 2x RAM" is "classic" because it goes back decades, to the time when UNIX machines had memory measured in megabytes, or even less. It's rather ridiculous to apply it to today's hardware. – Michael Hampton Sep 21 '21 at 07:42
  • @MichaelHampton Yap, that's a sentiment I definitely share :-D Well do I remember those days... Even my quarter RAM seems like an overkill, but as drive space is cheap, I've had no reason to start testing to find the optimal size for my setup. I've got a couple of old laptops with 4GB, I think I also reserved quarter size for those. – Peregrino69 Sep 21 '21 at 07:45
  • @phuclv but then many systems without much RAM or the ability to add any are somewhat lacking in CPU to process the compression. I'm sitting in front of one where it might make a difference: 8GB RAM and I sometimes need much of that for a windows VM, so I'll try it – Chris H Sep 21 '21 at 09:44
  • @ChrisH 8GB is nothing near lacking. Try some systems with 1GB or 2GB and you'll see that with zram it's significantly more responsive – phuclv Sep 21 '21 at 10:17
  • @phuclv it's all about the use case. I've run low spec machines in the past, but not tried to use windows in a VM for CAD on them. On this machine I can end up with 1-2 GB for the host,which is less than my old netbook – Chris H Sep 21 '21 at 10:25
  • @MichaelHampton IIRC some systems also need swap to be an integer multiple of RAM due to addressing schemes of swap and ram being the same? – rackandboneman Sep 22 '21 at 18:04
  • @rackandboneman Not sure what systems would that be, definitely not Linux on ordinary computers. – TooTea Sep 23 '21 at 11:24
  • @ron: For the past couple decades there has been no distinction between swap partition and file when it comes to performance, at least with a proper filesystem (e.g. ext3/4) as opposed to something FUSE-based or whatever. In both cases the swapping happens directly on the underlying block device blocks. – R.. GitHub STOP HELPING ICE Sep 23 '21 at 15:13
  • my point is it is not happening on the block devices until such time RAM is full. Case in point - any diskless linux system; swapping happens automatically under the hood in linux as process & memory mgmt and if one thinks they are doing something better by making a partition or explicitly making a swap file they are deluding themself. I would agree no performance difference between swap file vs partition, performance would be the same as it's all happening in RAM until it actually needs wherever on the disk (because RAM full) and performance will always then be in the toilet. – ron Sep 23 '21 at 21:01
  • and swap file vs swap partition - wherever on the disk partition-wise would/should not matter for read/write performance and i don't doubt there never was distinction made between the two regarding performance it makes no sense why there would ever be. But the entire topic of swap now I think is obsolete and anyone still trying to do anything with swap is fooling themselves and just because there's still some kind of swap function left accessible to them in their linux distro does not mean it's doing anything good for them. If so I'd like to know how. – ron Sep 23 '21 at 21:10
  • @TooTea I think I had read such explanations, but agreed, not about linux but far older systems (original unix). – rackandboneman Sep 25 '21 at 00:19

9 Answers9

34

Swap can be bad in that it may make some failure cases last longer. Consider a situation where some process starts using excessive amounts of memory, due to a bug or a misconfiguration or other such reason. If there's no swap, it'll eventually run the system out of memory, causing the OS to resolve the issue by eventually killing the process. (But possibly causing other trouble anyway.)

But if there is loads of swap space, the process will start consuming swap space, possibly thrashing pages between main memory and swap, and that slows eve-ry-thing down. The system will eventually run out of memory, but you suffer longer before that.

I'm mostly thinking slow swap devices, i.e. disks of spinning rust, since that's where I've encountered this... Probably less of an issue with modern high-speed SSDs.

(Of course, a proper solution to that would be per-process limits on memory use, but lacking those, as your usual random desktop system probably does, the fact of the swap space existing or not can play an influence.)

I'm not commenting on if having swap is good or bad in general, just the one possible situation. I'm also not commenting on ratios and such; they're usually generalizations, and may possibly be based on requirements that aren't valid any more.

ilkkachu
  • 138,973
18

Technically, a swap partition is more efficient than a swap file. Practically, if the swap file is contiguous, there should not be a lot of difference, and current versions of linux, no performance difference at all. There are a few bugs around swap files, but they are only triggered in some odd circumstances.

When swap is more harmful than useful depends entirely on the workload of your system. If your system workload never causes the swap to be used, then there are no issues. If you have programs that allocate lots of memory (that ends up in swap) and never use it again, swap helps a lot (memory leak?).

But if your total working set size (what a program wants in physical ram) for everything that is running is larger than physical memory and some of the overflow ends up in swap, then your system will thrash, constantly trying to push things to swap and load other things back in. This can cause your system performance to be 1/10 of normal, and it may feel like the system has locked up, where without the swap, something would have gotten OOM killed.

It is debatable and situational if it is better for the system to become slow and thrash, or if it is better if something gets killed and system performance returns to something more normal.

Any analysis beyond this or attempts to assign ram/swap ratios would be either situation specific or an opinion.

Swap is also used for other purposes, like hibernation, which requires you to have at least as much swap as ram, and possibly crash dumps.

I'd like to add that all of the above applies specifically to linux. Some versions of unix specifically require enough swap to shadow all of ram, and if you want virtual memory on top of that, you need more swap than ram. Current linux runs fine without swap -- some unixes do not, and extremely early versions of linux also needed swap.

user10489
  • 6,740
  • Well now, that would be an opinion. My opinion is that you should always have a little swap, otherwise you won't know when the system wants to use it. Typical swap to ram ratios would be 1G 10% 1/2 1 2 ... but without a use case, there's no basis to pick one of those. – user10489 Sep 20 '21 at 11:30
  • Indeed :-) I'm not interested in opinions or ratios - I've got my own. Your answer's pretty darn good so +1, but not an actual real-life situation so I'm waiting a bit before accepting :-) – Peregrino69 Sep 20 '21 at 11:32
  • What comes to hiberantion - Windows uses a separate hiberfile which obv needs to at least equal RAM as you say. That's not a thing in *NIX world? – Peregrino69 Sep 20 '21 at 11:37
  • 13
    "you should always have a little swap" this has no basis in reality. I've been running my PCs and servers swapless for over a decade with zero issues. But I've sure had terrible issues with SWAP enabled. Typical swap to ram ratios you've pulled it out of thin air - there's exactly zero rationale or science behind that aside from ages old manuals/guidelines which were written at the time when PCs had on average less than 64MB of RAM. – Artem S. Tashkinov Sep 20 '21 at 11:44
  • @ArtemS.Tashkinov I agree, swap is not always useful. However, on desktop systems there are usually programs that allocate memory but do not use it again for a long time (e.g. login window). If those memery regions are swapped out then more RAM is available. This can (and will) be used for disk buffers/cache, speeding up disk access. Of course if you have an abundance of RAM this will not be relevant or make a difference. – Ned64 Sep 20 '21 at 11:51
  • @Ned64 I've had more problems with swap on desktops than servers (like this one). I have to agree with Artem on this one. Ratios are a bad rule of thumb. DiskIO means that massive swap is a bad idea if you suddenly have to restore many GB from disk to RAM. Better to use a use a log(n) formula if you're going to use such rules at all. – Philip Couling Sep 20 '21 at 21:03
  • 1
    If you have a little bit of swap, it can't cause much thrashing, as it'll just fill up fast. If it is never used, then you are sure you don't need it. But if it is used and you still have free memory (in cache?) then you know you could get a bit more performance from enough swap. – user10489 Sep 21 '21 at 00:17
  • At least some versions of FreeBSD wanted quite a bit of swap. Even on systems with lots of RAM and lots of unused memory, they wanted to proactively swap out quite a few things. Not sure if that changed since I encountered that or if that was something you could easily tweak. – jcaron Sep 21 '21 at 08:37
  • "Technically, a swap partition is more efficient than a swap file." do you have a benchmark or citation? – ezekiel Sep 21 '21 at 09:01
  • 3
    "Technically, a swap partition is more efficient than a swap file. Practically, if the swap file is contiguous, there should not be a lot of difference." - If the swap file is contiguous, there is no difference at all. – marcelm Sep 21 '21 at 10:15
  • 4
    @marcelm: no difference, except for filesystem overhead (which might be one time) and various bugs involving swap files. And the possibility of growing the swap file if that is supported. – user10489 Sep 21 '21 at 11:19
  • 2
    @user10489 Check Andrew Morton's mail I linked; when the swap file is opened, the blocks are mapped directly, just like they are for a swap partition. After opening, the filesystem is completely out of the loop. Growing swap files (or partitions) is not supported on Linux. – marcelm Sep 21 '21 at 14:10
  • There's no harm done by omitting swap space - provided only a small amount of swap space is needed since the kernel will just reduce unused buffer storage. It only matters if you hit a case where you need a lot of swap space. – Jeremy Boden Sep 21 '21 at 21:37
  • A swap partition has slightly less one time overhead than a swap file, but this is negligible, especially since it only happens once when the swap is enabled. But there are still non-performance differences between the two. – user10489 Sep 23 '21 at 04:20
  • Thrashing can occur also without swap, at least on Linux, so I think it should be left out of the equation in this case – golimar Sep 23 '21 at 10:18
  • The real fix for thrashing is not to disable swap (which will just direct the thrashing to file pages), but to apply memory limits through cgroups (mostly for server workloads) or to use a daemon like earlyoom/oomd/systemd-oomd to pull the trigger before everything grinds to a halt (for desktops). – TooTea Sep 23 '21 at 11:16
  • @TooTea: That helps, but only to a point. Beyond that point, the only real fix is to buy more ram. – user10489 Sep 23 '21 at 11:25
  • 1
    Yes, but those are two orthogonal concerns. If your ordinary workload triggers thrashing, you need more RAM. If only pathological conditions (runaway processes, massive memory leaks, DoS attacks, …) trigger thrashing, you need to protect your system against them using the right tools, not buy more RAM or disable swap. – TooTea Sep 23 '21 at 11:31
5
  1. Bear in mind that managing the swap space consumes both RAM and CPU cycles - even if you don't really get to using the swap space. Sure, it is not much, but RAM usage something like 1/20 of the swap space is to be considered. The memory pressure adds up. CPU cycles are probably way less.

  2. Swap hides memory leaks - this may be both good (when you run a bad software you need to live with) and bad (this is how bad software is allowed to live in the first place).

    In some cases, a brief restart because of out-of-memory condition is preferrable to long timespan of bad performance. In other cases, it is not.

  3. Swap may write sensitive information on the disk. Including, but not limited to, crypto keys, passwords, personal data, etc... and keep them there indefinitely even if the software intends to keeps them only briefly in memory. Some software explicitly lock pages with known sensitive information in memory, but this feature cannot be extended to all possible sensitive information. This is a growing risk exposition over this data.

    I am yet to see an IT business with a good (working and always applied) policy about clearing disks removed from running systems.

    Encrypted swap areas (files/partitions) do exist, but they come at the additional cost of complexity and performance. At least for a while, in Linux, encrypted swap files, as well as some encryption methods over partitions, used to have known stability problems. Encrypted dm-crypt/luks swap partitions are okay-ish.

  4. Performance - you hit the memory limit, your users swear. SSDs are better in this regard, but see below.

    And in some OSes (e.g. Windows, I am yet to see Linux doing the same, but the bad habits are contaguios) the memory gets "offloaded" to swap long before you are out of physical memory - just in case. Yes, this improves responsiveness (somewhat) at the price of overall worse performance and additional disk traffic.

  5. Write load on SSDs - SSDs wear when written to. Modern SSDs are rather durable, but one can never be sure how much - and their failure modes are rather unpleasant.

    They are rather fast and one may not know of the swap usage until it is late.

fraxinus
  • 299
  • 4
    You've missed one of the important points - if you have large amounts of memory you're not using, then swapping that out makes more memory available for buffer cache, which can improve the performance of processes accessing storage. – Toby Speight Sep 21 '21 at 10:00
  • 1
    "I am yet to see an IT business with a good (working and always applied) policy about clearing disks removed from running systems." Oh, there are. But usually no one bothers to wipe that data, instead opting for physical destruction - and there is a whole market for devices and services related to that. – rackandboneman Sep 22 '21 at 18:06
  • @rackandboneman probably, I just never met them. And yes, I worked with both government bodies and businesses that owned a mechanical disk destructing devices. – fraxinus Sep 22 '21 at 18:48
5

Swapping on inappropriate media

SD cards used as swap tend to fail prematurely and nastily due to limited number of write cycles. This is particularly a problem on early raspberry pi setups due to limited usb bandwidth cheap SD cards and limited ram.

hildred
  • 5,829
  • 3
  • 31
  • 43
3

I can imagine a background-running application or service foo whose correct functionality depends on instant memory access. Dropping the memory space foo uses to swap would slow down the access to it slowing foo itself down causing warnings, errors or even a total failure.

This reasoning is erroneous. This reasoning contains the implicit assumption that putting something in swap and discarding it from physical RAM are the same thing. Either can occur without the other.

  1. Clean pages can be discarded from RAM without being written to swap. This can happen even if you have no swap file. So your program whose functionality relies on instant memory access could be screwed because its code pages were discarded from RAM even if there is no swap file. In fact, this is more likely to happen with no swap file because dirty pages cannot be discarded without a swap file meaning clean pages (such as code) are more likely to be absent from physical RAM.

  2. Pages written to swap are not necessarily discarded from physical RAM. A page can exist in both swap and physical RAM. Pages can be in both physical RAM and in swap.

As a result of these two things, the argument above just doesn't make sense. Swap allows dirty pages that have not been accessed in a long time to be ejected from physical RAM. Without swap, only clean pages can be ejected, even if there are no clean pages that haven't been accessed in a long time.

Your critical process isn't guaranteed to find data in RAM with or without swap. However, it is more likely to find data in RAM if you have swap. Why? Because whether you will find things in RAM depends on whether the system's working set fits in RAM. Having swap removes dirty pages that are never accessed from the working set, reducing its size and increasing the chances that it fits in RAM.

  • Thanks for clarification. That just means I wasn't able to even imagine the one situation when swapping would be harmful correctly :-D The limits of my ken are pretty obvious, and I'm the first one to admit them. I appreciate being educated :-) – Peregrino69 Sep 21 '21 at 18:11
2

Can someone give some real life examples from the UNIX/Linux world when having a swap file in a system with large amounts of RAM actually can cause / did cause unwanted consequences, and what those consequences could be / would have been?

Yes, quite a few examples, though I’ll stick to a simple abstract one that you can replicate easily in a VM with smaller numbers.

Assume you have a system with 64 GB of RAM, and 4 GB of swap space (this is a reasonable setup by some standards, not by others, but that’s not relevant right now). Some program starts that needs to work with 65 GB of data ‘in memory’ concurrently. Obviously, it can’t access all of that at exactly the same time, but the dataset is still small enough to fit in virtual memory without issue. What happens to the rest of the system while this program is running?

In the case that the rest of the system needs more than about 2.9 GB of RAM, something will crash, either the app using all the RAM, or possibly the whole system (you can actually configure Linux to reboot if it runs out of memory, I’ll explain why in a bit). However, if the rest of the system needs less than that, everything will keep running, except very slowly because the system is having to constantly shuttle data between swap space and RAM.

That state of constantly shuttling data between swap and RAM is known commonly as ‘thrashing’, and it’s one of the worst possible states an otherwise usable system can end up in short of a hard lockup. It’s important to note that thrashing eats up lots of resources, and how fast your persistent storage is is only one factor in making the system slow when thrashing. The gymnastics that are needed with the page tables to make swapping work correctly are kind of expensive at the hardware level in many cases, and that is a huge part of why thrashing makes things run so slowly. Nothing works well on a thrashing system, and it’s quite often not even reliably possible to log in and manually fix things.

This is obviously a very undesirable situation for a regular home user, but it’s ‘break the internet’ levels of bad if it happens on, say, a core router on the internet. Avoiding any kind of thrashing is part of the reason some people either avoid having swap space, or only provision a very small amount (as in a few hundred MB at most on a system with 64 GB of RAM).

Of course, even the guarantee of not thrashing may not be good enough for the system’s uptime requirements, so it’s possible to go a step further and have the system reboot when it runs out of memory (by configuring Linux to panic on an out-of-memory condition, and then configuring it to automatically reboot in the event of a panic). This hard reset approach is popular in high reliability setups because it gives you a guaranteed clean state to work with after running out of memory.

Does having a separate swap partition instead of a swap file change the situation?

In general no. The primary reason to want a swap partition over a swap file is mostly that it allows hibernation to work more reliably (or so you can easily share it between different Linux installs on the same system, though that’s a rarer use case these days).

Prompted by user10489's answer: *NIX-like OS:s don't have a separate hiberfile similar to what Windows uses?

Generally correct. I can’t speak for how macOS or other comercial UNIX-like systems handle hibernation, but Linux, *BSD and MINIX all store their hibernation data (really just a memory dump, unless you set things up to do fancy stuff like compression or encryption) in swap space. Windows adapted a split setup so that it did not have to empty it’s page file (equivalent to a swap file on Linux) when hibernating, which means that technically Windows is more flexible when it comes to hibernation than Linux.

  • 2
    Not having swap doesn't guarantee no thrashing. Not having swap only guarantees that reclaim has to target file-backed pages instead of anonymous ones. The resulting thrashing on file-backed pages can be just as bad. (Or worse, if it forces things like libc out of memory and then back again thousand times a second instead of an inactive anonymous page.) – TooTea Sep 23 '21 at 09:39
  • @TooTea True, when I didn't know this I was surprised to see the HD LED blinking like crazy on low free memory, while not having any swap configured – golimar Sep 23 '21 at 10:25
  • @TooTea While generally true, thrashing on file-backed pages tends to be much more workload specific than thrashing on swap, and it’s generally easier to configure a system to completely avoid it than to completely avoid thrashing on swap. – Austin Hemmelgarn Sep 23 '21 at 11:08
1

Swap is a highly variable subject, which is not made easier by the fact that each OS, and often even different versions of the same OS, might handle this wildly different.

I see these potential harmful aspects of swap:

  • A too large swap wastes space; if your storage is limited, this can be an issue.
  • An application might "think" that it has more RAM available than it in fact has, and thus reserve more than it strictly needs, and thus force other applications into swap that wouldn't need to be there in the first place. I had this problem on OS/2 3.0 (or Windows NT4 or 2000, unsure) and can vividly remember that I had written a program which grabs as much memory as possible (i.e., the full physical RAM) to force some really unused RAM reserved by some bad apps into swap... This problem might be a bit theoretical these days; I assume/hope that in the last decades the mainstream OSses have figured all of this out.
  • Swapping is slow. Incredibly slow. Sometimes I would rather have a clear-cut out-of-memory error than having to hit a brick wall when the swap is hit.

The only harmful aspect of not having (enough) swap is that you get out-of-memory errors and processes are killed by the OS. From my point of view, when at all possible, the correct solution is to get more RAM, not to increase swap. If an application actually does need slow storage to offload some of its data (this is quite usual in RDBMSses, for example), the application should handle that itself in an optimized way, and not rely on the OS and swap. If it is not possible to increase RAM, then the second correct solution is to reduce the RAM pressure, i.e. not use more than you have, by removing processes from the machine, or configuring them to use less.

You do find arguments that even if you have more RAM than you would ever need, you should still create swap. This may or may not be useful; one would probably have to dig deep into the RAM management routines of each OS to find out if there is any rhyme or reason to this theory. I would have zero problems trying without swap if I feel I know what my processes need, and my gut feeling for any modern OS would be that even if it is suggested to have a certain minimum amount of swap, it would work fine without any swap at all if it allows to be configured thus.

Whether to use a swap file or swap partition is more a management issue for me (it is easier to create or change a file than a partition). Especially if swapping to a SDD, it would not matter performance-wise. If swapping to a HDD, having a fragmented swap file would be ugly of course, but any modern OS should be able to create a big file in relatively large continuous spaces on the HDD.

AnoE
  • 575
0

I read the other answers and thought I could write something shorter, but apparently not. At least I will address the main question and not swap in general and ssd vs. hdd...


These are real-life situations from my experience where swap has proven questionable. I will present the scenarios briefly and then expand on the pros and cons.

  • On my personal desktop

In case you do something silly like a fork-bomb in a terminal, it is much more preferable to have that script / terminal OOM-killed by the kernel rather than watching your X session and everything else become completely unresponsive.

  • On a production MySQL server

If the available system memory is less than what the mysql instance needs (plus everything else on that system) then some live user data from a request may end up in swap. If the power is cut off at that time, chances are you will end up with an incorrect logical state of your application. Despite the server being able to restart without corruptions in the data layer, recovering from data loss may be very painful for you or your clients.

  • On the front-end nodes of a web application

If a single node is handling more connections than it has memory for, and it is allowed to swap, all of the transactions will run much slower and the response time of the web application will be higher than acceptable. The web app will intermittently time out with 503 or 504 errors and there will be support cases to deal with.

Pros and cons

  • Desktop

I know two ways to recover a system from a process that steals all your memory and swap in a reasonable amount of time.

  1. Shell in from another machine and kill the offending process. Obviously this is not always possible.
  2. The reset switch, which may be very unlucky depending on what you were doing at the time.
  3. Prepare for this scenario / harden your system (yeah, right..)

"Saving memory" by putting some not-often accessed bits on disk is not really a benefit. The system has to use CPU and DISK-IO to swap memory from/to disk, you don't want that. If the kernel worker [kswapd0] is in the list of top-five or top-three processes ranked by overall cpu-time used on your system, I think that is cause for concern. So reduce vm.swapiness to 0 or 1-5 with sysctl on your machine or disable swap altogether.

If you don't have enough memory in the first place, then ask your boss for a new laptop, buy your own or suffer from poor performance. You can also invest your time in optimizing the memory-usage of the offending applications and let me know what you think about the ROI of that in a decade or two ;)

  • Production MySQL server

There are no pros for having swap on a production MySQL server in my opinion. Needing swap means you don't know what the work load is. With swap, it will get slow and the application performance will be unacceptable.

  • WWW workers

Having swap may help you "gracefully" detect issues. Assuming you have monitoring in place this may be considered ok in same cases. In most cases the application will be too slow for comfortable use. If the frontend nodes are not horizontally scaled and the swap / memory is abused by some background report-like task, then the net result is the same or even worse. The response times will be too high.


So overall, you need to have some experience and goals for the system in question to make good desicions. Hopefully I have been clear about my negative perspective on swap, but in real life, I do have swap both on my desktop and production servers because there are benefits to having swap (such as detecting memory leaks, having alerts / time to act before services are killed, hibernation). Unless you can prove that swap ruins performance, it is safe to allocate some.


Does having a separate swap partition instead of a swap file change the situation?

Short answer is no.

Prompted by user10489's answer: *NIX-like OS:s don't have a separate hiberfile similar to what Windows uses?

This is not a question, this is statement with a question mark at the end. Windows has a "hidden system partition" and optional hiberfile. Linux uses swap partitions for hibernation or swap files which cannot be used for hibernation. Conceptually these partitions/files/hiberfiles fulfill the same purpose. The implementation details are pointless to compare for the purpose of answering the first question, if you ask me.

-1

a quick read: https://www.linux.com/news/all-about-linux-swap-space/

Linux has two forms of swap space: the swap partition and the swap file. The swap partition is an independent section of the hard disk used solely for swapping; no other files can reside there. The swap file is a special file in the filesystem that resides amongst your system and data files.

  1. swap file : can you remove this... I would say no but would also say everyone's definition today of swapping with regards to the linux operating system is somewhat out of context. I prefer to call it or think of it as memory & process management by the operating system. And what everyone wants to call "swap" from 20 years ago no longer necessary applies because the linux has kernel has improved drastically- the big change was when it went to kernel 2.6 a lot of improvements were made and it is now up to 5.something; you will have to research kernel.org to get the technical info. And I would get a more credible statement on this from a kernel developer who would know more of what they are talking about than I.

So the kernel makes use of ram, pretty much exclusively now because that's the best and fastest way to accomplish anything- with home pc easy getting to 32gb if not 64gb and work environment servers getting to 768gb on 4-socket quad-channel ram intel systems. Any swap file whether you specifically declare one or not I would argue now all happens under the hood as memory & process mgmt by the operating system and is stored in ram to begin with. You would have to research your linux distro and don't quote me on this but the disk (folder) location that comes to mind is /proc if any kind of swap file is inherently defined {otherwise the command swapon comes to mind to say where you want to put one} but in any case computer code doesn't care what you name it it's just a variable to it; I don't know what the convention is today I let RHEL/CentOS 7 for example run happily with all its tmpfs mounts never seeing the mention of swap anywhere.

Do I care about making a swap file ? NO, because that stuff has already been taking care of by linux.. I do not have to manually make a swap file to make my system work nor work better; if this is the case someone please cite a current credible reference otherwise I am saying the process & memory mgmt is already all taken care of for you by your linux distribution. There is no problem until you run out of RAM.

  1. swap partition : are you required to make this - NO. RHEL/CentOS7 for example {can't speak 1st hand on others} will give you a warning when installing it from dvd if you do not make a dedicated disk partition where no other files can reside but it is just a warning; I have been doing work servers {with >= 128gb ram} for a while now with no swap partition with zero problems ever.

Without a swap partition where would SWAP type stuff go if RAM runs out? Under '/proc' automatically? Which is a folder under the root '/' partition that has the capability to encompass the entire disk unlike making a dedicated partition where only those swap files can reside which will be some much smaller arbitrary size of your choosing. Or if not under /proc then wherever else you might declare it to be with the swapon command comes to mind. The point being unless you made your dedicated swap partition larger than your root '/' partition you are doing yourself a disservice and more than likely wasting disk space making a dedicated swap partition.

One time long ago a server thrashed away overnight on disks which was the swap partition and was able to recover itself after putting all its ram to 100%. But realistically speaking any normal admin is going to power button it after wasting 10 minutes from the system becoming unresponsive due to RAM 100% full. No one often says Thank God we made that swap partition. No intelligent person will routinely run their system to 100% full of RAM as normal operating procedure - if that is happening then that system is inadequate for your needs and you need more RAM plain and simple. The persistent idea of needing [disk] swap space to handle a ram full scenario borders on absurdity. Not to mention having a server with lots of ram 512GB for example then making a 16gb dedicated swap partition... what is another 16gb going to really solve that the existing 512gb could not besides upset me when I very often experience hard drive full of user data and that dedicated 16gb partition swap files only could have been used for real data. Not to mention a dedicated swap partition is usually a complete waste of disk when everything swap related is residing happily in RAM (tmpfs) to begin with (i.e. disk caching).

About swap for hibernation, everything said above applies and you simply need enough space somewhere for whatever the size of the contents in RAM are can be stored to somewhere on non-volatile storage. When is swap file harmful : depends on how you look at it it won't cause your system to fail if you go through the manual effort to make a swap file and/or partition even if you make it smaller than you're RAM it'll be dependent on your RAM size first and foremost until you hit a hibernation scenario or some scenario where that RAM data is larger than the [dedicated] disk [partition]. Probably most harmful if anyone ever makes a swap anything on my system and wastes hdd/ssd/nvme space when we put adequate amounts of RAM in there to begin with.

ron
  • 6,575
  • https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/storage_administration_guide/ch-swapspace – ron Sep 21 '21 at 13:44
  • note: BTRFS file system does not support swap space; meaning wherever that data resides on disk whether in a swap file or dedicated partition is arbitrary and by convention. – ron Sep 21 '21 at 13:45
  • Actually, current BTRFS does support swap files, through the same mechanisms used for supporting swap files on NFS shares. And, of course, you can always set up a loopback device to sidestep any such issues. – Austin Hemmelgarn Sep 22 '21 at 02:02