Varnish: Enabling wildcard purging of cache content

Varnish is great for load balancing and reducing load on your servers by caching content, but at the same time it's an absolute pain in the ass to clear the cache for multiple things at once. Fortunately, Varnish 3.0 makes it much easier to do mass purging.

Setup in Varnish 2.x

In 2.x syntax, we'd open up the VCL file and do something like:

sub vcl_recv {
if (req.request == "PURGE") {
if (!client.ip ~ purge_acl) {
error 405 "Not allowed";
}

return(lookup);
}
}

# Which also requires
sub vcl_hit {
# Clear the cache if a PURGE has been requested
if (req.request == "PURGE") {
set obj.ttl = 0s;
error 200 "Purged.";
}
}

Setup in Varnish 3.x

In 3.x syntax, purge() and purge_url() has been replaced by ban() and ban_url(). Contrary to the name, it doesn't ban a request but rather refresh it.

sub vcl_recv {
if (req.request == "PURGE") {
if (!client.ip ~ purge_acl) {
error 405 "Not allowed";
}

ban("req.http.host == " + req.http.host + " && req.url ~ " + req.url + "$");
error 200 "Purged.";
}
}

Requesting a PURGE

To clear the URL, we simply make a call using curl.

To clear a specific URL:

curl -X PURGE http://www.yourdomain.com/varnish/esi/comments/12345/

To clear any urls which match this pattern:

curl -X PURGE http://www.yourdomain.com/varnish/esi/comments/.*

Main differences

No more logic in vcl_hit() ! All your cache invalidation is done in the one place.

Another subtle difference is that purge() will clear the contents from memory, opening up your server to the thundering herd problem while ban() simply invalidates it and refreshes it when ready.

One last benefit of going to Varnish 3.0 is the support for GZip on ESI pages!

All great changes in my opinion!

aww-yea

Awww yeahhhhh~!

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog