Jun 3, 2016 - John Entwistle

Using a Drupal Ajax Form with Varnish HTTP Cache


The Varnish HTTP cache is truly an amazing bit of software that can help take the performance and responsiveness of your high-traffic website to the next level. According to the developers behind Varnish, the reverse-proxy cache can speed up page delivery by a factor of at least 300 times that of a similar server that doesn’t use Varnish to serve cached HTML. Varnish is highly configurable yet fairly simple to install and set up for most use cases, making it an ideal addition to any high-performance web platform.

Drupal developers may have encountered some woes when adding Varnish to their stack, however, such as the need to integrate a method of purging nodes and other pages when critical content is added or updated – for example, adding a breaking story to the homepage of a news outlet. One lesser-known hangup comes into play when Varnish is used to cache a page containing a Drupal FAPI form that uses ajax to validate or submit. Within both Drupal 7 and Drupal 8, all forms are cached for a hard-coded timespan of six hours. If the page containing your ajax form is cached for longer than six hours, Varnish will continue to serve form markup containing a stale form build ID, which will inevitably cause submissions to fail with no indication or work-around for the end user.

Fear not, however! With the help of one of the several modules which integrate Drupal with a Varnish cache server, it is possible to force the URLs of your pages containing an ajax form to be purged from the HTTP cache – before the form build ID expires – thereby avoiding the problem altogether. Perhaps the most straightforward way to achieve this is to use a Drupal module like Advanced Page Expiration to send an alternative cache-lifetime header that is shorter than your default (and shorter than the six-hour form-cache lifetime). Another option is to leverage the Purge module and force the necessary URLs to be removed from the cache upon a specific event such as when page content is updated, during a cron run, or perhaps even upon an unsuccessful form submission due to an invalid form build ID (although this would have the obvious downside of allowing at least one submission to fail). The Purge module also has several versions in the works for Drupal 8, so it’s a good choice if you’re using the latest and greatest Drupal.