GadElKareem

Varnish 5.1 always online

Recently I posted about Varnish with secure AWS S3 bucket as backend and I wanted to have the “always online” enabled, meaning you can take the backend offline while serving from Varnish cache.

Here is how it works for Varnish 5.1:

vcl 4.0;

backend example {
  .host = "1.2.3.4";
  .port = "80";
}

sub vcl_backend_response {
    //override page cache. Comment it out to allow backend to override it
    set beresp.ttl = 10s;
    //use the cached version of the page for up to a week long if backend is down
    set beresp.grace = 1w;
    //also hide 500+ errors and serve healthy cache instead
    if (beresp.status >= 500 && beresp.status <= 599) {
        return (abandon);
    }
}

sub vcl_hit {
   if (obj.ttl >= 0s) {
       // normal delivery
       return (deliver);
   }
   if (obj.ttl + obj.grace > 0s) {
       // Object is in grace, deliver it and try a fetch in the background
       return (deliver);
   }
   return (miss);
}