How to Clear RAM Memory Cache, Buffer and Swap Space on Linux

How to Clear RAM Memory Cache, Buffer and Swap Space on Linux

During the execution of any program or application, the system uses cache and buffer as temp data to improve program or application performance. Sometimes, the system runs out of memory due to many cached objects using a lot of RAM. In that case, we need to increase the Physical RAM and Swap memory, or we can instruct the kernel to clear the RAM memory cache, Buffer and Swap space.

Linux systems do not recommend clearing their memory cache, but it is safe to do so. Linux systems slow down when they purge the Memory cache since files can be read much faster from memory than persistent disk.

In today’s tutorial, we will learn how we can clear the RAM Memory cache, Buffer and Swap Space on the Linux operating system.

Clear Memory Cache

To check the Memory caches, run the following command.

free -h
Checking caches and buffer in RAM

In every Linux-based operating system, there are three ways to clear the memory cache.

  • To clear only Page Cache from the RAM.
sync; echo 1 > /proc/sys/vm/drop_caches
  • To clear only dentries and inodes from the RAM.
sync; echo 2 > /proc/sys/vm/drop_caches
  • To clear all the Memory caches, which include Page Cache, entries and inodes.
sync; echo 3 > /proc/sys/vm/drop_caches

This sync command synchronizes all the in-memory cache files with persistent storage. This is followed by a “;” to indicate that the next command will clear cache memory once the first command is triggered.

Note:- In a production environment, we do not recommend running a clear cache command, since it may result in data corruption or data loss. Be careful when using the above command.

Scheduling to Clear Memory Cache with Crontab

Cache memory can also be automatically flushed at regular intervals with a cron job. Use the following command in system crontab to automate this process.

Run the following command to open the crontab in edit mode.

crontab -e 

Add the following entries in the crontab file to flush the Memory Caches daily at 00:00.

0 0 * * *     sync; echo 3 | sudo tee /proc/sys/vm/drop_caches

Clear Swap Space

To clear Swap space, run the following command on the terminal.

swapoff -a && swapon -a

Conclusion

In today’s tutorial, we have learned how we can flush the Buffer, RAM Memory cache and Swap Space with just a few simple steps. On productions servers, we do not recommend running a clear cache command, since it may result in data corruption or data loss.

If you guys have any queries or questions, let me know in the comments section.