Debugging ASP.NET Core output caching: cross-user data leaks from custom policies, missing vary keys and public Cache-Control, stale data from in-memory stores on multiple instances and missing tag eviction, and the controls that prevent it.
A cross-user leak is a security incident: switch caching off (a feature flag or removing UseOutputCache) and purge the CDN before diagnosing. The usual causes: a custom IOutputCachePolicy or overridden base policy that caches authenticated responses (the default policy deliberately doesn't), a cache key that doesn't vary by user, or Cache-Control: public letting Azure Front Door share a personal response. The stale-data complaint is usually the in-memory store on several instances: EvictByTagAsync only clears the instance that handled the write, or an endpoint lacks the tag. Fix with no shared caching for personal data (or VaryByValue on the user id), the Redis store, tags on every cached endpoint and eviction after commit. Prevent it with two-user tests and an allow-list of cacheable endpoints.
"These are two different bugs and the first is a data breach, so I'd treat them differently. For the leak, I'd stop it before I understand it: disable output caching through configuration, purge Azure Front Door, and open a security incident, because under the Privacy Act we may need to assess a notifiable data breach within 30 days. Then I'd find which layer served the wrong data. The response headers tell you: an
Ageheader or Front Door'sX-Cache: TCP_HITmeans the CDN served it; otherwise it's the app's output cache.In the app, the default output cache policy is safe: it doesn't cache requests with an authenticated user or an Authorization header, and it doesn't cache responses that set cookies. Leaks come from code that bypasses those rules. For example, at [company] [someone copied the custom policy sample from the docs, which enables caching for authenticated requests, and applied it as the base policy], so
/me/accountwas cached under one key for everyone. The fix was to remove caching from personal endpoints entirely, and where per-user caching really paid off, vary by the user'ssubclaim. At the CDN, the endpoint hadCache-Control: public, max-age=60, which allows shared caches to store authenticated responses. Personal endpoints gotprivate, no-store.The stale-data problem was the in-memory store on [four] instances. The write called
EvictByTagAsync, but only on the instance that handled the PUT, and the other three served their copies until expiry. Moving to the Redis output cache store fixed that, along with making sure every cached endpoint carried the tag and eviction ran after the transaction committed. The mistake I see is treating caching as a performance setting. It's an authorisation decision: a cache is a copy of data served without running your authorisation code."
| Symptom | Likely cause | How to confirm |
|---|---|---|
| User A sees user B's data | Authenticated responses cached without per-user key | Two-user curl test with different tokens; output cache logs |
| Leak only through the website, not direct to origin | CDN caching public responses |
X-Cache, Age headers; Front Door rules |
| Changes visible on some refreshes, not others | In-memory store per instance | Hit each instance directly; compare responses |
| Changes never visible until expiry | Endpoint missing the tag, or eviction before commit | Read policy configuration; check eviction order |
| Stale data after deploys only | CDN TTL longer than expected | Front Door caching rules, s-maxage |
| Problem | Fix |
|---|---|
| Personal endpoint cached | Remove .CacheOutput(); send Cache-Control: private, no-store |
| Per-user caching needed | VaryByValue on the user id claim; never share across users |
| Custom policy too broad | Build on OutputCachePolicyBuilder (which includes the default rules) rather than a raw IOutputCachePolicy |
| Multi-instance staleness | AddStackExchangeRedisOutputCache |
| Missing invalidation | Tag every cached endpoint; evict after commit |
In a [customer portal API] on [4] instances, a broad custom base policy cached /me/account for 60 seconds under one key; [a handful of] customers saw others' details over [2 hours]. Disabling caching took 5 minutes; the fix (no caching on personal endpoints, Redis store, tags, two-user integration tests) kept the 70% hit rate on catalogue endpoints, and the incident was assessed and reported under the NDB scheme.
Checks whether the candidate treats a caching leak as a security incident, knows how output caching decides what to cache and how keys work, and can fix multi-instance staleness.
Green flags
Red flags
browser cache -> Azure Front Door (shared) -> app instance output cache (shared within instance or via Redis) -> handler
private honours Cache-Control server-side policy runs authorisation
Every shared layer serves a stored response without running the handler, so without running your authorisation checks. The cache key decides who gets which copy.
The built-in default policy (included by OutputCachePolicyBuilder, so in .CacheOutput(b => ...) and named policies built with AddPolicy(name, b => ...)):
Authorization header,A class implementing IOutputCachePolicy directly starts from nothing: if its CacheRequestAsync sets EnableOutputCaching, AllowCacheLookup and AllowCacheStorage to true unconditionally, authenticated responses are cached. Microsoft's docs include such a sample to show how to cache POSTs and authenticated requests; copying it as a base policy is a classic leak.
The default key is the scheme, host, path and, depending on policy, query values. It does not include the user. Per-user caching requires VaryByValue(ctx => new("user", ctx.User.FindFirst("sub")?.Value ?? "")) or SetVaryByHeader("Authorization") (the latter creates an entry per token, including every refresh). Most per-user data isn't worth caching at all: the per-user hit rate is low and the risk high.
Per RFC 9111, shared caches must not store responses to requests with Authorization unless the response has public, s-maxage or must-revalidate. Front Door caching also depends on its rules (query string behaviour, caching enabled per route). Cookie-authenticated requests are worse: the request has no Authorization header, so a public or max-age response may be cached by a shared cache.
PUT /products/7 -> instance B: commit, EvictByTagAsync("products") clears B only
GET /products -> instance A: cached copy (stale for up to Expire)
The Redis store (Microsoft.AspNetCore.OutputCaching.StackExchangeRedis) shares entries and tag evictions. Evict after the transaction commits; evicting before commit lets a concurrent reader re-cache the old data.
Under the Privacy Act 1988, an eligible data breach (unauthorised disclosure likely to cause serious harm) must be assessed within 30 days and, if eligible, notified to the OAIC and affected individuals. Keep evidence: which endpoints, time window, which users could have been served whose data (output cache logs and request logs with user ids).
IOutputCachePolicy, and call it with two different tokens; see the leak..CacheOutput() with default rules and confirm authenticated requests aren't cached.VaryByValue on sub and confirm separate entries.WebApplicationFactory that requests as two users and asserts different responses.Before: a broad custom policy applied as the base policy, the source of the leak.
using Microsoft.AspNetCore.OutputCaching;
namespace Portal;
// DON'T: starts from nothing, so it caches authenticated requests under a shared key.
public sealed class CacheEverythingPolicy : IOutputCachePolicy
{
public ValueTask CacheRequestAsync(OutputCacheContext context, CancellationToken ct)
{
context.EnableOutputCaching = true;
context.AllowCacheLookup = true;
context.AllowCacheStorage = true;
context.ResponseExpirationTimeSpan = TimeSpan.FromSeconds(60);
return ValueTask.CompletedTask;
}
public ValueTask ServeFromCacheAsync(OutputCacheContext context, CancellationToken ct) => ValueTask.CompletedTask;
public ValueTask ServeResponseAsync(OutputCacheContext context, CancellationToken ct) => ValueTask.CompletedTask;
}
// builder.Services.AddOutputCache(o => o.AddBasePolicy(new CacheEverythingPolicy())); // the bug
After: shared data cached explicitly with tags in Redis; personal data not cached anywhere.
using Microsoft.AspNetCore.OutputCaching;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOutputCache(o =>
{
// Named policy built on OutputCachePolicyBuilder: keeps the default safety rules.
o.AddPolicy("catalogue", b => b.Expire(TimeSpan.FromMinutes(5)).Tag("products"));
});
builder.Services.AddStackExchangeRedisOutputCache(o =>
o.Configuration = builder.Configuration.GetConnectionString("Redis")); // shared entries and evictions
builder.Services.AddAuthentication(/* ... */);
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseOutputCache();
app.MapGet("/products", () => Results.Ok(new[] { new { Id = 7, Name = "Kettle" } }))
.CacheOutput("catalogue");
app.MapGet("/me/account", (HttpContext http) =>
{
http.Response.Headers.CacheControl = "private, no-store"; // keeps Front Door and proxies out too
return Results.Ok(new { Name = http.User.Identity?.Name });
}).RequireAuthorization(); // no CacheOutput: personal data is never in a shared cache
app.MapPut("/products/{id:int}", async (int id, IOutputCacheStore cache, CancellationToken ct) =>
{
// await db.SaveChangesAsync(ct); // commit first...
await cache.EvictByTagAsync("products", ct); // ...then evict, on every instance via Redis
return Results.NoContent();
}).RequireAuthorization();
app.Run();
A regression test that would have caught the leak:
[Fact]
public async Task Account_is_never_shared_between_users()
{
await using var factory = new WebApplicationFactory<Program>();
var alice = factory.CreateClient(); alice.DefaultRequestHeaders.Authorization = new("Test", "alice");
var bob = factory.CreateClient(); bob.DefaultRequestHeaders.Authorization = new("Test", "bob");
var a = await alice.GetStringAsync("/me/account");
var b = await bob.GetStringAsync("/me/account");
Assert.Contains("alice", a);
Assert.Contains("bob", b); // fails if Bob is served Alice's cached response
}
IOutputCachePolicy that enables caching unconditionally. Why it is wrong: it drops the default rules that skip authenticated requests. Instead: build on OutputCachePolicyBuilder or explicitly check context.HttpContext.User.Identity?.IsAuthenticated.Cache-Control: public on authenticated endpoints. Why it is wrong: it explicitly allows the CDN to store and share the response. Instead: private, no-store on personal endpoints.A cache is a copy of data that skips your authorisation code. Once you see it that way, the rule follows: only data that every caller is allowed to see may go into a shared cache. I enforce it structurally: an allow-list of cacheable endpoints reviewed like security changes, no-store as the default for authenticated endpoints, and an automated two-user test for every cached route. Per-user caching rarely pays off; if it does, it belongs in a per-user store keyed by user id inside the handler (HybridCache), after authorisation has run.
Role- or permission-based caching is where teams get clever and get burnt. Varying by a role claim (VaryByValue(ctx => new("role", ...))) is only safe if the response depends on nothing but that role; the moment the handler also filters by tenant, region or record-level permissions, two users with the same role see each other's data. If you do it, build the key from the complete set of inputs the authorisation logic uses (tenant id plus permission set hash), and test it with two users who share a role but not a tenant.
On Azure: use Azure Managed Redis (or Azure Cache for Redis) in the same region as the app (Australia East) with private endpoints for the output cache store; configure Front Door routes so caching is enabled only on the catalogue paths and disabled on /me/* and other authenticated routes, rather than relying on headers alone; and alert on Front Door cache hit ratio per route so a cache suddenly appearing on an authenticated route is visible.
For staleness, decide the acceptable staleness per endpoint with the product owner and design invalidation to match. Measure hit ratio and the time from write to visible read; a cache that is 99% hits but makes users think saves fail is a bad trade.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Output caching (Redis) for shared data | Catalogue, reference data, public search | Redis, invalidation design | Any per-user or permission-filtered data |
| VaryByValue on user id | Expensive per-user views with high reuse | Many entries, leak risk if misconfigured | Most per-user endpoints |
| Vary by tenant + permission hash | Tenant-wide dashboards identical for a permission set | Key design and tests | Record-level permissions |
| HybridCache inside the handler after authorisation | Per-user or per-tenant data | Code in the handler | When the response itself is cheap |
No caching, no-store |
Personal, financial, health data | Full cost per request | Shared reference data |
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.
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.
In ASP.NET Core, register AddProblemDetails(), one or more IExceptionHandler implementations (.NET 8+) with AddExceptionHandler<T>(), and app.UseExceptionHandler() early in the pipeline. Handlers log once and map known exceptions to the right status code and an RFC 9457 ProblemDetails body, and never leak stack traces in production. For the process as a whole, AppDomain.CurrentDomain.UnhandledException is a last-chance notification: you can log and flush, but the process still terminates. TaskScheduler.UnobservedTaskException fires when a faulted task that nobody awaited is garbage-collected; it does not crash the process by default. In a BackgroundService, an unhandled exception in ExecuteAsync stops the host by default (.NET 6+). async void exceptions go to the synchronisation context and usually crash the process, so avoid async void except for event handlers.
How to tell it (STAR)
**S:** At [company], a week after we enabled output caching on the [customer portal API], a customer reported seeing another customer's account details. **T:** I had to stop the exposure, find the cause and make sure caching couldn't leak data again, while also fixing complaints about stale saves. **A:** I disabled caching through configuration and purged Front Door within [five minutes], then reproduced the leak with two test accounts against the origin. The cause was a custom base policy that cached authenticated responses under one key, plus `public` headers that let the CDN share them. I limited caching to catalogue endpoints, set `no-store` on personal data, moved to the Redis store to fix stale reads across instances, and added two-user tests. I also worked with our privacy officer on the NDB assessment. **R:** We kept a [70%] hit rate on catalogue endpoints, stale-save complaints stopped, and the two-user tests have since caught [N] risky caching changes before release.
Last updated 23 Nov 2026.