Investigating a cache that serves stale or cross-user data: incident containment, Privacy Act notifiable data breach assessment, finding missing key dimensions (user, tenant, culture, version), output and CDN caching of authenticated responses, and preventive design and tests.
Cross-user data is a security incident first, a caching bug second. I'd contain it immediately (disable or bypass the cache for the endpoint, flush the affected keys), preserve logs, and start a Notifiable Data Breaches assessment under the Privacy Act.
Then I find the key: compare the cache key with every input that changes the response, such as user, tenant, role, culture, query string or API version. Typical causes are a key missing the user or tenant, output or CDN caching of authenticated responses, or a singleton capturing scoped user state. Stale data usually means no invalidation on write or long L1 lifetimes.
The fix is a typed key builder, Cache-Control: private for personal responses, and a two-user test. The trade-off is hit ratio versus isolation.
"I'd split this into two problems, because they have different urgency. Stale data is a correctness bug. One user seeing another user's account details is a data breach, so that drives the first hour: contain it, keep evidence, and bring in whoever owns privacy and security. Containment is usually quick: turn off the cache for the affected endpoint with a feature flag or config, flush the affected keys or bump the key version, and if a CDN is involved, purge it. Then, under the Notifiable Data Breaches scheme in the Privacy Act, we have to assess within 30 days whether serious harm is likely and, if so, notify the OAIC and the affected people, so I'd start capturing which users were exposed from logs.
For example, at [company] [a profile endpoint] was cached with
[OutputCache]using the default policy. After [a change that made the endpoint authenticated], responses were cached by path alone, so the first user's profile was served to everyone hitting the same path for [60 seconds]. I found it by listing every input that changes the response, user, tenant, culture, query, and comparing it with what actually went into the cache key. The user id wasn't there. The fix was to stop caching that response in shared layers, setCache-Control: private, no-store, and add an integration test that logs in as two users and asserts each sees only their own data. [Number] users were potentially affected; we [notified / assessed as unlikely to cause serious harm].For the stale-data reports, I'd check whether writes invalidate the cache, whether instances have long-lived local caches, and whether code updates the cache instead of deleting it. The mistake I see is building keys by hand with string concatenation in many places. I want one typed key builder that forces the developer to state the scope: global, tenant or user."
| Symptom | Likely causes | First checks |
|---|---|---|
| Another user's data | Key missing user/tenant; output/CDN caching an authenticated response; Vary missing; scoped user state captured in a singleton; mutable cached object |
Cache key composition, cache policies, response Cache-Control, DI lifetimes |
| Old data after an edit | No invalidation on write; update-not-delete race; long L1 on other pods; CDN TTL | Write path, LocalCacheExpiration, CDN rules |
| Wrong language or currency | Culture not in key or Vary: Accept-Language missing |
Key and VaryByHeader |
| Data from a previous version | DTO shape changed but key version didn't | Versioned key prefix |
| Layer | Leak mechanism | Safe default |
|---|---|---|
| Output caching | Default policy doesn't cache authenticated requests, but custom policies or [OutputCache] overrides can |
Never vary-less caching for personal responses |
| CDN / Front Door | Caches responses with Cache-Control: public or missing headers per rules |
Cache-Control: private, no-store on personal data |
| HybridCache / Redis | Key lacks user/tenant | Typed key builder with explicit scope |
| Singleton service | Captures IHttpContextAccessor data or a scoped service |
Lifetimes validated with ValidateScopes |
After the fix, the two-user integration test ran on every pull request, and an audit of all 40 cached endpoints found two more with missing tenant ids in the key. No further reports in the following [six months], with the cache hit ratio for public endpoints unchanged at about 93%.
Checks that the candidate handles a cache leak as a security incident, can systematically find the faulty key or layer, and designs caching that is isolated by default.
Green flags
Red flags
A cached response is correct only if every input that can change the output is part of the key (or the response is identical for all values of that input):
response = f(path, query, user, tenant, roles, culture, api-version, feature flags, data version)
key must include every argument that varies, or the layer must not be shared
ASP.NET Core output caching's default policy only caches GET/HEAD 200 responses, and doesn't cache requests with an Authorization header or responses that set cookies. Leaks happen when a custom policy overrides that (for example to cache an authenticated endpoint for performance) without adding VaryByValue for the user. Response caching middleware and CDNs follow HTTP headers instead, so a missing or public Cache-Control on a personal response is the danger.
Centralise key creation:
CacheKey.Global("categories") -> "g:categories:v1"
CacheKey.ForTenant(tenantId, "settings") -> "t:{tenant}:settings:v1"
CacheKey.ForUser(tenantId, userId, "profile") -> "u:{tenant}:{user}:profile:v1"
Code review then checks the scope choice, not string formatting. Include a version so DTO changes don't deserialise old shapes.
Under Part IIIC of the Privacy Act 1988, an eligible data breach is unauthorised access to or disclosure of personal information likely to result in serious harm. The entity must assess a suspected breach within 30 days and, if eligible, notify the OAIC and affected individuals as soon as practicable. Fast containment and good logs (which user received which response) determine how many people you must treat as affected.
[OutputCache] with a custom policy to an authenticated endpoint, log in as two users and see the leak; then fix with VaryByValue or remove caching.CacheKey builder and an analyser-style unit test that fails if any cache call uses a raw string.Cache-Control headers.ValidateScopes and ValidateOnBuild and see whether any singleton captures a scoped service.WebApplicationFactory that runs on every PR.A typed cache key builder that forces an explicit scope, and an integration test that catches cross-user leaks.
namespace Accounts.Caching;
// Every key states its scope; reviewers check the scope, not string concatenation.
public readonly record struct CacheKey(string Value)
{
private const string Version = "v2"; // bump when the cached DTO shape changes
public static CacheKey Global(string name) => new($"g:{name}:{Version}");
public static CacheKey ForTenant(Guid tenantId, string name) => new($"t:{tenantId:N}:{name}:{Version}");
public static CacheKey ForUser(Guid tenantId, Guid userId, string name) =>
new($"u:{tenantId:N}:{userId:N}:{name}:{Version}");
public override string ToString() => Value;
}
using System.Security.Claims;
using Microsoft.Extensions.Caching.Hybrid;
namespace Accounts.Profiles;
public sealed record ProfileDto(Guid UserId, string DisplayName, string Email);
public interface IProfileStore
{
Task<ProfileDto> GetAsync(Guid tenantId, Guid userId, CancellationToken ct);
}
public static class ProfileEndpoints
{
public static void MapProfile(this WebApplication app) =>
app.MapGet("/me/profile", async (ClaimsPrincipal user, HybridCache cache, IProfileStore store,
HttpContext http, CancellationToken ct) =>
{
var tenantId = Guid.Parse(user.FindFirstValue("tid")!);
var userId = Guid.Parse(user.FindFirstValue(ClaimTypes.NameIdentifier)!);
var profile = await cache.GetOrCreateAsync(
CacheKey.ForUser(tenantId, userId, "profile").Value, // user-scoped key
(store, tenantId, userId),
static async (s, token) => await s.store.GetAsync(s.tenantId, s.userId, token),
new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(2) },
cancellationToken: ct);
// Personal data must never be stored by shared caches (CDN, proxies).
http.Response.Headers.CacheControl = "private, no-store";
return TypedResults.Ok(profile);
}).RequireAuthorization();
}
// Integration test: two users, same endpoint, each must see only their own data.
public sealed class ProfileIsolationTests(ApiFactory factory) : IClassFixture<ApiFactory>
{
[Fact]
public async Task Each_user_sees_only_their_own_profile()
{
var alice = factory.CreateClientFor(TestUsers.Alice);
var bob = factory.CreateClientFor(TestUsers.Bob);
var a = await alice.GetFromJsonAsync<ProfileDto>("/me/profile");
var b = await bob.GetFromJsonAsync<ProfileDto>("/me/profile");
var a2 = await alice.GetFromJsonAsync<ProfileDto>("/me/profile"); // served from cache
Assert.Equal(TestUsers.Alice.Id, a!.UserId);
Assert.Equal(TestUsers.Bob.Id, b!.UserId);
Assert.Equal(TestUsers.Alice.Id, a2!.UserId);
}
}
public Cache-Control on personal responses. Why it is wrong: CDNs and proxies may store and serve them. Instead: private, no-store.ValidateScopes.The senior point is that a cache is a copy of data with a different access-control model: whoever can reach the key gets the value. Personal data in a shared cache layer needs the same isolation guarantees as the database, which in practice means scoping keys explicitly, keeping personal responses out of HTTP-level caches, and testing isolation automatically. The expected performance gain on personal endpoints is usually small anyway.
| Layer for personal data | When it fits | Cost | When not to |
|---|---|---|---|
| None | Default for personal responses | Source load | Hot personal data that is expensive to build |
| HybridCache with user-scoped key | Expensive, frequently re-read personal data | Memory per user; still subject to APP 11 | Shared or public layers |
| Output cache varied by user | Rarely justified | Huge key space, risk on policy changes | Almost always |
| CDN | Never for personal data | n/a | Always |
Measure isolation with automated two-user tests per cached endpoint, and track hit ratio per endpoint to show whether caching personal data earns its risk.
First contain it: it is a likely data breach, so switch off the suspect path, preserve logs and start the Notifiable Data Breaches assessment. Then look for shared state, because a leak you cannot reproduce locally usually needs concurrency:
AddDbContextPool reusing a context whose tenant field was set once in the constructor.DbContext.Reproduce it with a load test that alternates tenants and checks every row. Fix by disabling pooling or setting the tenant on every lease, and add row-level security as a backstop. The trade-off: pooling saves microseconds per request, and a leak costs far more.
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.
I treat the TTL as the upper bound on staleness and explicit invalidation as a way to do better for changes I control.
RemoveByTagAsync) to invalidate groups, such as every cached view of product 42, without tracking keys.catalogue:v{n}:...): bump n and old entries are simply never read again.I choose a TTL from how stale the business can accept, how often the data changes and how expensive it is to rebuild, then add jitter. The trade-off is freshness versus load and latency.
How to tell it (STAR)
**S:** At [company] two customers reported seeing another person's profile shortly after we added output caching to reduce campaign load. **T:** As [the engineer on call / the tech lead], I had to contain it, work out who was exposed and make sure it couldn't recur. **A:** I reproduced it with two accounts, found the cache policy keyed only by path, and pulled the policy within [15 minutes]. I worked with our privacy officer on the Notifiable Data Breaches assessment using request logs to identify [N] affected users, then moved caching to a user-scoped key and added a two-user test for every cached endpoint. **R:** The leak window was limited to [about 40 minutes], the assessment [outcome], and the audit caught [two] more endpoints with missing tenant ids before they caused harm.
Last updated 23 Nov 2026.