LESSON 10 OF 13

Response Compression and HTTP-Level Performance

Learn how to configure ASP.NET Core Response Compression with Brotli and Gzip, inspect Accept-Encoding behavior, and measure compression benefits.

45 dk 59

Introduction

In the previous lessons, we examined API response design, serialization cost, and caching techniques. This lesson focuses on the HTTP layer of the performance chain. Even when an endpoint produces data quickly, a large response body may take significant time to transfer over the network. Text-based content such as JSON, HTML, XML, JavaScript, and CSS can often be reduced substantially through compression.

ASP.NET Core provides Response Compression Middleware for compressing response bodies according to the capabilities of the client. The middleware reads the client’s Accept-Encoding header and selects Brotli or Gzip when an appropriate provider is available. The client learns how the response was encoded from the Content-Encoding header.

The goal of this lesson is not simply to enable middleware. We will also evaluate CPU cost, payload reduction, HTTPS security considerations, content that should not be compressed, and a reliable measurement process.

The HTTP compression model

Accept-Encoding and Content-Encoding

A client announces the encoding algorithms it supports in the request:

GET /api/products HTTP/1.1
Host: localhost:5000
Accept-Encoding: br, gzip

If the server selects Brotli, the response may contain headers such as:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Encoding: br
Vary: Accept-Encoding

Content-Encoding identifies how the response body is encoded. The client automatically decompresses the body before presenting it to the application or user. Vary: Accept-Encoding tells shared caches that compressed and uncompressed representations of the same URL must not be mixed.

If the client does not send Accept-Encoding, or prefers identity, the server can return an uncompressed body. The middleware also skips compression when the response Content-Type does not match a configured MIME type.

Comparing Brotli and Gzip

AlgorithmStrengthTypical use
BrotliOften produces smaller text responsesModern browsers and API clients
GzipBroad client and tool compatibilityLegacy clients, services, and fallback support

Choosing an algorithm is not enough. Higher compression levels can reduce the payload further, but they also increase CPU usage and response-generation time. For low-latency, high-throughput APIs, Fastest may be more appropriate. When bandwidth is more constrained and CPU capacity is available, Optimal may be useful. The final decision should come from measurements.

Configuring Response Compression

1. Register the services

Start by importing the required namespaces and registering response compression services:

using System.IO.Compression;
using Microsoft.AspNetCore.ResponseCompression;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddResponseCompression(options =>
{
    options.Providers.Add<BrotliCompressionProvider>();
    options.Providers.Add<GzipCompressionProvider>();

    options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
        new[]
        {
            "application/problem+json",
            "application/vnd.api+json",
            "image/svg+xml"
        });
});

The default MIME types include compressible formats such as JSON, HTML, XML, CSS, and JavaScript. If your application returns a custom text-based media type, add it explicitly. Deliberately listing MIME types is more predictable than assuming broad wildcard behavior.

2. Configure compression levels

builder.Services.Configure<BrotliCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Fastest;
});

builder.Services.Configure<GzipCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Fastest;
});

Fastest prioritizes completing compression quickly. Optimal may produce a smaller result but generally requires more CPU. There may not be one ideal level for every endpoint. Large reports and small, frequently called JSON endpoints should be measured separately.

3. Place the middleware correctly

var app = builder.Build();

app.UseResponseCompression();
app.UseHttpsRedirection();
app.MapControllers();

app.Run();

UseResponseCompression should run before middleware that produces responses to be compressed. In most applications, placing it before endpoint mapping is sufficient. If IIS, Nginx, a gateway, or a CDN also compresses responses, inspect the deployment configuration to avoid unnecessary double compression.

HTTPS and security considerations

Compression of HTTPS responses is disabled by default in the ASP.NET Core middleware. Although it can be enabled, dynamically generated content that combines secrets with attacker-controlled text requires careful security analysis because of risks related to BREACH-style attacks:

builder.Services.AddResponseCompression(options =>
{
    options.EnableForHttps = true;
});

Enabling this option globally without analysis is not a good default. A response that contains a secret token, session information, or attacker-controlled text may expose information through compression size differences. First determine whether compression is already performed by the web server or CDN. If application-level HTTPS compression is required, limit it to low-risk content where possible and review the design with the security team.

Compressible and non-compressible content

JSON, HTML, XML, CSS, JavaScript, and plain text usually compress well because they contain repeated characters and structures. JPEG, PNG, GIF, WebP, ZIP, GZip, PDF, and MP4 files are commonly already compressed. Compressing them again consumes CPU and may produce little or no meaningful reduction.

Very small responses also require attention. Compression headers and algorithm overhead can exceed the benefit of compressing a response that is only a few hundred bytes. Instead of applying a “compress everything” rule, evaluate content type, response size, traffic volume, and available CPU capacity together.

Measurement: does compression help?

Validate the optimization with at least three measurements:

  1. Measure response time and payload size with compression disabled or not requested.
  2. Repeat the request with Accept-Encoding: gzip.
  3. Repeat it with Accept-Encoding: br and observe CPU usage.

Example requests:

curl -i http://localhost:5000/api/products \
  -H "Accept-Encoding: identity"

curl -i http://localhost:5000/api/products \
  -H "Accept-Encoding: gzip"

curl -i http://localhost:5000/api/products \
  -H "Accept-Encoding: br"

Do not look only at server-side duration. Inspect Content-Encoding, transfer size, client-perceived duration, CPU usage, and p95/p99 latency. When compression is applied, Content-Length may be removed because the encoded body size can be determined while the response is being streamed.

A comparison table might look like this:

ScenarioPayloadp95 durationCPU impact
Uncompressed850 KB180 msLow
Gzip110 KB145 msMedium
Brotli92 KB150 msMedium-high

These values are illustrative. Measure with your own hardware, data shape, client, and network conditions. A smaller Brotli payload does not always result in lower total latency; compression CPU cost or client-side decompression can change the result.

Common mistakes

  • Registering the middleware too late: Response Compression may not affect responses produced earlier in the pipeline.
  • Compressing every MIME type: Compressing already compressed files such as PNG or MP4 wastes CPU.
  • Ignoring HTTPS risks: Use EnableForHttps only after evaluating the security implications.
  • Ignoring the Vary header: Caches must separate representations according to Accept-Encoding.
  • Skipping proxy analysis: IIS, Nginx, a gateway, or a CDN may already compress responses.
  • Measuring only averages: p95 and p99 latency are often more meaningful under load.
  • Testing with the wrong client assumptions: Some clients automatically decompress responses; inspect network transfer size separately.

Practice exercise

Create an /api/catalog endpoint that returns JSON containing at least 5,000 products. First test it with response compression disabled or not requested. Then enable Brotli and Gzip and repeat the request with three different Accept-Encoding values.

  1. Record Content-Encoding, Vary, and transfer size for each request.
  2. Return a PNG or ZIP file from another endpoint and verify whether it is compressed.
  3. Compare the Fastest and Optimal compression levels.
  4. Interpret the results using payload size, average duration, p95 duration, and CPU usage.

Conclusion

Response Compression is an effective HTTP-level optimization that reduces the amount of data transferred without requiring changes to the business logic. A correct implementation requires understanding the client’s Accept-Encoding preference, the server’s Content-Encoding response, the role of Vary, and the configured MIME types.

Brotli may produce smaller text responses for modern clients, while Gzip provides strong compatibility. However, the algorithm and compression level should not be selected without measurement. CPU cost, HTTPS security implications, proxy behavior, and already compressed files must all be considered. The next step is to connect these measurements with automated performance tests and production traffic observations so that optimization decisions become more reliable.

Sources