📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the difference between response compression, output caching and response caching in ASP.NET Core? Explain what each does, how you configure it, and when each one helps or hurts performance.

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.

Intermediate Theory Intermediate aspnet-core http-caching output-caching performance response-caching response-compression

🎯 Key points

  • Response compression shrinks bytes on the wire (Brotli/Gzip) at a CPU cost per response; worthwhile for large text (JSON, HTML), wasteful for small or already-compressed content
  • EnableForHttps is off by default because of CRIME/BREACH; often better done by a proxy or CDN
  • Output caching (.NET 7+, unchanged in principle in .NET 10) stores full responses on the server; app controls policy, expiry and tag eviction
  • Output cache defaults: only 200 GET/HEAD, skips authenticated requests and responses setting cookies; locking stops stampedes
  • Personalised or tenant-specific responses must vary the key by user/tenant or not be cached at all
  • Response caching middleware follows HTTP Cache-Control rules; clients can bypass it with no-cache; its headers drive browser/CDN caching
  • Multi-instance: use a shared output cache store (Redis) or accept per-instance caches
  • Measure: response size, CPU, cache hit ratio, p95 before and after

⏱ 30-second answer

They solve different problems:

  • Response compression makes responses smaller (Brotli or Gzip). It helps large text payloads on slow networks but costs CPU per response. Over HTTPS it's off by default because of BREACH-style attacks, and is often better done at a proxy or CDN.
  • Output caching (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.
  • Response caching middleware follows HTTP 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 EnableForHttps is 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: CacheOutput with 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 sending Cache-Control: no-cache bypasses 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."


Side by side

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

When each helps or hurts

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can distinguish the three features, configure them correctly and recognise their risks.

Green flags

  • Explains that compression trades CPU for bytes and knows why HTTPS compression is off by default
  • Knows output caching is server-controlled with tags and locking
  • Knows response caching follows client-controllable HTTP rules
  • Thinks about personalised data and multiple instances

Red flags

  • Treats output caching and response caching as the same
  • Turns everything on globally without measurement
  • Caches authenticated responses without varying by user

📚 Learn in depth

1. Where each sits in the pipeline

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.

2. Response compression internals

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.

3. Output caching internals

  • Policies: a base policy plus named policies; CacheOutput() on endpoints or [OutputCache] on controllers.
  • The cache key includes the path and, by default, the full query string; SetVaryByQuery, SetVaryByHeader, SetVaryByRouteValue and VaryByValue narrow or extend it.
  • Defaults: cache only HTTP 200, only GET/HEAD, not when the request has an Authorization header or is authenticated, and not when the response sets a cookie.
  • Resource locking: concurrent requests for the same missing entry wait for the first to fill it (stampede protection).
  • Tags: Tag("products"), then IOutputCacheStore.EvictByTagAsync("products", ct) after a write.
  • Storage: in-memory by default; AddStackExchangeRedisOutputCache (.NET 8+) shares entries across instances.

4. Response caching internals

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.

5. Measuring

  • Response size: browser dev tools or k6 data_received.
  • CPU: dotnet-counters cpu-usage with compression on and off under load.
  • Output cache effectiveness: count hits vs misses with a custom metric or logs, and p95 split by hit/miss.

Try it yourself

  1. Add response compression and compare Content-Length for a 300 KB JSON response with Brotli at Fastest vs SmallestSize; measure CPU under k6.
  2. Add output caching to an endpoint with a 30-second expiry and a tag; write a POST endpoint that evicts the tag and verify fresh data appears.
  3. Send a request with an Authorization header and confirm it isn't cached by default.
  4. Add [ResponseCache(Duration = 60)] and inspect the headers; then send Cache-Control: no-cache and see the response caching middleware bypassed.

💻 Code

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).

⚠ Common mistakes

  • Mistake: Optimising without measuring. Why it is wrong: Compression can raise CPU and latency for small payloads; caching with a low hit ratio just uses memory. Instead: Measure size, CPU, hit ratio and p95 before and after.
  • Mistake: Micro-optimising cold paths by caching rarely called endpoints. Why it is wrong: Low hit ratio, added staleness risk, no user-visible gain. Instead: Cache hot, expensive, shared GET endpoints.
  • Mistake: Enabling compression for HTTPS everywhere without thinking about BREACH. Why it is wrong: Responses mixing secrets and reflected input can leak the secret. Instead: Exclude those responses or compress at the CDN with appropriate rules.
  • Mistake: Compressing images, PDFs or zip files. Why it is wrong: They're already compressed; you burn CPU for nothing. Instead: Limit MimeTypes to text formats.
  • Mistake: Overriding the output cache defaults to cache authenticated responses without varying by user. Why it is wrong: One user's data is served to another. Instead: Keep the defaults, or vary by a user or tenant value deliberately.
  • Mistake: Expecting the response caching middleware to always cache. Why it is wrong: Clients can bypass it with no-cache. Instead: Use output caching for server-controlled caching.
  • Mistake: In-memory output cache on many instances with tag eviction. Why it is wrong: Eviction only hits the instance that handled the write. Instead: Use the Redis store or short expiries.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions output caching Why: Checks they understand tag-based eviction and shared stores
    How to answer

    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.

  2. When: Candidate mentions Cache-Control or Accept-Encoding headers Why: Checks their grasp of HTTP headers and protocol behaviour
    How to answer

    HTTP is a request/response protocol: method + path + headers (+ body) in, status + headers (+ body) out.

    • Methods: 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.
    • Status codes: 2xx success, 3xx redirect/not modified, 4xx client error (400, 401 vs 403, 404, 409, 422, 429), 5xx server error (500, and 502/503/504 usually from proxies or gateways).
    • Headers: Content-Type, Accept, Authorization, Cache-Control, ETag/If-None-Match, Retry-After, traceparent.
    • Versions: HTTP/1.1 is text with one request at a time per connection; HTTP/2 is binary with multiplexed streams and header compression on one TCP connection; HTTP/3 does the same over QUIC/UDP, removing TCP head-of-line blocking.

↩ Usually asked after

More in Application Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me