Serve stale content while the backend is offline

Configuring Varnish Cache to serve stale content is very useful for when your origin is unavailable. This behavior is achievable when running Varnish Cache as a reverse proxy within the Section Content Delivery Grid.

Prerequisites

Make sure you have an account on Section, and have selected Varnish Cache to run in your proxy stack.

Note: This guide will assumes Varnish Cache v6.0.1 or later, for older Varnish Cache versions please reach out to us at support@section.io and we can provide you with instructions to upgrade to newer Varnish Cache.

Set up

This guide assumes you know basic VCL and the flow of HTTP traffic through Varnish Cache.

Step 1 - Ignore background fetch errors

We will need to add logic within vcl_backend_response to ensure that errors from an unavailable origin do not replace successful responses already in the cache.

You will need to check for the backend response status of background fetches, for any “5XX” errors and return abandon.

sub vcl_backend_response {
    if (bereq.is_bgfetch && beresp.status >= 500 && beresp.status <= 599) {
        return (abandon);
    }

    // ...
}

Step 2 - Serve expired objects

Also within vcl_backend_response we will need to set the grace period for which expired objects will be allowed to be served from the cache. Varnish Cache will still request a new version from the origin when serving an expired object, but won’t wait before responding to the User-Agent.

sub vcl_backend_response {
    // ...

    set beresp.grace = 24h; // adjust this time period to suit your needs
}

Testing

You can test this logic, by enabling maintenance mode on your server which will serve some type of 500 error. Keep in mind if the request is not in the cache before your origin goes down, the end user will still receive an error.

To learn more about this functionality of Varnish Cache, see their official documentation.