DEV Community

Rafael Bernard Araújo
Rafael Bernard Araújo

Posted on • Originally published at rafael.bernard-araujo.com on

Setting up maintenance mode with Varnish

Varnish is "the free, open-source software that enables super fast delivery of HTTP or API based content", "an HTTP reverse proxy that works by caching frequently requested web pages, so they can be loaded quickly without having to wait for a server response.".

If you need some sort of an alternative cloud or servers in datacenter Varnish can act as CDN, Load Balancer and Api Gateway layers at the same time. It is very powerful when you have to manage those services instead of using a Cloud service. And this is not that uncommon.

How Varnish works

Consider the use case where you need a maintenance window for a product for which you need to be sure that you are suspending all connections to the backend servers consistently. Performing a redirection in the CDN layer is the better choice.

The Varnish Configuration Language (VCL) is a domain-specific programming language used by Varnish to control request handling, routing, caching, and several other aspects.

-- https://www.varnish-software.com/developers/tutorials/varnish-configuration-language-vcl/

This is a very powerful language, that, for our use case, will allow creating a synthetic response to proxy the request to, instead of hitting the backends. There will be no need to create a web directory to be served for another web server, but just directly from Varnish.

Varnish serving maintenance synth response

# default.vcl
sub vcl_synth 
{
    # previous headers manipulation if you like
    # and other code that you need for synth if you like
    # (...)

    # Adding an x-cache header to indicate this is a synth response
    set resp.http.x-cache = "synth synth";

    # Maintenance - we are calling the status for this synth 911 because we can have different synths
    if ( resp.status == 911 ) {
        set resp.http.Content-Type = "text/html; charset=utf-8";
        # You can put absolutely what you want
        synthetic ({"
<html>
<head>
    <title>Maintenance mode - Try again later</title>
</head>
<body>
<h1>This website is under maintenance.</h1>
</body>
</html>
"});
        return (deliver);
    }
}
Enter fullscreen mode Exit fullscreen mode

Then I can forward everything that requests my-domain.com to the maintenance

# includes/my-domain-hints.vcl

if ( req.http.host ~ "my-domain.com" ) {
    return(synth(911, ""));
    # All the other VCL configs are below here, but we are returning early above to the maintenance
    # (...)
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)