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.
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.
"HTTP caching is controlled mostly by the
Cache-Controlresponse 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=60lets any cache reuse the response for 60 seconds;s-maxageoverrides that for shared caches only;privatekeeps it out of shared caches;publicexplicitly allows them.no-cacheis badly named: it means 'you may store this, but check with me before using it', which pairs with ETags.no-storemeans 'don't keep this anywhere', and that's what I use for anything with personal data.
Varytells caches which request headers change the response. If I return gzip or Brotli depending onAccept-Encoding, or English or Vietnamese depending onAccept-Language,Varymakes 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 followsCache-Control, and a client sendingCache-Control: no-cachebypasses 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=300on an endpoint that returns user-specific data, which lets a CDN serve one customer's account to another. Personal data getsprivateorno-store. Only shared, non-personal resources should ever be publicly cacheable."
| 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 (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 |
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.
Checks whether the candidate can use HTTP caching correctly and safely, and knows which ASP.NET Core feature fits which job.
Green flags
Red flags
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.
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).
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.
AddOutputCache registers IOutputCacheStore (in-memory by default, AddStackExchangeRedisOutputCache for Redis).Expire, SetVaryByQuery, SetVaryByRouteValue, SetVaryByHeader, VaryByValue and Tag.If-None-Match with 304.| 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 |
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.
DateTime.UtcNow; call it repeatedly and see the cached time..CacheOutput(p => p.Tag("time")) and an admin endpoint that calls EvictByTagAsync("time", ct).UseResponseCaching with [ResponseCache(Duration = 30)] and send Cache-Control: no-cache from curl to bypass it.(disk cache) and 304 responses.X-Cache response header (TCP_HIT / TCP_MISS) for a cached endpoint.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();
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.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.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.Cache-Control: no-cache. Instead: use output caching for server-side protection.s-maxage within the staleness the business accepts, and use versioned URLs for assets.Vary applies.Microsoft.AspNetCore.OutputCaching.StackExchangeRedis) or short expiries.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.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 |
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.
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.
Last updated 23 Nov 2026.