Search code examples
varnishvarnish-vclvarnish-4

Increase varnish grace time while backend is sick


We use Varnish Cache as a Frontend to a lot of our customers and we server stale content by grace while any backend is sick.

We do now have a failed backend and we want to increase the grace period (while it's sick), is that a possible scenario? I tried digging in docs and found nothing.

Varnish 4


Solution

  • Serving outdated content in Varnish Cache 4.x when a backend in sick is a common use cache. You simply need to implement your own vcl_hitsubroutine. The idea is caching contents using a high grace value (e.g. 24 hours), but limit grace to a small time window (e.g. 10 seconds) when your backend is healthy:

    sub vcl_hit {
        if (obj.ttl >= 0s) {
            # Normal hit.
            return (deliver);
        }
    
        # We have no fresh fish. Lets look at the stale ones.
        if (std.healthy(req.backend_hint)) {
            # Backend is healthy. Limit age to 10s.
            if (obj.ttl + 10s > 0s) {
                return (deliver);
            } else {
                # No candidate for grace. Fetch a fresh object.
                return(fetch);
            }
        } else {
            # Backend is sick. Use full grace.
            if (obj.ttl + obj.grace > 0s) {
                return (deliver);
            } else {
                # No graced object.
                return (fetch);
            }
        }
    }
    

    For further information please check: