- Varnish built-in VCL·续
- Hit-for-miss#
- Immediately deliver uncacheable content#
- Zero TTL#
- Don’t cache responses with Set-Cookie headers#
- Surrogate-Control no-store#
- Cache-Control no-cache, no-store & private#
- Don’t peform wildcard cache variations#
- Cached content#
- 12. vcl_backend_error#
- 13. vcl_init#
- 14. vcl_fini#
- 15. Built-in VCL code#
Varnish built-in VCL·续
We will break down the code and explain the various aspects in the next sections.
Hit-for-miss#
A key aspect in vcl_backend_response is deciding whether or not HTTP responses can be stored in the cache. Depening on specific HTTP response headeres we can decide not to cache.
Instead of just not deciding to store the object in cache, we actually cache the decision not to cache. We keep track of uncacheable objects to ensure that the next request for this HTTP resource will not try to add the request to the waiting list for request coalescing purposes.
Because we know ahead of time that the response is not cacheable, the request will never be satisfied by request coalescing. Adding requests for uncacheable content to the waiting list will trigger serialization , which means waiting list items are processed serially rather than in parallel. This can result in a major performance degradation as the waiting list grows.
By storing uncacheable responses as Hit-For-Miss objects, we can bypass the waiting list and immediately fetch the content from the origin server. We do this through set beresp.uncacheable = true;.
And because set beresp.ttl = 120s; is set, a Hit-For-Miss object will be available for 2 minutes. After that the cacheability of the response is re-evaluated . Hit-For-Miss objects are also invalidated when the next backend response is considered cacheable.
It is important to set a long enough Time To Live. If you set beresp.ttl to zero, the Hit-For-Miss information is lost, the next request can end up on the waiting list, and serialization may occur. Never set beresp.ttl to zero is the lesson here.
Immediately deliver uncacheable content#
The built-in VCL for vcl_backend_response checks the bereq.uncacheable variable. If a return(pass) occured or the object was marked as Hit-For-Miss , the backend response is immediately delivered to the client, without evaluating the cacheability of the response.
Here’s the VCL code that illustrates this:
if (bereq.uncacheable) {
return (deliver);
}
Zero TTL#
When Varnish receives a response from the backend and it receives headers that would imply a zero TTL , the built-in VCL will decide to create a Hit-For-Miss object for this with a lifetime of 2 minutes. As mentioned earlier, this will ensure the waiting list is bypassed and the request is directly sent to the origin server.
Here’s a simplified version of the VCL that illustrates this:
if (beresp.ttl <= 0s) {
# Mark as "Hit-For-Miss" for the next 2 minutes
set beresp.ttl = 120s;
set beresp.uncacheable = true;
}
Any Cache-Control header containing a zero TTL or an Expires header with a timestamp in the past will result in beresp.ttl to be zero. Here are some examples of such headers:
Cache-Control: max-age=0Cache-Control: s-maxage=0Expires: Wed, 29 Sep 2021 15:36:22 GMT
Don’t cache responses with Set-Cookie headers#
When a Set-Cookie header is set by the origin, it implies a state change. This means we should not cache this response, because we would risk setting this cookie value for all users hitting this cached object.
Here’s the simplified VCL code that also creates a Hit-For-Miss object:
if (beresp.http.Set-Cookie) {
# Mark as "Hit-For-Miss" for the next 2 minutes
set beresp.ttl = 120s;
set beresp.uncacheable = true;
}
Surrogate-Control no-store#
Because Varnish supports HTTP surrogates, the built-in VCL respects the Surrogate-Control header. If it contains a no-cache value, Varnish will not cache that response and will create a Hit-For-Miss object.
Here’s the simplified VCL code for this:
if (beresp.http.Surrogate-control ~ "(?i)no-store") {
# Mark as "Hit-For-Miss" for the next 2 minutes
set beresp.ttl = 120s;
set beresp.uncacheable = true;
}
Cache-Control no-cache, no-store & private#
If no Surrogate-Control header is set, the built-in VCL will consider the Cache-Control header and look for directives that imply uncacheable behavior.
Directives like no-cache, no-store or private would indicate that the resource is not cacheable.
Here’s the simplified VCL code that checks for these directives:
if (!beresp.http.Surrogate-Control &&
beresp.http.Cache-Control ~ "(?i:no-cache|no-store|private)") {
# Mark as "Hit-For-Miss" for the next 2 minutes
set beresp.ttl = 120s;
set beresp.uncacheable = true;
}
So if the following HTTP response header would appear, the built-in VCL will not cache the response and will create a Hit-For-Miss object:
Cache-Control: private, no-cache, no-store
Variations of this header that included either no-cache, no-store or private would result in the same behavior.
Keep in mind that the Cache-Control header’s max-age and s-maxage directives are used to determine the TTL and that the cache is already bypassed when either of these directives would result in a zero TTL
Don’t peform wildcard cache variations#
The Vary HTTP response header is used to instruct caches to create a cache variation for each object, based on the value of that header. The Vary header’s value must be a valid request header.
If for example Varnish receives a response containing the Vary: Accept-Language header, it will create a cache variation for this based on the value of the Accept-Language header.
This is delicate balancing act between offering enough cache variations per cached resource and maintaining a high enough hit rate.
However if your origin server returns Vary: * to create cache variations based on every request header, then the built-in VCL will decide not to store this resource in cache. A Hit-For-Miss object will be created to mark this object as uncacheable.
Here’s the simplified VCL code for this behavior:
if (beresp.http.Vary == "*") {
# Mark as "Hit-For-Miss" for the next 2 minutes
set beresp.ttl = 120s;
set beresp.uncacheable = true;
}
Cached content#
If after all these checks your response didn’t result in the creation of a Hit-For-Miss object, we can conclude that the response is cacheable.
The object will be stored in the cache and will contain either the standard TTL, or a TTL that was assigned by the origin server through a Cache-Control or Expires header.
If the next client request takes place within the lifetime of the object, what was originally a cache miss , will now become a cache hit.
12. vcl_backend_error#
The vcl_backend_error subroutine is reached when an attempt to fetch content in vcl_backend_fetch fails, or when the response from vcl_backend_response is considered erroneous.
Just like vcl_synth, the vcl_backend_error subroutine will prepare a synthetic output template using HTTP status information.
Here’s what the VCL code looks like and it’s remarkably similar to vcl_synth:
sub vcl_backend_error {
set beresp.http.Content-Type = "text/html; charset=utf-8";
set beresp.http.Retry-After = "5";
set beresp.body = {"<!DOCTYPE html>
<html>
<head>
<title>"} + beresp.status + " " + beresp.reason + {"</title>
</head>
<body>
<h1>Error "} + beresp.status + " " + beresp.reason + {"</h1>
<p>"} + beresp.reason + {"</p>
<h3>Guru Meditation:</h3>
<p>XID: "} + bereq.xid + {"</p>
<hr>
<p>Varnish cache server</p>
</body>
</html>
"};
return (deliver);
}
This VCL code sets the following response headers:
Content-Type: text/html; charset=utf-8Retry-After: 5
The beresp.status variable contains the HTTP status code that was returned by the origin server when the error was triggered. When a Varnish backend fetch failed, the beresp.status value will be 503.
The resp.reason variable is contains the reason phrase for the corresponding error. It is either returned by the origin server, or it is Backend fetch failed when Varnish failed to fetch content.
The bereq.xid will contain the transaction id which can be looked up in the Varnish Shared Memory Logs.
Here’s an example of HTML output that is returned by vcl_backend_error:
<!DOCTYPE html>
<html>
<head>
<title>503 Backend fetch failed</title>
</head>
<body>
<h1>Error 503 Backend fetch failed</h1>
<p>Backend fetch failed</p>
<h3>Guru Meditation:</h3>
<p>XID: 123456</p>
<hr>
<p>Varnish cache server</p>
</body>
</html>
Just like for vcl_synth, it also makes sense to override this output template in your own VCL file. You can load a synthetic output template from a file
13. vcl_init#
The vcl_init subroutine is called when the VCL code is loaded. This subroutine is typically used to initialize Varnish Modules (VMODs)
Here’s the built-in VCL code for vcl_init;
sub vcl_init {
return (ok);
}
14. vcl_fini#
When your VCL configuration is discarded, the vcl_fini is called and allows you to clean up your VMODs.
Here’s the built-in VCL code for vcl_fini:
sub vcl_fini {
return (ok);
}
15. Built-in VCL code#
Now that you have familiarized yourself with the built-in VCL for the various subroutines, here’s the full built-in VCL code:
vcl 4.1;
#######################################################################
# Client side
sub vcl_recv {
if (req.method == "PRI") {
/* This will never happen in properly formed traffic (see: RFC7540) */
return (synth(405));
}
if (!req.http.host &&
req.esi_level == 0 &&
req.proto ~ "^(?i)HTTP/1.1") {
/* In HTTP/1.1, Host is required. */
return (synth(400));
}
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);
}
if (req.method != "GET" && req.method != "HEAD") {
/* We only deal with GET and HEAD by default */
return (pass);
}
if (req.http.Authorization || req.http.Cookie) {
/* Not cacheable by default */
return (pass);
}
return (hash);
}
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);
}
sub vcl_pass {
return (fetch);
}
sub vcl_hash {
hash_data(req.url);
if (req.http.host) {
hash_data(req.http.host);
} else {
hash_data(server.ip);
}
return (lookup);
}
sub vcl_purge {
return (synth(200, "Purged"));
}
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);
}
sub vcl_miss {
return (fetch);
}
sub vcl_deliver {
return (deliver);
}
/*
* We can come here "invisibly" with the following errors: 500 & 503
*/
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);
}
#######################################################################
# Backend Fetch
sub vcl_backend_fetch {
if (bereq.method == "GET") {
unset bereq.body;
}
return (fetch);
}
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);
}
sub vcl_backend_error {
set beresp.http.Content-Type = "text/html; charset=utf-8";
set beresp.http.Retry-After = "5";
set beresp.body = {"<!DOCTYPE html>
<html>
<head>
<title>"} + beresp.status + " " + beresp.reason + {"</title>
</head>
<body>
<h1>Error "} + beresp.status + " " + beresp.reason + {"</h1>
<p>"} + beresp.reason + {"</p>
<h3>Guru Meditation:</h3>
<p>XID: "} + bereq.xid + {"</p>
<hr>
<p>Varnish cache server</p>
</body>
</html>
"};
return (deliver);
}
#######################################################################
# Housekeeping
sub vcl_init {
return (ok);
}
sub vcl_fini {
return (ok);
}
