Monday, November 11, 2013

Linux SWAP Partition as twice the RAM size - why ?

Linux SWAP Partition as twice the RAM size - why ?


Linux divides its physical RAM (random access memory) into chucks of memory called pages. Swapping is the process whereby a page of memory is copied to the preconfigured space on the hard disk, called swap space, to free up that page of memory. The combined sizes of the physical memory and the swap space is the amount of virtual memory available.

Swapping is necessary for two important reasons. First, when the system requires more memory than is physically available, the kernel swaps out less used pages and gives memory to the current application (process) that needs the memory immediately. Second, a significant number of the pages used by an application during its startup phase may only be used for initialization and then never used again. The system can swap out those pages and free the memory for other applications or even for the disk cache.

To see a VPS machine with 512 MB of physical RAM and the ratio of SWAP space we can use free -m


The picture shows us that we have total of 490 MB of physical ram and twice the size of the SWAP memory on the hdd (which is not yet used) of 991 MB. As this server has small amount of free memory (only 76MB) I had to investigate further. I have used the HTOP utility to see the real memory consumer.


The process with the ID of 1310 is using some memory resources dynamically. We cannot see the real proccess name, because it is assigned to multiple instances of one application. To investigate further we should use the PID number to see which service is killing the VPS machine.

This can be done with the PMP command :  pmap -x 1310


The output shows us that the SAMBA libraries are attached to the PID. Simply stopping the SAMBA service I will free up some memory.


To get back on the inital question , I will try to have a short explanation of the SWAP size. The memory hirearchy presented to application by the Linux system is arranged in few levels:

  • Processor/CPU registers - bits in size
  • L1 Cache - kbits in size
  • L2 Cache - MBs in size
  • L3 cache - 100 of MBs in size
  • RAM - GBs in size
The data that is used in application loading is moved to RAM, and some of that data need the L3 cache also. The used application data is often moved to the faster L2 and L1 cache memory. As we can see the data is moved from the RAM up to the last CPU register table. In this order we can get that the SWAP data should be between 1.5 and 2 times the Actual RAM is. 
This is the main reason why we should create the SWAP twice the RAM. And applications should not allocate that data to other HDDs, especially large ones, because of the slow I/O operations. If your RAM is free then there is no use of swap partition.

Feel free to comment.

No comments:

Post a Comment