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

📚 Interview question

How do HTTP caching headers work for an API? Explain the main Cache-Control directives (max-age, s-maxage, no-cache, no-store, private, public), what Vary does, how browsers, CDNs and proxies use them, and the difference between response caching and output caching in ASP.NET Core.

HTTP caching for APIs: Cache-Control directives, Vary, private vs shared caches and CDNs, and ASP.NET Core's response caching middleware vs output caching in .NET 10.

Intermediate Theory Intermediate aspnet-core cache-control cdn http-caching output-caching web-api

🎯 Key points

  • Cache-Control tells caches whether, where and how long to store a response
  • max-age for all caches, s-maxage for shared caches (CDN, proxy) only
  • no-cache = store but revalidate every time; no-store = never store (sensitive data)
  • must-revalidate = never serve stale without checking; stale-while-revalidate=N = serve stale for N s while refreshing in the background
  • private = browser only; public = shared caches allowed, even for authenticated responses
  • Vary lists request headers that change the response (Accept-Encoding, Accept-Language); Vary: Authorization effectively disables shared caching
  • Response caching follows HTTP rules and clients can bypass it; output caching is server-controlled with tags, stampede locking and a Redis store (.NET 8+)
  • Invalidate on writes (tags, ETags, versioned URLs) and measure hit ratio per layer

⏱ 30-second answer

Cache-Control tells every cache between the server and the client whether it may store a response and for how long. max-age applies to all caches, s-maxage only to shared caches (CDNs, proxies); private means only the browser may store it, public allows shared caches; no-cache means store but revalidate each time (with an ETag), and no-store means never store, which is what personal data needs. Vary lists request headers that change the response, so caches keep separate copies. In ASP.NET Core, response caching middleware implements these HTTP rules (clients can bypass it), while output caching is a server-side cache you control with policies, tags and an optional Redis store. The trade-off is freshness versus load.

🗣 Full answer (senior)

How I would answer this in an interview

"HTTP caching is controlled mostly by the Cache-Control response header, and the key idea is that there are two kinds of cache: private caches, like the browser, which serve one user, and shared caches, like Azure Front Door, a corporate proxy or a CDN, which serve many users. max-age=60 lets any cache reuse the response for 60 seconds; s-maxage overrides that for shared caches only; private keeps it out of shared caches; public explicitly allows them. no-cache is badly named: it means 'you may store this, but check with me before using it', which pairs with ETags. no-store means 'don't keep this anywhere', and that's what I use for anything with personal data.

Vary tells caches which request headers change the response. If I return gzip or Brotli depending on Accept-Encoding, or English or Vietnamese depending on Accept-Language, Vary makes the cache keep separate copies. In ASP.NET Core there are two server-side features that people confuse. Response caching middleware is an HTTP cache inside your app: it follows Cache-Control, and a client sending Cache-Control: no-cache bypasses it. Output caching, added in .NET 7, is a server cache you configure: policies per endpoint, vary by query or route values, tag-based eviction, stampede protection and, since .NET 8, a Redis store. It ignores client cache headers, because it exists to protect the server.

The mistake I see is public, max-age=300 on an endpoint that returns user-specific data, which lets a CDN serve one customer's account to another. Personal data gets private or no-store. Only shared, non-personal resources should ever be publicly cacheable."


Cache-Control directives (response)

Directive Meaning
max-age=N Fresh for N seconds in any cache
s-maxage=N Overrides max-age for shared caches
public Shared caches may store it, even if the request had Authorization
private Only the user's own cache may store it
no-cache May store, must revalidate before each use
no-store Must not store at all
must-revalidate Once stale, must not be served without revalidation
stale-while-revalidate=N May serve stale for N seconds while fetching a fresh copy
immutable Won't change while fresh (versioned static assets)

Response caching vs output caching

Response caching (UseResponseCaching) Output caching (UseOutputCache)
Model HTTP cache rules Server-controlled policies
Client can bypass Yes (Cache-Control: no-cache) No
Storage In-memory In-memory or Redis (.NET 8+)
Invalidation Expiry only Expiry plus tags (EvictByTagAsync)
Stampede protection No Yes (resource locking, on by default)
Typical use Rarely the best choice for APIs Expensive, shared GET endpoints

Production example

A [public product catalogue API] served the same category lists to every visitor. Adding Cache-Control: public, max-age=60, s-maxage=300 with an ETag let Azure Front Door absorb about 85% of catalogue traffic, and output caching with a products tag absorbed most of the remaining origin load; a product update evicted the tag so changes appeared within seconds on the origin and within five minutes at the edge.

🔍 What the interviewer is checking

Checks whether the candidate can use HTTP caching correctly and safely, and knows which ASP.NET Core feature fits which job.

Green flags

  • Explains no-cache vs no-store correctly
  • Distinguishes private and shared caches and the risk of public on personal data
  • Knows what Vary is for
  • Contrasts response caching (HTTP rules, bypassable) and output caching (server policies, tags, Redis)

Red flags

  • Believes no-cache disables caching
  • Caches authenticated responses publicly
  • Thinks response caching and output caching are the same

📚 Learn in depth

1. Freshness and validation

request -> cache has copy?
             no  -> forward to origin, store if allowed
             yes -> fresh (age < max-age)? -> serve from cache
                    stale -> revalidate: send If-None-Match / If-Modified-Since
                               304 -> refresh age, serve cached copy
                               200 -> replace copy

Freshness avoids the request entirely; validation avoids the body. Both reduce load in different ways.

2. Private vs shared caches

browser cache (private) -- corporate proxy (shared) -- CDN / Front Door (shared) -- origin

Shared caches serve the same stored response to many users, so anything user-specific must be private or no-store. Per RFC 9111, a shared cache must not store a response to a request with an Authorization header unless the response explicitly allows it (public, s-maxage or must-revalidate).

3. Cache keys and Vary

The default cache key is the method and URL. Vary: Accept-Encoding adds that header to the key. Vary: * or Vary: Authorization makes a response effectively uncacheable in shared caches, which is sometimes exactly what you want. CDNs often have their own query-string caching rules (ignore, include all, include specified), so the CDN configuration must match the API's design.

4. Output caching internals

  • AddOutputCache registers IOutputCacheStore (in-memory by default, AddStackExchangeRedisOutputCache for Redis).
  • The default policy caches only HTTP 200 responses to GET and HEAD, does not cache requests that are authenticated (Authorization header or authenticated user) and does not cache responses that set cookies.
  • Policies add Expire, SetVaryByQuery, SetVaryByRouteValue, SetVaryByHeader, VaryByValue and Tag.
  • Resource locking means one request populates the entry while concurrent identical requests wait, which prevents cache stampedes.
  • Output caching can store an ETag you set and answer If-None-Match with 304.

5. What to cache in an API

Resource Header
Reference data (countries, product categories) public, max-age=3600 + ETag
Search results shared by all users public, max-age=30 or output caching only
A user's own profile private, no-cache + ETag
Medical, financial or identity data no-store
POST responses Not cached

6. Australian context

Under the Privacy Act 1988 and the APPs, personal information leaked by a misconfigured shared cache is an unauthorised disclosure, potentially a notifiable data breach. Defaulting APIs to no-store for authenticated endpoints is a cheap control.

Try it yourself

  1. Add output caching to a Minimal API endpoint that returns DateTime.UtcNow; call it repeatedly and see the cached time.
  2. Add .CacheOutput(p => p.Tag("time")) and an admin endpoint that calls EvictByTagAsync("time", ct).
  3. Swap to UseResponseCaching with [ResponseCache(Duration = 30)] and send Cache-Control: no-cache from curl to bypass it.
  4. Use browser dev tools (Network tab, Size column) to see (disk cache) and 304 responses.
  5. Inspect Azure Front Door's X-Cache response header (TCP_HIT / TCP_MISS) for a cached endpoint.

💻 Code

Output caching with tags plus explicit HTTP cache headers for downstream caches:

using Microsoft.AspNetCore.OutputCaching;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOutputCache(o =>
{
    o.AddPolicy("catalogue", p => p
        .Expire(TimeSpan.FromMinutes(5))
        .SetVaryByQuery("page", "pageSize")
        .Tag("products"));
});
// Multi-instance: share entries and evictions across instances (.NET 8+).
// builder.Services.AddStackExchangeRedisOutputCache(o => o.Configuration = builder.Configuration.GetConnectionString("Redis"));

var app = builder.Build();
app.UseOutputCache();

// Shared, non-personal data: cacheable by browsers (60 s) and CDNs (300 s).
app.MapGet("/categories/{id:int}/products", (int id, HttpContext http) =>
{
    http.Response.Headers.CacheControl = "public, max-age=60, s-maxage=300";
    http.Response.Headers.Vary = "Accept-Encoding";
    return Results.Ok(new[] { new { Id = 1, Name = "Kettle", CategoryId = id } });
}).CacheOutput("catalogue");

// Personal data: never stored by shared caches, revalidated by the browser.
app.MapGet("/me/orders", (HttpContext http) =>
{
    http.Response.Headers.CacheControl = "private, no-store";
    return Results.Ok(Array.Empty<object>());
}).RequireAuthorization();

// Writes evict the tag so the next read is fresh.
app.MapPut("/products/{id:int}", async (int id, IOutputCacheStore cache, CancellationToken ct) =>
{
    // ... update the product ...
    await cache.EvictByTagAsync("products", ct);
    return Results.NoContent();
}).RequireAuthorization();

app.Run();

⚠ Common mistakes

  • Mistake: Thinking no-cache means "don't cache". Why it is wrong: it means store but revalidate before each use. Instead: use no-store when the response must not be kept.
  • Mistake: public caching on user-specific responses. Why it is wrong: a CDN or proxy can serve one user's data to another, which is a privacy breach. Instead: private or no-store for anything personal.
  • Mistake: Forgetting Vary when the response depends on a header. Why it is wrong: a cache serves a Brotli body to a client that can't decode it, or the wrong language. Instead: Vary on every header that changes the representation.
  • Mistake: Using response caching middleware to protect the server. Why it is wrong: clients can bypass it with Cache-Control: no-cache. Instead: use output caching for server-side protection.
  • Mistake: Caching with no invalidation plan. Why it is wrong: writes succeed but readers see old data until expiry, which users report as "my change didn't save". Instead: evict output cache tags on every write path, keep CDN s-maxage within the staleness the business accepts, and use versioned URLs for assets.
  • Mistake: ETags that don't change when the representation does (for example a row version that ignores child rows or the requested language). Why it is wrong: clients get 304 and keep stale or wrong content indefinitely. Instead: derive the ETag from everything that shapes the response, and make it differ per representation when Vary applies.
  • Mistake: In-memory output caching on several instances with tag eviction. Why it is wrong: eviction only clears the instance that handled the write; others serve stale data until expiry. Instead: use the Redis output cache store (Microsoft.AspNetCore.OutputCaching.StackExchangeRedis) or short expiries.
  • Mistake: Overriding the output cache's default policy to cache authenticated endpoints without varying by user. Why it is wrong: one user's response is served to everyone. Instead: keep authenticated responses out of shared caches, or vary by a user claim deliberately.
  • Mistake: Long max-age without versioning or ETags. Why it is wrong: clients keep stale data with no way to refresh. Instead: short max-age plus ETags, or versioned URLs with immutable.

🏛 Senior insight: trade-offs

Caching is a correctness problem before it is a performance one. I first classify every endpoint: shared and non-personal, personal, or sensitive. Only the first class gets public; everything authenticated defaults to no-store unless there's a reason otherwise. Then I choose the layer: the CDN for global, shared, read-heavy content; output caching for expensive shared queries at the origin; HybridCache or IMemoryCache for data used inside handlers; browser caching with ETags for per-user data.

Measure hit ratio per layer (Front Door's cache hit ratio, output cache hits through logs or metrics) and origin load before and after. A cache with a 20% hit rate adds complexity for little gain.

Option When it fits Cost When not to
CDN with s-maxage Global, public, read-heavy data Purge latency, stale edges Personal or fast-changing data
Output caching (Redis store) Expensive shared GETs, multi-instance Redis dependency, invalidation design Per-user responses
Browser cache with ETag + no-cache Per-user data that changes occasionally One revalidation round trip Sensitive data (use no-store)
No caching (no-store) Sensitive or highly personal data Full cost every time Shared reference data

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions revalidation or 304 responses Why: Checks ETags and conditional requests in depth
    How to answer

    An ETag is an opaque version identifier for a representation of a resource, returned in the ETag header. Clients send it back in conditional requests. On a GET, If-None-Match lets the server answer 304 Not Modified with no body when nothing changed, saving bandwidth. On a PUT, PATCH or DELETE, If-Match makes the write conditional: if someone else changed the resource since the client read it, the server returns 412 Precondition Failed instead of silently overwriting their change (the lost update problem). A SQL Server rowversion column, mapped with EF Core's IsRowVersion, makes a natural strong ETag. The trade-off: clients must read before they write and handle 412 by refreshing and retrying.

  2. When: Candidate mentions tags or eviction Why: Checks multi-layer invalidation design
    How to answer

    Use a shared output cache store (Redis) so EvictByTagAsync clears every instance, not just the one that handled the write. At the CDN, keep s-maxage short or purge by path through the CDN API (an Azure Front Door purge can take minutes). For data that must change quickly, avoid purging altogether: content-hash or versioned URLs (/catalogue?v=42) make the new version a new cache key, and ETags let clients revalidate cheaply with If-None-Match and get 304 when nothing changed. Decide the acceptable staleness per endpoint; stale-while-revalidate keeps responses fast while the edge refreshes, and the client should re-read after its own write so users see their change.

↩ Usually asked after

More in API Reliability

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me