Setting a specific Brotli compression level when using response compression in ASP.NET Core

Brotli can compress HTML, CSS and JS files more than Gzip. If you can’t enable Brotli compression on the server level but want to use it in your ASP.NET Core app you can use the response compression middleware to enable it from your Startup.cs file. Setup is easy and looks like below..

Setting up MVC response compression

Note the app.UseResponseCompression() in the Configure method needs to be before app.UseStaticFiles() as otherwise headers have already been sent. The default setup above will use Brotli if the client supports it else it will use Gzip if it’s supported. By default the Brotli compression provider will be set to a compression level of 1 (fastest).

The compression level corresponds to how aggressive an algorithm will compress a document. Brotli has 11 levels, 1 being the fastest but least compressed and 11 being the most compressed but also the slowest. Brotli at its highest level (11) is extremely slow compared to Gzip at its highest level (9). Slow compression is fine for static CSS/JS files which we can compress ahead of time. For on the fly compression (eg. dynamic web pages) slow speeds can negatively impact web app performance..

SO

.. for Brotli compression to be advantageous over Gzip we need to find the compression level which gives us the best balance between compression amount and speed..

BUT

the problem with the Brotli compression provider in ASP.NET Core is that it only has three options in its enum for setting the level…

ResponseCompression Options

There is no enum option for the best balance between compression and speed. In this case we can just set the level with a number directly…

Setting Brotli Level

You need to experiment with different levels but a number of resources seem to be agreeing on level 4 or 5 as being the sweet spot…

https://blogs.akamai.com/2016/02/understanding-brotlis-potential.html

https://paulcalvano.com/2018-07-25-brotli-compression-how-much-will-it-reduce-your-content

https://quixdb.github.io/squash-benchmark/#results-table

Of course for your static content such as CS, JS, Fonts etc. compress to the max with 11. This will give you significant byte savings over Gzip.

 

Leave a Reply

Your email address will not be published. Required fields are marked *