Chapter 6. Dealing with Backends

Although the strategy is to minimize the use of the backend, it is still a crucial part of the equation. Without the backend, we cannot cache any objects, and preferably it’s the backend that decides what gets cached and how long objects are stored there.

In this chapter, we’ll talk about backends and how you can configure access to them using VCL. We’ll also group backends and perform load balancing using directors. Dealing with healthy and unhealthy backends will also be covered in this chapter.

Backend Selection

In previous chapters, I mentioned that there are two ways to announce the backend to Varnish:

  • By adding a backend to your VCL file.

  • Or by omitting VCL completely and using the -b flag at startup time.

That’s how you do it automatically. But there are situations where there are multiple backends and you want to control which request goes to which backend. You can define multiple backends and use req.backend_hint to assign a backend other than the default one.

Here’s an example:

vcl 4.0;

backend public {
  .host = "web001.example.com";
}

backend admin {
  .host = "web002.example.com";
}

sub vcl_recv {
    if(req.url ~ "^/admin(/.*)?") {
        set req.backend_hint = admin;
    } else {
        set req.backend_hint = public;
    }
}

You notice that we defined two backends:

  • A backend that handles the public traffic and that resides on web001.example.com.

  • A backend that serves the admin panel and that resides on web002.example.com.

By incorporating the req.backend_hint ...

Get Getting Started with Varnish Cache now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.