Varnish built-in VCL
The built-in VCL contains a set of rules that will be executed by default, even if they are not specified in your own VCL file. It is possible to bypass the built-in VCL by issuing a return statement in your VCL code.
The built-in VCL provides much of the safe-by-default behavior of Varnish, so be very careful if you decide to skip it.
The built-in VCL defines the behavior for various states of the Varnish Finite State Machine , each of which comes with its own subroutine. This tutorial will explain what the behavior in each of these subroutines means.
1. vcl_recv#
The vcl_recv subroutine is executed when Varnish receives a request from the client. Its VCL logic decides whether or not the request is considered cacheable.
Here’s a breakdown of that logic:
Don’t allow PRI requests#
When you receive a request that has the PRI request method, it means that an HTTP/2 request was received, whereas Varnish wasn’t configured to handle HTTP/2. This is not supposed to happen, and a HTTP 405 Method Not Allowed error is synthetically returned:
if (req.method == "PRI") {
/* This will never happen in properly formed traffic (see: RFC7540) */
return (synth(405));
}
Enforce the host header#
When a top-level HTTP/1.1 request is received that does not have a Host header, an HTTP 400 Bad Request error is returned. The rules of the protocol state that every HTTP/1.1 request should have a Host header:
if (!req.http.host &&
req.esi_level == 0 &&
req.proto ~ "^(?i)HTTP/1.1") {
/* In HTTP/1.1, Host is required. */
return (synth(400));
}
Invalid request methods#
There is a series of HTTP request methods that Varnish accepts. If request method doesn’t match this list, return(pipe) is executed:
if (req.method != "GET" &&
req.method != "HEAD" &&
req.method != "PUT" &&
req.method != "POST" &&
req.method != "TRACE" &&
req.method != "OPTIONS" &&
req.method != "DELETE" &&
req.method != "PATCH") {
/* Non-RFC2616 or CONNECT which is weird. */
return (pipe);
}
Piping means that Varnish no longer considers this an HTTP request. Instead, it just treats the data as TCP and shuffles the payload over the wire, without further interference. If dealing with HTTP requests, always consider using a pass instead of a pipe, as piping relinquishes your ability to manipulate the transaction in further steps, and your logs will be blind to the backend response.
Uncacheable request methods#
Varnish follows HTTP best practices. When it comes to caching, only idempotent requests may be cached. This means: request methods that don’t explicitly change the state of the resource.
As a result, GET and HEAD are the only two cacheable request methods:
if (req.method != "GET" && req.method != "HEAD") {
/* We only deal with GET and HEAD by default */
return (pass);
}
So if the request method is for example POST, the return(pass) logic will kick in, and you’ll be sent to the vcl_pass subroutine. Requests that end up in vcl_pass will bypass the cache, and will result in an uncacheable backend fetch.
Authorization headers and cookies are not cacheable#
Stateful content is hard to cache: because of personalization, a stateful request may cause too many cache variations of an object.
Varnish’s approach is a cautious and conservative one and that is reflected in the built-in VCL:
if (req.http.Authorization || req.http.Cookie) {
/* Not cacheable by default */
return (pass);
}
This means that any request containing a Cookie header, or an Authorization header will result in a return(pass), which bypasses the cache.
This is just the built-in VCL. If your use case requires caching even when cookies are present, you’ll have to write some custom VCL.
Cacheable content#
If your request uses a valid and ceacheable request method, if the request contains a Host header and there are no Cookie or Authorization headers, the request is cacheable and we can look it up in cache:
return (hash);
By performing return (hash);, the logic transitions to the vcl_hash subroutine where the object’s hash is composed and looked up in the cache.
2. vcl_pipe#
The vcl_pipe subroutine is reached when return (pipe) is called from another subroutine.
Piping means that Varnish no longer considers this an HTTP request. Instead, it just treats the data as TCP and shuffles the payload over the wire, without further interference. If dealing with HTTP requests, always consider using a pass instead of a pipe, as piping relinquishes your ability to manipulate the transaction in further steps, and your logs will be blind to the backend response.
Here’s the built-in VCL for vcl_pipe, which honestly isn’t that exciting:
sub vcl_pipe {
# By default Connection: close is set on all piped requests, to stop
# connection reuse from sending future requests directly to the
# (potentially) wrong backend. If you do want this to happen, you can undo
# it here.
# unset bereq.http.connection;
return (pipe);
}
3. vcl_pass#
When you reach the vcl_pass subroutine, it means that the requested content shouldn’t be served from cache. By calling return (pass); you reach this subroutine.
As you can see in the VCL code below, content will be directly fetched from the origin server:
sub vcl_pass {
return (fetch);
}
The response of a passed request will not be stored in the cache, whereas a regular cache miss would attempt to store the object in the cache.
4. vcl_hash#
When return (hash); is called in vcl_recv, the object’s hash key is composed in vcl_hash and eventually the hash is used to look the object up in the cache:
sub vcl_hash {
hash_data(req.url);
if (req.http.host) {
hash_data(req.http.host);
} else {
hash_data(server.ip);
}
return (lookup);
}
This subroutine will use the hash_data() function to add data the hash of the object that is requested.
By default a cached object is identified by the request URL and the Host header. This is reflected in the VCL code. The hash_data(req.url); function will add the request URL to the hash and if a Host header is found, the hash_data(req.http.host); function will ensure that the Host header is also added to the hash.
In the unlikely case that no Host header is found, the hash_data(server.ip); function will add the server IP to the hash instead.
Once the hash is composed, return (lookup) is used to look the object up in the cache. When the result is a cache hit, we transition to vcl_hit. In case of a cache miss, we transition to vcl_miss.
5. vcl_purge#
When content needs to be removed from the cache, you can call return (purge); in your VCL code to make it happen. However, the built-in VCL doesn’t provide a standard way to do this.
Unless you implement custom purging logic, the following VCL code will be isolated:
sub vcl_purge {
return (synth(200, "Purged"));
}
What we learn from the vcl_purge implementation is that a synthetic HTTP 200 Purged response is returned to the client. The output template for this synthetic output is defined in vcl_synth.
6. vcl_hit#
The use case for the vcl_hit subroutine is pretty obvious: dealing with a cache hit.
Here’s the VCL code:
sub vcl_hit {
if (obj.ttl >= 0s) {
// A pure unadulterated hit, deliver it
return (deliver);
}
if (obj.ttl + obj.grace > 0s) {
// Object is in grace, deliver it
// Automatically triggers a background fetch
return (deliver);
}
// fetch & deliver once we get the result
return (miss);
}
What we learn from this code is that the built-in VCL doesn’t return a cache hit unconditionally. When an object is found in the cache, Varnish will check the freshness and decide how to deliver the object.
Fresh content#
As long as the remaining TTL of an object, represented by the obj.ttl variable, is greater than zero, the content is considered fresh:
if (obj.ttl >= 0s) {
// A pure unadulterated hit, deliver it
return (deliver);
}
This means the cached object can be immediately delivered to the requesting client. The return (deliver); statement will trigger this behavior and will cause a transition to the vcl_deliver subroutine.
Stale content#
When the content has expired and the remaining TTL is no longer greater than zero, the obvious outcome would be a cache miss. But if the object has grace time left, Varnish will serve the stale content while asynchronously fetching the content from the origin web server:
if (obj.ttl + obj.grace > 0s) {
// Object is in grace, deliver it
// Automatically triggers a background fetch
return (deliver);
}
Grace can be configured by overriding the default_grace runtime parameter, by setting the beresp.grace value in VCL, or by using the stale-while-revalidate directive in a Cache-Control header.
And when the object becomes out of grace , a synchronous fetch is done through return (miss):
// fetch & deliver once we get the result
return (miss);
7. vcl_miss#
The vcl_miss subroutine is pretty straightforward: it is accessed when the requested object couldn’t be found in the cache or when the object has expired and is out of grace.
When a cache miss occurs, the content will be fetched from the origin server through the return(fetch) statement. This results into a transition to the vcl_backend_fetch subroutine.
Here’s the built-in VCL code for the vcl_miss subroutine:
sub vcl_miss {
return (fetch);
}
8. vcl_deliver#
The vcl_deliver subroutine is used to return the HTTP response to the requesting client.
Whether a cache hit, cache miss, cache pass or synthetic response takes place, vcl_deliver is responsible for delivering the content to the client.
Here’s the built-in VCL code for the vcl_deliver subroutine:
sub vcl_deliver {
return (deliver);
}
9. vcl_synth#
Not all content returned by Varnish originates from the origin server. In certain cases Varnish will return output that it generated itself. We call these synthetic responses.
Whenever you call return(synth(...));, you transition directly to the vcl_synth subroutine where the response template is composed.
The return(synth(...)); statement requires a status code and an optional response reason.
In the case of return (synth(405)); a synthetic HTTP 405 Method not allowed response is returned. If you add a second argument to synth(...) you can override the reason phrase.
Here’s the built-in VCL code for the vcl_synth subroutine:
sub vcl_synth {
set resp.http.Content-Type = "text/html; charset=utf-8";
set resp.http.Retry-After = "5";
set resp.body = {"<!DOCTYPE html>
<html>
<head>
<title>"} + resp.status + " " + resp.reason + {"</title>
</head>
<body>
<h1>Error "} + resp.status + " " + resp.reason + {"</h1>
<p>"} + resp.reason + {"</p>
<h3>Guru Meditation:</h3>
<p>XID: "} + req.xid + {"</p>
<hr>
<p>Varnish cache server</p>
</body>
</html>
"};
return (deliver);
}
The standard output template that is created in vcl_synth sets the following headers:
Content-Type: text/html; charset=utf-8Retry-After: 5
The resp.status variable is based on the first argument of synth(..). When return(synth(405)) is called, resp.status will equal 405.
When return(synth(200, "Purged")); is called from the vcl_purge subroutine the resp.status variable is 200 and the resp.reason variable is Purged. The HTML output for this call would be the following:
<!DOCTYPE html>
<html>
<head>
<title>200 Purged</title>
</head>
<body>
<h1>Error 200 Purged</h1>
<p>Purged</p>
<h3>Guru Meditation:</h3>
<p>XID: 123456</p>
<hr>
<p>Varnish cache server</p>
</body>
</html>
It makes sense to override the vcl_synth output template in your own VCL file. You can actually load a synthetic output template from a file
10. vcl_backend_fetch#
The vcl_backend_fetch subroutine is a backend side subroutine that is only called when the object cannot be served from the cache. This happens when a cache miss occurs or when requests bypasses the cache.
This is reflected in the built-in VCL: both vcl_miss and vcl_pass will perform a return(fetch), which triggers vcl_backend_fetch.
vcl_backend_fetch will convert the request, represented by the req object, into a backend request, respresented by the bereq object.
Here’s the built-in VCL code for vcl_backend_fetch:
sub vcl_backend_fetch {
if (bereq.method == "GET") {
unset bereq.body;
}
return (fetch);
}
Besides the return(fetch); there’s not a lot happening. The only interesting thing is the fact that the request body is removed for GET requests.
11. vcl_backend_response#
When your origin server responds to a backend request issued by vcl_backend_fetch, you reach the vcl_backend_response subroutine. This backend side subroutine provides access to the backend response through the beresp object and also contains rules to decide whether or not the backend response should be stored in the cache.
Here’s the built-in VCL code for the vcl_backend_response subroutine:
sub vcl_backend_response {
if (bereq.uncacheable) {
return (deliver);
} else if (beresp.ttl <= 0s ||
beresp.http.Set-Cookie ||
beresp.http.Surrogate-control ~ "(?i)no-store" ||
(!beresp.http.Surrogate-Control &&
beresp.http.Cache-Control ~ "(?i:no-cache|no-store|private)") ||
beresp.http.Vary == "*") {
# Mark as "Hit-For-Miss" for the next 2 minutes
set beresp.ttl = 120s;
set beresp.uncacheable = true;
}
return (deliver);
}
