We're using gzip compression like:
services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
services.AddResponseCompression(options =>
{
options.Providers.Add<GzipCompressionProvider>();
});
Since we'd like to avoid compression for small responses, question is if we can somehow configure gzip compression not to be used for response sizes less than XY?
The Compression Middleware in ASP.NET Core 2.1 does not seem to provide the ability of compressing data based on content size, so short answer to your question is "No".
However, I understand the main reason for such setup would be to make the overall request end-to-end faster, which is what the CompressionLevel.Fastest is supposed to do for you already.
The GZipCompressionProvider ends up calling the Deflater constructor and CreateZLibStreamForDeflate method where the CompressionLevel enumeration defined in .NET is mapped into the compression level defined into the underlying zlib library used to perform the actual compression. From the zlib manual:
The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6).
According to the way the ASP.NET Core Compression Middleware maps compression levels, as defined in Deflater and ZLibNative, we can deduce the following:
Note, there is no option mapping into higher zlib compression levels, like 9 which is the highest compression and the most expensive, which would probably make the ASP.NET Core web app spending more time compressing than sending the whole content back to the client.
In a web service implementation, compression is just a tool to make things faster, therefore compression should be as light as possible to avoid the case where the compression algorithm spends more time than what it would take for the network to deliver the payload not compressed.
The way I see it, CompressionLevel.Fastest works best as in most cases it guarantees the client to receive a quicker response, hence it normally is the best option for a web site or web api that needs to deal with usual file sizes.
On the other hand, if your web service needs to deliver large contents, CompressionLevel.Optimal would bring more value as it would have more impact in how much data will be sent over the network.
On top of that, the client can always specify if the response should be compressed by setting the Accept-Encoding request HTTP header appropriately, as explained in ASP.NET Core Compression Middleware documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With