Pruning Magento Cache & Sessions Using Cron

Note: Magento 1.x only. Over the weekend a client contacted me because they had serious performance issues with their Magento based store. The three main issues were:

  1. Checkout taking more than 30 seconds to complete after clicking to submit payment. (Causing double orders/payments and users just leaving the store)
  2. Login to the front or back end taking excessively long.
  3. Slow importing of new products and timeouts.

Upon investigation I narrowed down the issues to Magento’s Cache. Magento 1.* caches heavily but does not always remove invalidated files. In addition, Magento had saved sessions that amounted to well over 3 million files.

 Pruning Magento Cache & Sessions Using Cron

Also read: MySQL Performance: Stop hoarding. Drop unused MySQL databases


Pruning Magento Cache and Sessions

Once I purged cache the issue was resolved. However, it took less than 24 hours for the cache to again grow large enough that the issues returned. In a case like this it’s recommended that you implemented a balanced approach by setuping up an hourly cron script to delete files older than x. With that approach, the issues above were resolved without any noticeable performance hit when cache is pruned, instead of purged.

The script I ended up using was:


find /var/www/html/var/cache/ -type f -mmin +120 -exec rm {} \;
find /var/www/html/var/session/ -type f -mmin +120 -exec rm {} \;
find /var/www/html/var/report/ -mtime +7 -exec rm -f {} \;
find /var/www/html/var/tmp/ -mtime +1 -exec rm -f {} \;

* Change your path and run as root. (test first manually).

This method Prunes Magento’s cached files older than 2 hours, session files older than 2 hours, report files older than 7 days and tmp files older than 1 day. This now keeps the cache & session files below millions of files which avoids storage I/O bottlenecks.

Make sure your Magento cookie (session) timeout is set shorter than the prune TTL. In this case, Magento’s cookie timeout is set to 1 hour so pruning files older than 2 hours won’t delete any active sessions! This server also uses Varnish FPC and APC for opcode PHP Opcache and Magento caching.

Hope this helps another Magento admin. Please add your solution to this issue if different.


Last Updated: May 22nd 2019

Tags: ,