Skip to main content

What is stopping Varnish and Drupal Pressflow caching anonymous users page views.

Every so often with Pressflow and Varnish you might find that your anonymous users aren't being cached via Varnish.

A quick way to see whether your anonymous pages are being served is to add some debugging headers to Varnish by adding some code like the snippet here to vcl_deliver()

sub vcl_deliver {
  if (obj.hits > 0) {
    set resp.http.X-Varnish-Cache = "HIT";
  }
  else {
    set resp.http.X-Varnish-Cache = "MISS";
  }
}

and hit them with:

curl -I http://yoururl.com

If you do that command twice and get a MISS both times then it is time to do a little debugging I usually open pressflow/includes/bootstrap.inc.

At the time of writing a function called drupal_session_commit() looks like this:

function drupal_session_commit() {
  global $user;
  if (empty($user->uid) && empty($_SESSION)) {
    if (drupal_session_started() && drupal_save_session()) {
      // Destroy empty anonymous sessions.
      session_destroy();
    }
  }
  else if (drupal_save_session()) {
    if (!drupal_session_started()) {
      drupal_session_start();
    }
    // Write the session data.
    session_write_close();
  }
}

I typically edit drupal_session_commit() and add some debug lines. For example:

function drupal_session_commit() {
  global $user;
  if (!empty($_SESSION)) {
    print "<pre>";
    print_r($_SESSION);
    print "</pre>";
  }
  if (empty($user->uid) && empty($_SESSION)) {
    // ...
  }
}

Whatever that block of code spits out to the top or bottom of the screen depending on your theme basically gives you variable names to grep the code for to find the offending module setting session variables that cause Drupal not to cache with Varnish.

I use a command like this to find Drupal code in modules where session_var_name is your offending variable:

cd $pressflow_root
find . |xargs grep session_var_name

If you are running against subversion feel free to use a slightly modified version:

cd $pressflow_root
find . |grep -v svn |xargs grep session_var_name

Of course it could be something else causing Varnish not to cache but I find it is normally contrib drupal modules using the session.