Take care of your cache_form table

Submitted by exaboy on Sat, 02/25/1961 - 22:06
Take care of your cache_form table

Little too often I come across a cache_form table that is bursting at the seams, not from anything bizarre, although that actually happens a lot, rather simply because developers lose track of its intended purpose and id like to think they inadvertently abuse it. With a bit of initiative i've witnessed 79GB cache_form tables reduce to 16GB saving their business from the need to upsize disks and threaten stability

But why is this a problem in the first place? Good question. The cache_form table isn't really a cache table at all when you compare it with the other cache tables Drupal utilises. This table is poorly named since its purpose is to preserve the form state as it was when the user last submitted the form. Now, as you can imagine on most modern websites forms are used all over the place, and you guessed it they all have respective cache_form entries.

Ugh, what make this a real issue is that Drupal does not manage this table at all! It just continues to push content into the table like there is no tomorrow. This problem is not new, its been around since Drupal 6 (http://drupal.org/node/226728) where the cache_forms table isn't cleared when the items are expired and what is more incredible simply running cron doesn't help either!

You can truncate the cache_form table, however this has the possible side-effect of dropping forms that might be in the process of being submitted. To remediate such an issue with your cache_form table firstly look at the areas of your sites that have forms and are contributing to the problem. The second part is to regularly purge stale entries, something along the lines of the following should suffice:

DELETE FROM {cache_form} WHERE expire < now();

A more elegant solution would be to implement a hook_cron method which does the heavy lifting for you, like such:

mymodule_cron() { cache_clear_all(NULL, 'cache_form'); }

During this purging process the entries which are not older than 6 hours will not be deleted, which is ideal, but 6 hours is a long time, where is this defined? We can identify the issue here in the source:https://api.drupal.org/api/drupal/includes!form.inc/function/form_set_cache/7, this can be a real problem.

function form_set_cache($form_build_id, $form, $form_state) { // 6 hours cache life time for forms should be plenty. $expire = 21600;

As the comment reads they are assuming it should be plenty and in likely your case 6 hours is far too long. So the trick is to clear the cache_form table more frequently and patch the value of $expire to a lower value. Remember patching core is not cool, but its perfectly acceptable if done correctly and responsibly.