API responses can become surprisingly large as an application grows. A simple endpoint may initially return a few customer records, but later it might return thousands of records, detailed reports, analytics data, or large JSON documents.
Sending these responses without compression increases network usage and can make applications feel slower, particularly for mobile clients and users on limited connections.
ASP.NET Core supports response compression through middleware. Traditionally, developers have used Brotli and Gzip to reduce the size of HTTP responses. Zstandard, commonly known as Zstd, adds another compression option designed to provide a useful balance between compression speed and compression ratio.
With .NET 11, ASP.NET Core adds built-in Zstandard support to its response compression and request decompression middleware. This means developers can use Zstd without introducing a separate compression library or writing a custom compression provider.
This article explains how Zstandard works, how to configure it in ASP.NET Core, how to control compression quality, and what to consider before enabling it in production.
Understanding Zstandard Compression
Zstandard is a general-purpose compression algorithm developed by Meta. It is designed to provide fast compression and decompression while maintaining a good compression ratio.
It is standardized for HTTP content encoding through RFC 8878.
When a client requests a resource, it can tell the server which compression formats it supports through the Accept-Encoding request header.
For example:
GET /api/reports HTTP/1.1
Host: example.com
Accept-Encoding: zstd, br, gzip
The client is telling the server that it can process Zstandard, Brotli, and Gzip compressed responses.
If the server selects Zstandard, the response includes:
HTTP/1.1 200 OK
Content-Type: application/json
Content-Encoding: zstd
Vary: Accept-Encoding
The response body contains Zstandard-compressed data rather than plain JSON.
The client uses the Content-Encoding header to determine how to decompress the response before processing the JSON.
This is an important distinction: compression does not change the API's logical response structure. The client still receives the same JSON content after decompression.
Why Use Zstandard Instead of Only Gzip or Brotli?
Gzip and Brotli are already widely supported, so developers may wonder why another compression format is necessary.
The answer is that compression algorithms make different trade-offs between processing time and output size.
Compression format | General characteristics |
|---|
Gzip | Widely supported and compatible with many clients |
Brotli | Often provides strong compression for web content |
Zstandard | Offers configurable compression levels and fast decompression |
Zstandard is particularly interesting for APIs that transfer large amounts of structured data.
For example, consider an application that returns large JSON responses containing customer records, transaction history, or analytics information.
The server spends CPU time generating and compressing the response, while the client spends time decompressing it.
A compression algorithm that provides a useful balance between these operations can improve the overall request experience.
However, no algorithm is automatically the best choice for every API. The result depends on the response content, compression quality, hardware, network conditions, and client capabilities.
The correct approach is to measure actual workloads rather than assume that Zstandard will always produce smaller or faster responses.
Enabling Zstandard Response Compression in ASP.NET Core
In .NET 11, Zstandard is integrated into the existing ASP.NET Core response compression middleware.
You do not need to install a separate Zstandard compression package.
Start by creating an ASP.NET Core Web API project:
dotnet new webapi -n ZstdApi
cd ZstdApi
Open Program.cs and register response compression:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCompression();
var app = builder.Build();
app.UseResponseCompression();
app.MapGet("/", () => "Hello from ASP.NET Core!");
app.Run();
The AddResponseCompression method registers the response compression services.
The UseResponseCompression method adds the middleware to the HTTP request pipeline.
When a request contains an Accept-Encoding header that supports an available compression format, the middleware can compress eligible responses.
In .NET 11, Zstandard is supported by the response compression middleware and is enabled by default alongside the existing supported compression providers.
This means the application can negotiate Zstandard compression without implementing a custom provider.
The middleware does not compress every response unconditionally. The client must advertise support for a compression format, and the response must meet the middleware's compression requirements.
Configuring Zstandard Compression Quality
One of the useful features of Zstandard is its configurable compression quality.
ASP.NET Core exposes this through ZstandardCompressionProviderOptions.
The quality level ranges from 1 to 22.
A lower value generally prioritizes compression speed, while a higher value spends more processing time to achieve better compression.
For example, configure the quality level in Program.cs:
using Microsoft.AspNetCore.ResponseCompression;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCompression();
builder.Services.Configure<ZstandardCompressionProviderOptions>(
options =>
{
options.CompressionOptions =
new ZstandardCompressionOptions
{
Quality = 6
};
});
var app = builder.Build();
app.UseResponseCompression();
app.MapGet("/api/data", () =>
{
return Results.Ok(new
{
Message = "Zstandard compression is enabled.",
GeneratedAt = DateTime.UtcNow
});
});
app.Run();
Here, Quality is set to 6.
This is a reasonable starting point for testing, but it should not be treated as a universal production recommendation.
A higher quality level may reduce the response size, but it can also increase CPU usage and response-generation time.
For APIs that generate large responses frequently, the additional CPU cost can become significant.
For this reason, test different quality levels using representative API responses and realistic concurrent traffic.
Understanding Middleware Order
Middleware order matters in ASP.NET Core.
Response compression should be registered early enough in the pipeline to wrap the response body produced by downstream middleware and endpoints.
For example:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCompression();
var app = builder.Build();
app.UseResponseCompression();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
In this example, response compression is placed before routing, authentication, authorization, and controller execution.
This allows the compression middleware to process eligible responses generated by the downstream pipeline.
If another middleware or infrastructure component performs compression, avoid accidentally compressing the same response twice.
For example, a reverse proxy or web server may already apply compression. Check the deployment configuration before enabling compression at multiple layers.
Testing Zstandard Responses
After enabling compression, verify that the application actually returns a Zstandard-compressed response.
A simple test endpoint can return a larger JSON payload:
app.MapGet("/api/products", () =>
{
var products = Enumerable.Range(1, 5000)
.Select(id => new
{
Id = id,
Name = $"Product {id}",
Category = "Electronics",
Description =
"This product contains detailed information for testing response compression."
});
return Results.Ok(products);
});
Start the application:
dotnet run
Use curl to request a compressed response:
curl -H "Accept-Encoding: zstd" \
-H "Accept: application/json" \
-i https://localhost:7001/api/products
Use the actual HTTPS port assigned to your application.
If Zstandard is selected, inspect the response headers for:
Content-Encoding: zstd
Vary: Accept-Encoding
The Content-Encoding header confirms the selected response encoding.
The Vary header is important because the server can return different representations depending on the client's Accept-Encoding header. Caches need to account for that difference.
To inspect the response body after decompression, use a curl build that supports Zstandard:
curl --compressed \
-H "Accept-Encoding: zstd" \
https://localhost:7001/api/products
The curl installation must support the requested compression format. If it does not, use a compatible HTTP client or a browser that supports Zstandard.
When testing, compare both the compressed and uncompressed response sizes. Also verify that the decompressed JSON remains valid and contains the expected data.
Supporting Multiple Compression Formats
Not every client supports Zstandard.
Some older mobile applications, third-party integrations, and custom HTTP clients may only support Gzip or Brotli.
This is why content negotiation is important.
A client can advertise multiple supported formats:
Accept-Encoding: zstd, br, gzip
The response compression middleware considers the available providers and the client's encoding preferences when selecting a compression format.
Clients can also express preferences using quality values:
Accept-Encoding: zstd;q=1.0, br;q=0.8, gzip;q=0.5
The q value represents the client's relative preference for an encoding.
The server should not assume that every client can decode Zstandard simply because the API supports it.
If a client does not advertise Zstandard support, the server can select another acceptable encoding or return an uncompressed response, depending on the available providers and negotiation rules.
For production applications, verify the supported compression formats across web clients, Android applications, iOS applications, API consumers, and any intermediary services.
Configuring Request Decompression
Zstandard support in .NET 11 is not limited to outgoing responses.
ASP.NET Core also supports Zstandard request decompression through the request decompression middleware.
This is useful when clients upload large JSON documents, bulk records, or other request payloads.
For example, a client can send:
POST /api/import HTTP/1.1
Host: example.com
Content-Type: application/json
Content-Encoding: zstd
The request body contains Zstandard-compressed content.
ASP.NET Core can decompress the body before the endpoint reads it.
Enable request decompression with the following configuration:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRequestDecompression();
var app = builder.Build();
app.UseRequestDecompression();
app.MapPost("/api/import", async (HttpRequest request) =>
{
using var reader = new StreamReader(request.Body);
var content = await reader.ReadToEndAsync();
return Results.Ok(new
{
Message = "Request decompressed successfully.",
ContentLength = content.Length
});
});
app.Run();
The middleware identifies the request encoding using the Content-Encoding header and wraps the request body with the appropriate decompression stream.
Decompression occurs when the request body is read. It is not necessary for the middleware to decompress the entire request immediately when the request arrives.
This is useful because the endpoint can continue using the normal request body APIs without implementing its own Zstandard decompression logic.
Request decompression and response compression are separate capabilities. Enable each one according to the application's requirements.
Important Security and Performance Considerations
Compression can improve network efficiency, but enabling it without considering the application workload can create problems.
Avoid compressing very small responses
Compression requires processing time and introduces some overhead.
For a very small response, the compressed output may not be significantly smaller than the original content. In some cases, compression can even increase the total size.
Focus on responses that are large enough to benefit from compression.
Avoid compressing already-compressed content
Images, videos, ZIP archives, and other compressed formats usually gain little from additional compression.
Compressing them again can waste CPU resources without providing meaningful network savings.
Review the MIME types handled by the response compression middleware and configure them according to the application's content.
Be careful with HTTPS compression
Compression of dynamically generated responses over HTTPS can introduce security risks, particularly when attacker-controlled input and sensitive information are included in the same compressed response.
Attacks such as BREACH exploit information revealed through differences in compressed response sizes.
ASP.NET Core keeps EnableForHttps disabled by default in response compression configuration because of these risks.
Before enabling compression for HTTPS responses, review whether sensitive data and attacker-controlled input can appear together. Use appropriate mitigations, such as avoiding compression of sensitive responses and separating secrets from reflected input.
HTTPS alone does not eliminate compression side-channel risks.
Monitor CPU usage
Higher compression quality can increase CPU consumption.
An API that returns large reports to many concurrent users may experience additional CPU pressure after compression is enabled.
Monitor CPU utilization, request duration, response sizes, and throughput.
A smaller response is not automatically a faster response if compression becomes the application's bottleneck.
Protect request decompression from oversized payloads
Request decompression can turn a relatively small compressed payload into a much larger uncompressed body.
Applications should enforce appropriate request-size limits and consider resource consumption when accepting compressed uploads.
Do not assume that a small compressed request is safe to process without limits.
When Should You Use Zstandard in Production?
Zstandard is worth evaluating when an application frequently transfers large JSON responses, structured data, or other compressible content.
It can be particularly useful for APIs serving mobile clients, reporting applications, analytics dashboards, and services that transfer large datasets.
However, compatibility is an important consideration.
Before enabling it for all clients, confirm that the clients can decode Zstandard responses. Older clients may need to continue using Brotli, Gzip, or uncompressed responses.
A practical rollout strategy is to enable compression in a test environment, measure representative response sizes and processing costs, and verify compatibility with each supported client.
For high-traffic APIs, compare different quality levels under realistic concurrency rather than relying on a single request measurement.
Also check whether a reverse proxy, CDN, or hosting platform already performs compression. The final response should have one correctly applied content encoding, not multiple unintended compression layers.
Summary
Zstandard brings another compression option to ASP.NET Core applications. With .NET 11, the existing response compression and request decompression middleware support Zstandard without requiring a separate compression provider.
Developers can enable response compression through AddResponseCompression and UseResponseCompression, then configure compression quality through ZstandardCompressionProviderOptions.
The same framework also supports incoming Zstandard-compressed requests through AddRequestDecompression and UseRequestDecompression.
The main advantage is flexibility. Applications can negotiate between Zstandard, Brotli, and Gzip based on client capabilities instead of implementing separate compression logic.
However, compression should always be evaluated against actual application workloads. Client compatibility, CPU consumption, response size, security, and request-size limits all matter.
When configured and measured properly, Zstandard can help ASP.NET Core applications transfer large payloads more efficiently while keeping the existing HTTP API contract unchanged.
Join the conversation! Your thoughts help the community grow.