Prune any cache directory using cron (prune Magento cache/sessions)

Over the weekend, I received a “low storage space” alert for a client’s server, a Magento-based web store.  Problem: /: Disk space is critically low (used > 90%)

Upon investigation, the culprit was a Magento caching plugin that accumulated 62GB of cached data. The plugin was useful but did not invalidate or rather remove old files. In addition, there were saved sessions that amounted to over 3 million session files because of an application-specific setting.

 Pruning Magento Cache & Sessions Using Cron

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

 

Pruning Magento Cache and Sessions

Once I pruned the cache, the issue was resolved. However, what would prevent the cache from again growing large enough that the issue would return? In a case like this, it’s recommended that you implement a scheduled task (cron job) to delete files older than x. With that approach, the issues above were resolved without any noticeable performance hit when the cache was pruned.

I ended up using something the bash script below, then adding that to cron jobs:

#!/bin/sh
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 +3 -exec rm -f {} \;
find /var/www/html/var/tmp/ -mtime +1 -exec rm -f {} \;

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

The above lines will prune cached files older than 2 hours, session files older than 2 hours, report files older than 3 days and temp files older than 1 day. This keeps the cache & session files below millions of files.

It was set to run hourly, 5 mins past the hour:

5 * * * *

Make sure your Magento cookie (session) timeout is shorter than the prune TTL. In this case, Magento’s cookie timeout is set to 1 hour (PHP’s default is 24 minutes), so pruning files older than 2 hours won’t delete any active sessions!

I hope this helps. Please add your solution to this issue if different.

 

Published: August 30th, 2013 | Updated: January 4th, 2023

Tags: ,

Be the first to post a comment.