.NET API Response Compression

stamp character set

There are times when API responses are too large. In my experience, I have seen this in 2 flavors. The most common is a data model that grows and grows to a large number of properties. Increasing the amount of data being provided to the client on every request. The other flavor seen is a dataset that continues to grow. To a set much larger than anticipated. Requiring pagination of data that may not exist yet. Perhaps those have been avoided and performance optimization is the target. API response compression may be your answer.

What is API Response Compression?

Similar to a tactic used with emailing large items, we can use tools like 7zip or WinZip to reduce the size of those large items to a smaller package. Reducing the size of the item such that it can send it via email. The default compression MIME types are similar to those large items. They are text-based datasets being transferred from server to client.

Why Compress API Responses?

The amount of bandwidth the client and server have available to them is not unlimited. Compression allows for a small compromise between computational resources and bandwidth.

How is API Response Compression Enabled?

The .NET team has made this so easy for development teams. The default configuration can be configured in 2 lines!

// Register all the necessary components with the IServiceCollection container
services.AddResponseCompression();

// Configure the applications middleware to execute the compression middleware per request
app.UseResponseCompression();

With these 2 lines of configuration, the API will have both Brotli and GZip compression algorithms. For the client to request compressed responses an additional request header has to be passed Accept-Encoding with a value of br for Brotli or gzip for GZip. If no additional request header is passed, the client will receive the response uncompressed. By default, the following MIME types will be compressed when the Accept-Encoding header is provided:

  • application/javascript
  • application/json
  • application/xml
  • text/css
  • text/html
  • text/json
  • text/plain
  • text/xml

I have created a working API with response compression that can be found here

Side Note:

Testing this took me way too long. As you will see in the GitHub repository there is no Postman collection. My original intention was to provide this information in the repository for convenience. But, the reporting of the response size in Postman is the uncompressed value, not the size of the response as it comes across the wire. There is an open issue with the Postman product team. As of writing this post, the issue is open and has been since November of 2019. Other HTTP clients display the compressed response size, one of them being Fiddler by Telerik. The limitation of Fiddler is that I am unfamiliar with request import or export functionality.