June 17, 2012, 10:14 PM — When your Linux server starts feeling sluggish, you might benefit from looking at your swap space and gauging whether it's adequately sized for your system's workload. Fortunately, Linux has some handy commands for helping you get a good picture of your system's behavior.
Setting your swap space to be twice the size of your RAM is a good rule of thumb, but systems with very large amounts of memory likely won't likely need anywhere near that amount of swap. Besides, adding it later is easy if you have adequate disk space.
Before we get started with the commands, let's review how swap space is used on Linux systems. Linux uses what is called a "demand-paged virtual memory system". This means that it breaks memory into chunks which are called "pages". Imagine the squares on a chess board, each square being a page and the entire board being your memory. To see how big each of these pages is, use the getconf PAGESIZE command. You will see something like this:
$ getconf PAGESIZE 4096
The pages on this particular Linux system are 4 KB in size. That's fairly typical.
When some process on a Linux system needs more memory, the pager will swap out (i.e., move from memory to swap space) some pages that haven't been used in a while. These pages can be moved back into memory when they're needed.
Demand paging can be contrasted with anonymous paging in which, once modified, pages must remain in RAM until the associated processes have run to completion and anticipatory paging in which a process's non-resident pages are preloaded into memory if they are likely to be referenced soon. No, it's not psychic, it's just a good algorithm for predicting the behavior of your executables.
If you suspect that your system may be having problems because of inadequate swap space, it's a good idea to track how swap space is being used. One way to do this is by using the sar command (part of the sysstat package) to collect performance data and then to remember to examine it from time to time. A cron job like this will collect performance statistics every 15 minutes between 8 AM and 6 PM Monday through Friday:
*/4 8-18 * * 1-5 /usr/lib/sysstat/sa1 -d 240 1
Some systems are preconfigured to collect performance information with sar. Check the contents of your /var/log/sa directory for files like these.