In search of the best cache busting query string

James Simm
James Simm
Head of Engineering
Length
4 min read
Date
25 April 2019

Busting the cache based on file modified date

This one is pretty similar to busting based on version but doesn’t rely on you having versioning setup and generally has a lot less maintenance. However, it’s not as accurate as version based cache busting, or my preferred approach.

On top of that, if you have multiple content delivery servers, the timestamps could be different on each of them, which would mean browsers and CDNs would cache multiple versions of the same file.

With that said it’s very easy to get working, and if you have a very small project it might be a good bet for a quick way of doing it.

A good example is this stack overflow post.

Although there are a few problems with it on larger projects.

Busting the cache based on git hash

This is my preferred approach, as your git hash should refer directly to the code itself, so there’s no chance of a collision between versions, and it aligns with repeatable builds, which is something I really like.

The only real downside to this one is that it’s a bit more computationally expensive than the others, so you likely want to cache it or use a singleton to generate it.

Here’s the example, it uses MSBuildGitHash which needs a small modification to your csproj so it can stamp the DLL with your git hash. After that you just need the following code to get the version out:

public static string VersionHash(this HtmlHelper helper)
{
var assembly = typeof(TheCurrentClassYou’reCallingFrom).Assembly;
var attributes = assembly.GetCustomAttributes<AssemblyMetadataAttribute>();
var hash = attributes.FirstOrDefault(a => a.Key == “GitHash”)?.Value;
return hash?.Replace(“-dirty”, string.Empty);
}

Just replace the classname before the .Assembly call with your classname and you should be good to go.

More Insights?

View all Insights

Questions?

Global SVP Technology & Engineering

Jonathan Whiteside