VCL, which stands for Varnish Configuration Language, is used to define your own caching policies in Varnish Cache and Varnish Enterprise. It is a real programming language whose syntax can in some cases be the same as the C language.
The upside of learning VCL is that, once you master it, you are able to define perfect caching policies and ensure that your Varnish Cache instance behaves exactly how you expect in every circumstance and under a variety of conditions.
The downside is, of course, that you will have to learn a new programming language.
In this blog post we won’t discuss the syntax itself, but most likely I’ll point out some interesting VCL tips and not very well-known VCL rules.
sub vcl_hash { }
your Varnish Cache will instead see:
sub vcl_hash {
hash_data(req.url);
if (req.http.host) {
hash_data(req.http.host);
} else {
hash_data(server.ip);
}
return (lookup);
}
This is because the builtin subroutine for vcl_hash will be appended to your empty vcl_hash.
As a rule of thumb, we strongly suggest that you let builtin.vcl be appended to your VCL to avoid unhappy situations.
If you don’t want the builtin.vcl to be appended to your VCL file, then you need to specify a “return(action)”, which exits one state/subroutine and instructs Varnish to proceed to the next state/subroutine. If you must “return” from any subroutine, please test your VCL extensively before using it in a production environment. (More on Varnishtest).
PCRE
Varnish Cache and Varnish Enterprise rely on PCRE to process regular expressions.
if (bereq.url ~ "\.(aif|aiff|au|avi|bin|bmp|cab|carb|cct|cdf|class|css)$" ||
bereq.url ~ "\.(dcr|doc|dtd|eps|exe|flv|gcf|gff|gif|grv|hdml|hqx)$" ||
bereq.url ~ "\.(ico|ini|jpeg|jpg|js|mov|mp3|nc|pct|pdf|png|ppc|pws)$" ||
bereq.url ~ "\.(swa|swf|tif|txt|vbs|w32|wav|wbmp|wml|wmlc|wmls|wmlsc)$"||
bereq.url ~ "\.(eot|woff|svg|ttf)"||
bereq.url ~ "\.(xml|xsd|xsl|zip)$")
PCRE sometimes misbehaves and crashes when heavy recursive regular expressions are used. You can try to simplify as much as possible your regular expressions, breaking them down into smaller expressions.
It is also suggested that you increase the thread_pool_stack parameter, which represents the thread stack size.
sub vcl_hash {
hash_data(req.http.Cookie);
return(lookup);
}
This VCL snippet inserts and searches for objects in cache based only on the request Cookie header and here we have at least two problems:
Hopefully this blog post will help anyone who is an active VCL writer to define better and more secure caching policies.
If you want to learn more about VCL, the Varnish-Book is a great place to start.