Clearing the cache from memory

Linux has a supposedly good memory management feature that will use up any “extra” RAM you have to cache stuff. This section of the memory being used is supposed to be freely available to be taken over by any other process that actually needs it, but unfortunately some Linux distros think that cache memory is too important to move over for anything else that actually needs it.

I have 16 GB RAM in my Server. Whenever there is no cache being stored in the memory (i.e. when I first boot / restart the server), response time is great. But as soon as it fills up with cache, my server response is terrible.

Up until kernel 2.6.15 there was no way to clear the cache from memory except to restart the server. However, it is not desirable to restart the server as it would affect the user more important it will affect the business.

Luckily from kernel 2.6.16 onwards tunable was added. Hence, simply run the following command as root will clear out the cache from memory.

# sync
# sysctl -w vm.drop_caches=3
# free

Writing to vm.drop_caches will cause the kernel to drop clean caches, dentries and inodes from memory, causing that memory to become free.

To free pagecache:

# sysctl -w vm.drop_caches=1

To free dentries and inodes:

# sysctl -w vm.drop_caches=2

To free pagecache, dentries and inodes:

# sysctl -w vm.drop_caches=3

As this is a non-destructive operation, and dirty objects are not freeable, you should run “sync” first in order to make sure all cached objects are freed.

Be the first to comment

Leave a Reply

Your email address will not be published.


CommentLuv badge