Wednesday, October 24, 2012

Automatic cache busting using Git commit in Symfony2

Cache busting

Cache busting is to rewrite a URL for an asset (JS, CSS, images, etc) so that is unique. This way, you can cache them for as long as you want. If the URL changes, it will use the new file.


Symfony includes a cache busting mechanism which appends a GET parameter to your asset, but you must remember to increment it and it could quickly become a pain.

Incrementing using Git version

The idea is to use the current Git commit as a version number using git rev-parse --short HEAD. We can call this in the command line using PHP. Don’t worry, in production mode, Symfony caches the compiled configs, so it won’t be checked until you clear the cache.


  • All assets will be reset with every commit. Not a big deal since when you deploy, you usually touch a lot of assets.
  • By default, Symfony uses a GET parameter, which is not cached by all CDNs.
    However, Amazon CloudFront now supports them.
    Otherwise, it is possible to rewrite using a folder prefix, but it can get tricky.
  • You must be using Git (!), including on your production server. Otherwise, it could be possible to achieve something similar by adding a Git hook on commits, writing version in a file, and loading this file instead.


  1. Why not strategy similar to ?
    (i.e. embedding a hash of the content into the filename).

    This is guaranteed to invalid your cache when the content of your asset changes. Does not requires any versioning system dependencies. And is trivial to implement if you have an asset compilation step.

  2. This is indeed a nice solution, but as far as I know, this is not available in Symfony and it would require developing a hook in AsseticBundle, which means an extra bundle, etc.

    Otherwise, when you combine multiple assets into one using assetic, it does generate a hash (if you don't specify ont), but I think it is based on the filename, so it is not very useful.

  3. Thanks for this post!