Load balancing with Varnish

Varnish has a built in load balancer. Use this if you have more then one origin server. Using this is quite easy. You start up by declaring more then one backend server. We add a probe object to each backend to let varnish check the health of the objects.

backend foo {
  .host = "foo.example.com";
  .probe = {
                .url = "/";
                .interval = 5s;
                .timeout = 1 s;
                .window = 5;
                .threshold = 3;
  }
}

backend bar {
  .host = "bar.example.com";
  .probe = {
                .url = "/";
                .interval = 5s;
                .timeout = 1 s;
                .window = 5;
                .threshold = 3;
  }
}

Here we have two, foo and bar. The probe specifies that Varnish should fetch the / object every 5s. If it takes more then a second it is considered a failure. If more then 3 out of the 5 last probes are OK the backend is considered healthy. For details on health checking see the backend health polling page.

Now these two backends need to be wrapped in a single logical director, sort of a virtual backend. Lets call it baz.

director baz round-robin {
        {
                .backend = foo;
        }
        {
                .backend = bar;
        }
}

Thats it, really. The keyword round-robin indicates that requests will be distributed among the backends in a round-robin fashion. Currently there also exists a random director. You can probably guess how it works. :-)

You can send traffic to your brand new director in vcl_recv, like this:

sub vcl_recv {
   if (req.http.host ~ "^(www.)?mysite.com$") {
       set req.backend = baz;
   }
}

There are more options documentet on the VCL manual page.