ASP.NET Core's response compression middleware, output caching (.NET 7+) and the HTTP response caching middleware: how each works, configuration, security caveats and when each improves or worsens performance.
They solve different problems:
AddOutputCache, .NET 7+) stores the whole response on the server and replays it without running the endpoint. The app controls the policy: expiry, vary-by, tags for eviction, and stampede-preventing locking.Cache-Control rules, so clients can bypass it; its headers mainly matter for browser and CDN caching.For server-side caching of API responses I choose output caching. The trade-off is freshness: anything cached can be stale until it expires or is evicted.
"Compression and caching attack different costs. Compression reduces bytes transferred: a 400 KB JSON response often becomes 40 to 60 KB with Brotli, which matters on mobile networks. The price is CPU on every response, and over HTTPS there's a security angle: compressing responses that mix secrets with attacker-controlled input enables BREACH-style attacks, which is why
EnableForHttpsis off by default. In practice I often let Azure Front Door, a CDN or the reverse proxy compress, and only use the middleware when the app is exposed directly.Caching avoids doing the work at all. Output caching, added in .NET 7, stores the full response in the server and serves it without running the endpoint. I control it from the app:
CacheOutputwith an expiry, vary-by query or header, and tags so I can evict, for example, every 'products' entry when a product changes. It caches only successful GET and HEAD responses, skips authenticated requests and responses that set cookies by default, and locks so that only one request regenerates an expired entry. Response caching is the older middleware: it follows HTTP caching rules, so a client sendingCache-Control: no-cachebypasses it, and it's mainly useful for its headers, which let browsers and CDNs cache.The mistake I see is turning on caching or compression globally without measuring. Compressing tiny responses or images wastes CPU, and caching a personalised response can leak one user's data to another. I measure response sizes, CPU and hit ratio before and after, and I'm explicit about what varies the cache key."
| Response compression | Output caching | Response caching | |
|---|---|---|---|
| Goal | Fewer bytes on the wire | Skip endpoint execution | Honour HTTP caching |
| Where data lives | Not stored | Server memory or Redis (IOutputCacheStore) |
Server memory |
| Who controls it | App config | App policy | Client and server headers |
| Client can bypass | n/a | No | Yes (no-cache) |
| Eviction | n/a | Expiry + tags (EvictByTagAsync) |
Expiry only |
| Main cost | CPU per response | Memory, staleness | Memory, staleness |
| Added in | ASP.NET Core 1.x | .NET 7 | ASP.NET Core 1.x |
| Feature | Helps | Hurts |
|---|---|---|
| Compression | Large JSON/HTML/text on slow links | Small responses (< ~1 KB), already-compressed content (images, zip), CPU-bound servers, secret-bearing HTTPS responses with reflected input |
| Output caching | Expensive, shared, read-heavy GET endpoints | Personalised data, rapidly changing data, low hit ratio |
| Response caching | Public content where client caching rules are fine | Anything that must not be bypassed or must be evicted on change |
A public catalogue endpoint took 180 ms (SQL plus mapping) at p95 and returned 350 KB of JSON. Output caching with a 60-second expiry and a products tag gave an 94% hit ratio and p95 of 9 ms on hits; letting Azure Front Door compress with Brotli cut payloads to 48 KB without adding CPU to the app.
Checks whether the candidate can distinguish the three features, configure them correctly and recognise their risks.
Green flags
Red flags
client --> [CDN / Front Door: may cache + compress]
--> Kestrel --> UseResponseCompression --> UseRouting --> UseCors
--> UseOutputCache --(hit)--> stored response
\--(miss)--> endpoint --> store --> response
Compression should be registered early so it wraps everything written later. Output caching runs after routing (so it knows the endpoint's policy) and after CORS.
The middleware checks Accept-Encoding, picks a provider (Brotli preferred, then Gzip), and wraps the response body stream so bytes are compressed as they're written. It sets Content-Encoding and Vary: Accept-Encoding. MimeTypes controls which content types are compressed. CompressionLevel.Fastest is usually the right choice for dynamic content: Optimal/SmallestSize can cost several times the CPU for a few per cent smaller output.
BREACH: if a compressed HTTPS response contains a secret (e.g. an anti-forgery token) and attacker-controlled reflected input, an attacker who can observe response sizes can guess the secret byte by byte. Hence EnableForHttps = false by default; enable it only for responses without that mix.
CacheOutput() on endpoints or [OutputCache] on controllers.SetVaryByQuery, SetVaryByHeader, SetVaryByRouteValue and VaryByValue narrow or extend it.Authorization header or is authenticated, and not when the response sets a cookie.Tag("products"), then IOutputCacheStore.EvictByTagAsync("products", ct) after a write.AddStackExchangeRedisOutputCache (.NET 8+) shares entries across instances.The middleware caches only when HTTP rules allow: the response must have Cache-Control: public with a max-age, no Set-Cookie, the request must not send no-cache or Authorization, and so on. [ResponseCache(Duration = 60)] simply sets headers. Those headers are the valuable part: they let browsers and CDNs cache, which saves the round trip entirely.
data_received.dotnet-counters cpu-usage with compression on and off under load.Content-Length for a 300 KB JSON response with Brotli at Fastest vs SmallestSize; measure CPU under k6.Authorization header and confirm it isn't cached by default.[ResponseCache(Duration = 60)] and inspect the headers; then send Cache-Control: no-cache and see the response caching middleware bypassed.Compression, an output cache policy with tag eviction, and HTTP caching headers in one minimal API.
// Program.cs (.NET 10)
using System.IO.Compression;
using Microsoft.AspNetCore.OutputCaching;
using Microsoft.AspNetCore.ResponseCompression;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCompression(options =>
{
// Default (false) kept on purpose: compressing HTTPS responses that mix secrets
// (anti-forgery tokens, session data) with reflected input enables BREACH.
// Set true only for APIs whose responses never do that, or let the CDN/proxy compress.
options.EnableForHttps = false;
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
// Text formats only: images, PDFs and zips are already compressed.
options.MimeTypes = ["application/json", "text/plain", "text/html"];
});
builder.Services.Configure<BrotliCompressionProviderOptions>(o => o.Level = CompressionLevel.Fastest);
builder.Services.AddOutputCache(options =>
{
options.AddPolicy("Catalogue", policy => policy
.Expire(TimeSpan.FromSeconds(60))
.SetVaryByQuery("category", "page") // only these query keys vary the entry
.Tag("products"));
});
// For several instances: builder.Services.AddStackExchangeRedisOutputCache(o => o.Configuration = "...");
var app = builder.Build();
app.UseResponseCompression();
app.UseOutputCache();
// Server-side cached: expensive query runs at most once a minute per category/page.
// Public, non-personalised data only: the default policy won't cache authenticated requests.
app.MapGet("/products", async (string? category, int page, CancellationToken ct) =>
{
await Task.Delay(150, ct); // stand-in for the SQL query
return Results.Ok(new { category, page, items = Array.Empty<object>() });
}).CacheOutput("Catalogue");
// After a write, evict every cached catalogue page.
app.MapPut("/products/{id:int}", async (int id, IOutputCacheStore cache, CancellationToken ct) =>
{
// ... update the product ...
await cache.EvictByTagAsync("products", ct);
return Results.NoContent();
});
// HTTP caching headers: lets browsers and the CDN cache for 5 minutes.
app.MapGet("/categories", (HttpContext http) =>
{
http.Response.Headers.CacheControl = "public,max-age=300";
return Results.Ok(new[] { "boots", "jackets" });
});
app.Run();
Note that output caching doesn't add Cache-Control headers for you: server-side caching and client/CDN caching are configured separately, so set headers deliberately (and never public on personalised data).
MimeTypes to text formats.no-cache. Instead: Use output caching for server-controlled caching.Seniors push caching and compression as far out as possible: a CDN or Front Door hit costs the app nothing. Inside the app, output caching is the default choice for server-side response caching; the response caching middleware is mostly legacy. The design decisions are what varies the key, how entries are evicted, and what happens with several instances.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| CDN/proxy compression | Public traffic through Front Door/App Gateway/YARP | Config at the edge | Internal service-to-service calls on fast networks |
| App response compression | App exposed directly, large text payloads | CPU per response | Small or binary payloads; BREACH-sensitive pages |
| Output caching (memory) | Single instance or short expiry | Per-instance staleness | Tag eviction across many instances |
| Output caching (Redis) | Many instances, tag eviction | Network hop, Redis cost | Tiny, cheap endpoints |
| Cache-Control headers | Public, cacheable content | Can't recall cached copies | Personalised or sensitive data |
Tag entries in the policy (.Tag("products")) and call IOutputCacheStore.EvictByTagAsync("products", ct) after a write. With the default in-memory store, eviction only affects the instance that handled the write, so other instances keep serving stale entries until they expire.
For several instances, use the Redis output cache store (AddStackExchangeRedisOutputCache from Microsoft.AspNetCore.OutputCaching.StackExchangeRedis, available since .NET 8 and current in .NET 10). Output caching uses its own IOutputCacheStore abstraction, not IDistributedCache, because it needs tag-based eviction.
Alternatives: short expiries where a little staleness is fine, versioned keys (vary by a data version so a write naturally misses), or publishing an invalidation event (Redis pub/sub, Service Bus) that each instance handles by evicting locally. The trade-off is freshness versus the cost of a shared store.
HTTP is a request/response protocol: method + path + headers (+ body) in, status + headers (+ body) out.
GET/HEAD/OPTIONS are safe; GET, PUT, DELETE are idempotent (repeating has the same effect); POST and usually PATCH are not, so retries need an idempotency key.Content-Type, Accept, Authorization, Cache-Control, ETag/If-None-Match, Retry-After, traceparent.Last updated 23 Nov 2026.