46

I've used unix for quite a while, and for the last couple years I've felt like swap is an anachronism, but I'd be curious what other folks think.

My argument is roughly this (assuming no global ulimit or twiddling of OOM settings):

There is little value in swap because if you need to swap out to disk, 
odds are it's going to be a vicious cycle where an app will continue 
to eat not only real memory, but swap as well until it gets OOM 
reaped (_if_ it gets OOM reaped). 

If you have swap enabled, it will only prolong this death march to 
the detriment of other processes - and in the worst case where the
process is not OOM reaped in a timely manner, grind the system to
a halt.

Without swap, it will probably get OOM reaped sooner (if at all)

For any service that is tuned for performance, I would think that understanding the upper limits of it's resource usage would be key to tuning it in the first place, in which case you know how much you need.

I can't imagine many situations (some, but not many) where you'd suspend a running process and it could swap out to make room for other things, but you'd still lose your sockets if you did that, so forcing a core-dump via gcc or copying the memory out by hand would be functionally equivalent.

I definitely wouldn't want swap on an embedded system (even though it may have a smaller available ram), if you run out of ram I'd rather have my process die than tear up a million-write-per-sector flash memory drive over a weekend by wear-leveling the sectors down to the nub.

Any unix-beards out there have any compelling reasons to keep swap around?

UPDATE answers && analysis:

  • CONFIRMED? - fork() requires the same amount of memory for the child process as the parent

    Modern fork() is copy-on-write for children on POSIX (in general), but Linux and FreeBSD specifically, and I'm assuming OSX by extrapolation. I consider this part of the anachronistic luggage that swap carries with it.

    Curiously, This Solaris article claims that even though Solaris uses Copy-on-Write with fork(), that you should have at least 2x (!) the parent process size in free virtual memory for the fork() not to crap out in the middle. While the Solaris element somewhat busts the argument that swap is an anachronism - I think enough operating systems correctly implement CoW in such a way that it's more important to dispel the myth than to mark it as further justification for swap. Since. Lets face it. At this point the people who actually use Solaris are probably just Oracle guys. No offense Solaris!

  • CONFIRMED - tmpfs/ramfs files can go to swap as a convienence when tmpfs/ramfs fills up

    Don't use no-limit tmpfs/ramfs! Always explicitly define the amount of ram that you want tmpfs/ramfs to use.

  • PLAUSABLE - Have a little swap 'just in case'

    One of my old bosses used to have a great saying, 'you don't know what you don't know' - essentially, you can't make a decision based on information you don't have yet. This is a plausible argument for swap to me, however - I suspect that the types of things you'd do to detect if your application is swapping out or not would be heavier than checking to see if malloc() succeeds or catching the exception from a failed new().

    This may be useful in cases where you're running a desktop and have a bunch of random things going on, but even still - if something goes nuts I'd rather it be OOM reaped than diving into swap-hell. That's just me.

  • BUSTED! - On Solaris, swap is important for a couple of reasons

    tmpfs - states The amount of free space available to tmpfs depends on the amount of unallocated swap space in the system. The size of a tmpfs file system grows to accommodate the files written to it, but there are some inherent tradeoffs for heavy users of tmpfs. Tmpfs shares resources with the data and stack segments of executing programs. The execution of very large programs can be affected if tmpfs file systems are close to their maximum allowable size. Tmpfs is free to allocate all but 4MB of the system’s swap space.

    Solaris facts and myths about swap - states Virtual memory today consists of the sum total of physical RAM and swap space on disk. Solaris DOES NOT require any swap space to be configured at all. If you choose this option, once RAM is full, you will not be able to start new processes..

    I'm unsure if this means that the maximum virtual map you can create is ram+swap, or if you could still do something like mmap() a file larger than ram and rely on mmap()'s lazy initialization.. While you can probably run Solaris these days fine without swap, it seems like it's less friendly about it than other POSIXy operating systems.

  • BUSTED! Popular Linux hibernation tools appear to rely on swap

    By default, TuxOnIce looks like it relies on swap for hibernation - although other backends exist. However, if you're not running a box that needs to hibernate, I would still stand behind the statement that 'swap is anacronistic on linux'

8
  • 1
    I don't have much un*x beard (some hair still ;), but my 2 cents would be that having a "bit" of swap would give your system some robustness. As instead of directly OOM, you would go to swap instead if a bit over your system limits. Sure, if really way over your system limits, your system will eventually crash/halt/nuke-itself/whatever-hell-you-can-imagine. So giving a bit rope to play with ;)
    – Ouki
    Feb 27, 2012 at 19:15
  • 1
    The thing about fork() is in fact true if you set your system to never overcommit RAM (this is not the default). Now why you would need that setting anymore I have no clue. It's not useful for realtime processing.
    – Joshua
    Feb 27, 2012 at 22:43
  • @Jushua: Memory overcommitment might not be the default or even possible depending on the operating system.
    – jlliagre
    Feb 28, 2012 at 13:31
  • 1
    I have a NAS server with 8GB of RAM, it will run up to 2 VMs. I did not put swap. If it starts swaping heavily, then it is anyway already dead. So it perfectly supports your argument. On the other hand, I am still using my rusty desktop with is limited to 1GB of RAM and there I do have swap to handle the sparse memory. It makes thing a bit slower but help me having Firefox and other applications opened at the same time.
    – Huygens
    Feb 9, 2013 at 21:56
  • 1
    I find the OOM killer triggers too late, only after all caches have been emptied and the system has become sluggish. To keep my system snappy, I use earlyoom or nohang to do the same job but earlier! Can be used with or without swap. Nov 4, 2019 at 2:47

10 Answers 10

31

Don't confuse (the) swap (as a disk area) and (to) swap (as a method to move memory pages from RAM to disk and reciprocally).

Excessive swapping is something to be avoided for performance reasons but having a swap area isn't necessarily a problem.

On systems, like Linux, that overcommit memory, i.e. that allow processes to allocate more memory than available, running out of RAM with not enough swap to handle the situation will trigger the OOM killer. You have to trust the algorithm used to select the "right" process to kill, and accept one or more of your processes to be killed without being given a chance to shut down properly. Here is a famous analogy that explain why the OOM killer might not be a good idea at all.

On systems like Solaris, that do not overcommit memory, i.e that make sure a memory reservation is always backed by virtual memory, whether in RAM or on disk, having a sufficient swap area is absolutely necessary otherwise a potentially significant part of the RAM will be wasted.

9
  • 1
    Are you sure that the point about Solaris is still true? blogs.oracle.com/jimlaurent/entry/solaris_faq_myths_and_facts states: Virtual memory today consists of the sum total of physical RAM and swap space on disk. Solaris DOES NOT require any swap space to be configured at all. If you choose this option, once RAM is full, you will not be able to start new processes. I think I see what your point is - if you wanted to mmap something larger than physical ram without the swap you couldn't? (Regardless that mmap is a lazy initializer). Feb 27, 2012 at 21:54
  • 6
    Yes, I'm sure my point about Solaris is still true. Even while your Jim Laurent's quote is true, i.e. Solaris doesn't demand swap, not having swap means all memory reservation (i.e. malloc) need to be backed by RAM, even while some of the allocated memory is not used. This is not related to large mmap or tmpfs, although tmpfs is also a reason why you might want to have swap with Solaris (and Linux too for that matter).
    – jlliagre
    Feb 28, 2012 at 7:38
  • 1
    Update for Linux: overcommiting can be turned off, OOM algorithm can be modified, you can even have your own OOM handler with cgroups.
    – peterph
    May 28, 2013 at 7:44
  • 2
    @peterph Turning off overcommitting on Linux make swap even less an anachronism. If you don't overcommit, you have to make sure you have a swap area large enough for all reservations to be backed.
    – jlliagre
    May 28, 2013 at 9:44
  • 1
    The virtual memory reserved by a fork depends on the size of the program doing it. Let say you have a java VM using 2 GB of memory forking, it will temporarily require 2 GB more. If this happen while you have less the 2 GB available or simultaneously multiple times, one or more fork will fail. This is a common situation with non over-committing OSes, and with Linux too when overcommitting disabled. It can be easily fixed by having a swap area large enough which IMHO is a quite better solution than memory overcommitment.
    – jlliagre
    May 29, 2013 at 20:22
5

I can't add to the discussion technically, but I can give a few examples. My old notebook (2GB RAM kunbuntu lucid) typically runs with swap at 0. When I run transmission (bittorrent client) with a number of torrents that can collectively be using 100 connections, my swap can go way up. It gets even worse when I have an XP vm running that uses 1GB real memory.

I have seen others comment that memory intensive processes like graphics rendering can also dip into swap. If you only do that occasionally, then it's not a issue.

As far as OOM problems, swap can actually be a lifesaver because it buys you time between identifying the problem and things going south. Lots of things use almost all my memory, so I don't pay any attention to that, but when swap starts running up I notice that and start looking for the problem - before it bites me.

2
  • Well yeah, legacy systems can't do much without swap enabled. I still have an old subnotebook with 256MB of RAM, where swap is requred to start pretty much any program. I believe the question targets modern systems though. Sep 21, 2015 at 10:43
  • It's not just legacy systems, there's a certain non reality to the assumption people run more than 4 GiB ram, and 4 GiB fall well within the use case Joe mentions, it's not just legacy hardware, the entire OP was a total strawman in my view. Plus of course, hybernating to swap is what I use for laptops always, avoids the constant battery drain of suspend to ram, and I'd use it on everything that supports it for the same reason.
    – Lizardx
    Feb 28, 2021 at 23:41
5

There's one very nice application for swap space: RAM extension by putting the swap space on storage device that uses RAM, to overcome limitations of installable system RAM

Have a look at this gadgest http://techreport.com/articles.x/16255 It basically a interface from S-ATA to DDR2-RAM. You can stuff up to 64GB of RAM into those. By placing swap space on one of those you're getting some significant additional RAM. Of course it's not as fast as regular system RAM. But it kind of turns the system RAM into sort of an additional cache layer.

4
  • 1
    Concidering its price ($549) wouldn't be more efficient to invest $100 in a mainboard supporting 64GB of RAM? Sep 21, 2015 at 10:27
  • 2
    @DmitryGrigoryev: Of course. But sometimes you're forced to use that particular kind of hardware (because for reasons cough medical system certification cough) but also have to deal with ridiculously large datasets produced in very little time (think tomography scanners, datarates >3GiB/s).
    – datenwolf
    Sep 21, 2015 at 13:42
  • Wouldn't you have to certify the RAM drive as a medical device as well in that case? ;) But yeah, I got the point. Sep 21, 2015 at 13:48
  • 2
    @DmitryGrigoryev: Indeed you have to do it. However certifying such a S-ATA RAM disk device is much, much easier than certifying a whole mainboard. When sourcing for computers used in medical equipment you usually buy as much components as possible certified off-the-shelf. For those parts where nothing with a certification readily available exists you then do the necessary tests and certification yourself. Especially when working in research, where the emphasis lies on patient safety and the data is not used for treatment planning this is the most cost effective and quickest solution. BT;DT.
    – datenwolf
    Sep 21, 2015 at 16:48
3

I know of one reason to keep swap around. I have an app that takes up as much memory as I can afford to configure for my system. It uses Hadoop, which at one part of the processing does a fork and exec to run a single unix command (I think "uname" or "user" or something that they couldn't find a Java equivalent for). It appears that java doesn't do a vfork with copy on write semantics like a native application would. If I start up my app using 4Gb of RAM, when it forks, the fork uses another 4Gb of RAM, but then quickly releases it. If I didn't have 4Gb of swap for that Hadoop to swap into, I would have to pay for 8Gb of RAM just to have 4Gb for my app.

2
  • This is a great point, but not a reflection of modern fork() - On Linux and FreeBSD (and, ostensibly OSX?) fork() is implemented through the use of copy-on-write pages. Copy-on-write (or COW) is a technique to delay or altogether prevent copying of the data. Rather than duplicate the process address space, the parent and the child can share a single copy. The data, however, is marked in such a way that if it is written to, a duplicate is made and each process receives a unique copy. Citations: forums.freebsd.org/showthread.php?t=26355 and Linux manpage for fork() Feb 27, 2012 at 20:32
  • While true, there are some pages that cannot be marked COW. For example, the pages used for the kernel stack of the new child process and the pages used for internal data structures (the files_struct, the struct signals, the task_struct, and others). Also, many executable pages are not position-dependent code (PIC) and thus pages of executable code that were modified by the dynamic loader (ld-linux.so) must have swap space reserved for them even if nothing is written to swap space immediately. That's why I love Linux; you can turn off swap and the system still runs. :)
    – Azhrei
    Jun 1, 2015 at 6:34
3

On my system, /tmp spills to swap if it gobbles too much RAM.

This is a lot faster than using a real filesystem for /tmp.

5
  • That's pretty dangerous - if I need ramfs, I specify in fstab (or options) to set the size explicitly. It's just as likely that a program can go ape-crap insane with memory allocation as it is that it will start creating files in /tmp. Swap would be a bad place for ramfs files to show up (especially if you're relying on ramfs for the speed) Feb 27, 2012 at 20:36
  • 2
    I exceed RAM size in there frequently. tmpfs backed by swap is significantly faster than ext2 even when spilling.
    – Joshua
    Feb 27, 2012 at 22:26
  • Useful to know - and will probably be a future research item to look at - I'd still be concerned about an application filling up my ram by proxy of tmpfs/ramfs in /tmp. That gives me the heebie jeebies! Feb 27, 2012 at 22:33
  • Then set the limit = size of swap.
    – Joshua
    Feb 27, 2012 at 22:42
  • Incidentally, this is the difference between ramfs and tmpfs. tmpfs can spill to swap while ramfs cannot.
    – Joshua
    Mar 7, 2012 at 20:03
3

I've been running Linux and Windows without swap (paging file, in Windows nomenclature), on notebooks/desktops with 4Gb or more. There are a few occasions when memory exhaustion happens, I just deal with them. I feel the system is snappier this way, which I care more about. No special requirements on my workload though.

Things I've learned:

  • Windows "loses" memory with time, in about 20-30 days of uptime I get to a point when I prefer to just reboot. I don't know why this happens. I'm guessing it may be either a leak in some driver or the anti-virus. When you have a paging file, I believe it can put this leaked memory to the paging file, so it would be harder to notice this issue on a regular Windows system.
  • Firefox deals way better with little memory than Chrome. Firefox warns you, and still runs, Chrome just crashes.
2

I think your arguments are quite valid for a server, where performance is important, and knowing which app will act next may not be predictable.

For a desktop however, I find swap useful when I am pushing and popping tasks.

For example, if I am working on a task using app A and then I discover I need to use app B for something (either a sub-task, or an interruption), then it is mentally easier for me to let A swap to disk while I work in B than to close A and then remember to start it again afterwards.

This is especially true if A is holding some unsaved state which would not be restored when it is restarted.

Whether it is faster to push and pull A to/from swap, or close and restart it, depends on the app. (Some manage to have a slow startup but a small residential size.)

However I would agree that a better solution to enhance productivity would be to install some additional RAM.

1
  • Update: After writing this answer, I owned a laptop with lots of RAM and a slow hard-drive. In that case my advice reversed! Here is a summary of pros and cons. Nov 4, 2019 at 2:40
1

There are a lot of reasons, when swap is used.

Usually, when the system has not enough physical memory, the kernel can put some applications (in fact - some parts of memory which is used by not running applications) to swap.

Later, when these applications should do something (for example, some data arrives on a socket or some timer fires) - the kernel will put some other application to swap.

Another example of swap usage is suspend to disk.

Concerning embedded devices, all of them can be divided on (at least) two big groups:

  1. they run Linux/Windows or similar non-RTOS (Real Time OS); or
  2. they run an RTOS.

Of course, there are devices running just some code (some kind of microcontrollers) etc. I would not describe them because such devices don't have any OS, so discussing swap is senseless for such devices.

The first group of embedded devices (running some OS) can use (and usually they use) the swap. And in general, such devices use swap in the same manner as desktops and servers.

The second group of devices (running RTOS) don't use swap at all, because RTOS has limitation to time to responding on event, and

  • reading from swap can take unpredictable time
  • devices have a predefined (at compile time) number of tasks it's not necessary to swap

BTW, there are a lot of description of how linux uses the swap, one of them is http://distilledb.com/blog/archives/date/2009/02/22/swap-files-in-linux.page
Windows use a similar approach.

1
  • Also, swap is needed for hibernation (suspend to disk) unless you're using something like TuxOnIce.
    – Renan
    Feb 27, 2012 at 21:17
1

It seems to me that both hibernation and hybrid sleep need swap space on Linux.

I never used swap space/partition on Linux until confronted with the need to use Hybrid Sleep - as sleep on critical battery level was not available on my system, as that was handled by Upower, which only choses between Shut-Down, Hibernate and Hybrid-sleep. (For more details see Suspend instead of shutdown on critical battery level?).

1

A few good uses I have seen are processes that use much memory, but not performance critical. One case was an ancient Firefox which had a bad memory leak. It would fill up RAM and spill over to swap with no ill effect. Another one we had was our recursive DNS sever (those rapidly build up a huge cache which is rarely used).

The other explanation I've seen about swap ran somewhat along the lines: "You are told to always configure SWAP = 2 * RAM. This is complete nonsense, there is no relationship between RAM and swap. Swap is to accomodate spikes in memory usage, you should add enough memory so that most of the time your load fits in RAM. If your load is stable, you don't need swap. If your load is highly variable, you need enough swap for the spikes, and arrange so that swap is used rarely enough so as not impact performance significantly overall. Summarizing, as you have no idea what your load spikes are, and as disk is so much cheaper than RAM, do configure SWAP = 2 * RAM."

Some old versions of Solaris couldn't use swap at all unless there was at least as much swap as RAM (I remember that it allocated fixed swap space for existing RAM or something like that), so 2 * RAM was really around the minimal sensible value. But that was eons ago, when our large machine had 64 MiB RAM and a 1 GiB disk...

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .