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

📚 Interview question

After you turned on output caching, a customer reports seeing another customer's account details, and other users complain that changes they save don't show up for several minutes. How do you diagnose and fix both problems in an ASP.NET Core API, and how do you make sure caching can't leak data again?

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.

Senior Debugging Advanced aspnet-core debugging output-caching privacy security web-api

🎯 Key points

  • Treat a cross-user leak as a security incident: disable caching first, then investigate, then assess NDB obligations
  • A cached response skips authorisation: only data every caller may see belongs in a shared cache
  • Default output cache policy skips authenticated requests; custom IOutputCachePolicy or overrides can bypass that
  • Per-user or per-role responses need the user id (or the full permission set) in the key, or no shared caching at all
  • Check the CDN too: Cache-Control: public on authenticated responses lets Front Door share them
  • Stale data: in-memory store per instance means EvictByTagAsync only clears one instance; use Redis and evict after commit
  • Prevent with two-user tests, a reviewed allow-list of cacheable endpoints and Cache-Control: no-store by default
  • Use response headers (Age, X-Cache) and logs to prove which layer served the data

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 Age header or Front Door's X-Cache: TCP_HIT means 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/account was 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's sub claim. At the CDN, the endpoint had Cache-Control: public, max-age=60, which allows shared caches to store authenticated responses. Personal endpoints got private, 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."


Symptoms to causes

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

Fixes

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

Production example

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.

🔍 What the interviewer is checking

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

  • Disables caching and purges the CDN before investigating; mentions breach assessment
  • Knows the default policy skips authenticated requests and how custom policies bypass it
  • Checks the CDN layer and Cache-Control headers
  • Explains in-memory vs Redis store and evict-after-commit
  • Proposes two-user tests and an allow-list

Red flags

  • Keeps caching on while debugging
  • Fixes by shortening expiry
  • Doesn't consider the CDN or Privacy Act obligations

📚 Learn in depth

1. Where cached data can come from

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.

2. The output cache's safety rules

The built-in default policy (included by OutputCachePolicyBuilder, so in .CacheOutput(b => ...) and named policies built with AddPolicy(name, b => ...)):

  • caches only GET and HEAD,
  • caches only 200 responses,
  • does not cache when the request has an authenticated user or an Authorization header,
  • does not cache responses that set cookies.

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.

3. The cache key

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.

4. The CDN layer

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.

5. Staleness on multiple instances

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.

6. Incident obligations

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

Try it yourself

  1. Build an endpoint returning the caller's name, apply a broad custom IOutputCachePolicy, and call it with two different tokens; see the leak.
  2. Switch to .CacheOutput() with default rules and confirm authenticated requests aren't cached.
  3. Add VaryByValue on sub and confirm separate entries.
  4. Run two instances with the in-memory store, update data through one, read through the other.
  5. Switch to the Redis store and repeat.
  6. Write an integration test with WebApplicationFactory that requests as two users and asserts different responses.

💻 Code

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
}

⚠ Common mistakes

  • Mistake: Investigating a leak while caching stays on. Why it is wrong: more customers are exposed every minute. Instead: disable caching and purge the CDN first, then diagnose.
  • Mistake: Writing a raw 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.
  • Mistake: Caching per-user responses without the user in the key. Why it is wrong: the first user's response is served to everyone. Instead: don't cache personal data in shared caches, or vary by the user id claim.
  • Mistake: 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.
  • Mistake: In-memory output cache on several instances with tag eviction. Why it is wrong: eviction clears only one instance. Instead: the Redis store or short expiries.
  • Mistake: Evicting before the transaction commits. Why it is wrong: a concurrent request re-caches the old data. Instead: commit, then evict.
  • Mistake: Treating the leak as a bug ticket only. Why it is wrong: it may be an eligible data breach under the Privacy Act. Instead: run it as a security incident with a breach assessment.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Cache-Control directives or the CDN Why: Checks HTTP caching header knowledge
    How to 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.

  2. When: Candidate proposes the Redis store or tag 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.

  3. When: Candidate talks about handling failures in middleware globally Why: Checks global exception handling and middleware ordering
    How to answer

    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.

🛠 Real-world problems: how you handle them

Output cache serves one customer's account to another
Situation
A [customer portal API] on [4] App Service instances behind Azure Front Door; output caching was added to cut database load, with a custom base policy and the in-memory store.
Signals
A customer report of seeing someone else's name and address on the account page; support tickets that saved changes 'revert' for a few minutes; output cache hit rate jumping to [85%] after the release.
Investigation
Reproduced with two test accounts and curl against the origin, bypassing Front Door, which proved the app cache was serving the leak; read the output cache configuration and found a raw IOutputCachePolicy as base policy; checked Front Door caching rules and found `Cache-Control: public, max-age=60` on account endpoints; hit each instance directly to show stale reads after an update; queried request logs for the exposure window and affected user ids.
Resolution
Disabled output caching via configuration and purged Front Door within [5 minutes]. Removed the custom base policy, applied named policies only to catalogue endpoints, set `private, no-store` on personal endpoints, moved to the Redis output cache store and evicted tags after commit. Ran a breach assessment with the privacy officer and notified affected customers.
Prevention
Two-user integration tests for every authenticated endpoint, an allow-list of cacheable endpoints reviewed as a security change, a rule in the API guidelines that authenticated responses default to no-store, and a dashboard for cache hit ratio and write-to-read freshness.

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.

More in API Reliability

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me