This week’s episode is about VCL — the Varnish Configuration Language — which is used to define your own caching policies in Varnish Cache and Varnish Enterprise, and the number one feature in Varnish.
Varnish Configuration Language (VCL) is a DSL, a domain-specific language, meaning it can only be used within the context of Varnish.
It is a curly braces style language, which makes it similar to languages like C and Java. But unlike these languages, VCL is not a top-down programming language. Instead, it extends standard behavior to a predefined set of subroutines, and these subroutines reflect the flow of the built-in finite state machine. The code itself gets translated into C code and eventually compiled to machine code when Varnish starts.
The purpose of VCL is:
- request handling
- requests routing
- response manipulation
- backend selection
- controlling the cash
- decision making
The benefits of VCL are that is extremely powerful and fast, and that is thanks to its architecture, its very narrow scope, and the fact that code gets translated into C. It is also tremendously flexible when you compare it to a simple configuration file; you get a full-blown programming language where the flexibility is second to none and that is thanks to the rich syntax of VCL and the ecosystem of modules (VMODs) that allow you to do things that aren't possible in standard VCL.
Allow us to throw in a code example:
vcl 4.1;
backend default {
.host = "backend.example.com";
.port = "80";
}
sub vcl_recv {
if(req.url ~ "^/admin(/.*)?") {
return(pass);
}
}
It all starts with the VCL version label, in this case, it's version 4.1 but in no way reflects the version of Varnish itself. This is the latest version 4.0 and it's perfectly compatible with the latest version of Varnish.
We also need to define a backend. This is the server that Varnish connects to when content is not stored in the cache and needs to be fetched. We define host and port properties, and there are many other optional parameters to tune. In this very specific example we will hook into the VCL receive subroutine which is called in the finite state machine when requests are received from a client. So in this case we're evaluating the request URL, and matching it to a specific regular expression pattern. If the regular expression matches admin or support and resource of admin, we decide not to cache.
Check out our video next week for more tech information about VCL. And in the meantime here are a few resources to keep you busy: