Module 1 · Safe reads and concurrent cache refreshes · Lesson 1 of 12
Cache Keys, Tenant Boundaries, and Cache-Aside Reads
Two authorized callers, one wrong price
Tenant A primes product 42 at 80. Tenant B is allowed to read its own price 100. Can a cache hit still return the wrong authorized tenant’s value? Predict the A, B, A trace before checking the key implementation.
Read with a purpose. Read Run and its nested Read first. Compare the supplied key function, then inspect Joined, Prefixed, CatalogKey and TextKey to separate value identity from string encoding.
Entry check: this course assumes C# tasks, cancellation, basic DI and HTTP request/response concepts. The first program isolates key behavior with synthetic trusted callers; it does not configure authentication.
Commit to a prediction
Use the existing sequential A, B, A reads for product 42. Both tenants are authorized; A’s source price is 80 and B’s is 100. Which result establishes key isolation under the typed tenant/product key?
Show answer
Correct answer: B
The key separates two legitimate response values, and A’s repeat hits its own entry. One source read in the broken design serves B the wrong price. A typed key neither changes other entries nor grants permission to later callers.
Companion program: the key-isolation trace as code
This console example implements the paper trace and asserts the expected results of each design. It intentionally keeps the broken design so the test demonstrates the leak, not because that design is safe. One program processes exactly A, B, A and prints each returned price and the number of source reads. It then shows the colon-join collision and two encodings that avoid it. Authorization is assumed to have happened before each read, as the lesson requires. This program tests key behavior, not authentication.
Use a .NET 10 console project with implicit usings enabled and a reference to Microsoft.Extensions.Caching.Memory 10.0.0. Put the C# below in Program.cs. For example:
dotnet new console -n CacheKeyTrace --framework net10.0 cd CacheKeyTrace dotnet add package Microsoft.Extensions.Caching.Memory --version 10.0.0 dotnet run
Run the final command after replacing Program.cs. The fixed two-entry source and sequential calls intentionally omit expiration and memory limits; production needs bounded cardinality, expiration/invalidation, and concurrent-miss handling. GetOrCreate does not guarantee a single factory invocation when callers race.
// A01: prove key isolation. Same reads (A, B, A) against two key designs; then show why
// "join with a colon" is not an injective encoding and what to use instead.
using Microsoft.Extensions.Caching.Memory;
var prices = new Dictionary<(string Tenant, int Product), decimal> { [("A", 42)] = 80m, [("B", 42)] = 100m };
Run("product-only key", (tenant, product) => $"product:{product}", new[] { 80m, 80m, 80m }, 1);
Run("tenant + product key", (tenant, product) => new CatalogKey(tenant, product), new[] { 80m, 100m, 80m }, 2);
void Run(string name, Func<string, int, object> keyFor, decimal[] expected, int expectedReads)
{
using var cache = new MemoryCache(new MemoryCacheOptions());
int sourceReads = 0;
decimal Read(string tenant, int product) => // cache-aside: authorize first (not shown), then key, then cache
cache.GetOrCreate(keyFor(tenant, product), _ => { sourceReads++; return prices[(tenant, product)]; });
var tenants = new[] { "A", "B", "A" };
var actual = tenants.Select(t => Read(t, 42)).ToArray(); // materialize exactly three reads
if (!actual.SequenceEqual(expected) || sourceReads != expectedReads)
throw new InvalidOperationException($"Unexpected trace for {name}");
var trace = tenants.Select((t, i) => $"{t}={actual[i]}");
Console.WriteLine($"{name,-22} {string.Join(" ", trace)} source reads={sourceReads} B correct={actual[1] == prices[("B", 42)]}");
}
// Colon-joined strings: two different (tenant, product) pairs can produce one key.
Console.WriteLine();
string Joined(string tenant, string product) => $"{tenant}:{product}";
Console.WriteLine($"joined (\"A:B\",\"C\") -> {Joined("A:B", "C")} (\"A\",\"B:C\") -> {Joined("A", "B:C")} equal={Joined("A:B", "C") == Joined("A", "B:C")}");
// Length-prefixed segments are injective: the decoder knows where each segment ends.
string Prefixed(params string[] parts) => string.Concat(parts.Select(p => $"{p.Length}:{p}|"));
Console.WriteLine($"prefixed (\"A:B\",\"C\") -> {Prefixed("A:B", "C")} (\"A\",\"B:C\") -> {Prefixed("A", "B:C")} equal={Prefixed("A:B", "C") == Prefixed("A", "B:C")}");
// In-process, a record struct key is simplest: equality compares each field, no string encoding at all.
Console.WriteLine($"record key new(\"A:B\",\"C\") == new(\"A\",\"B:C\") -> {new TextKey("A:B", "C") == new TextKey("A", "B:C")}");
readonly record struct CatalogKey(string Tenant, int Product);
readonly record struct TextKey(string Tenant, string Product);Expected output
product-only key A=80 B=80 A=80 source reads=1 B correct=False
tenant + product key A=80 B=100 A=80 source reads=2 B correct=True
joined ("A:B","C") -> A:B:C ("A","B:C") -> A:B:C equal=True
prefixed ("A:B","C") -> 3:A:B|1:C| ("A","B:C") -> 1:A|3:B:C| equal=False
record key new("A:B","C") == new("A","B:C") -> FalseWhat the trace demonstrates
- Product-only key: one source read, and B receives 80. The "efficient" design served the wrong price, exactly as in the paper trace.
- Tenant + product key: two source reads, and every tenant gets its own price. The extra read is the cost of correctness.
- Colon join:
("A:B","C")and("A","B:C")produce the same string,A:B:C. Validating identifiers so they cannot contain the separator is one fix. - Length prefixes (
3:A:B|1:C|) make the encoding injective, so different tuples always give different strings. - In-process, a
record structkey needs no encoding at all.MemoryCacheaccepts a non-null object key. These record structs provide generated field-based equality; arbitrary reference-type keys do not automatically gain that behavior.
Try it
- Add a
Currencydimension to the price and make the tenant + product design fail. Then fix it by adding the field toCatalogKey. - Replace
Prefixedwithstring.Join(":", parts)and retry the same two tuples. Both now becomeA:B:C: removing the length framing and using an unchecked separator reintroduces the collision.
Why a key is not permission
Caching is about saving work after you already know what data is allowed to be served. Authorization is about deciding whether the caller may see the data at all. Those are different responsibilities.
A common interview trap is to blur them together: “If the item is missing from cache, deny access.” That is incorrect. A cache miss only means the cache does not currently hold a value. It says nothing about whether the user is allowed to load the value from the database or another source of truth.
For a product catalog, a public product page might be safe to cache broadly, while a tenant-specific price, contract discount, or hidden inventory flag must be isolated. If two tenants can see different effective data, then the cache key must encode the boundary that changes the answer.
A simple mental model helps:
request -> authorize -> build safe cache key -> read cache -> if miss, load source -> store -> return
The key idea is that protected data is never returned until authorization has succeeded. A resource may need to be loaded first to evaluate an ownership policy; an existing cache entry must not bypass that check. The cache is a performance layer, not proof of permission.
Authorization nuance: some permission checks need information about the document first. Consider a document-owner policy: the app needs the document owner before it can decide access. The authorization API accepts a resource and returns an authorization result; therefore this policy needs that resource first. Finish authorization before returning protected data. Microsoft: authorization API contract.
Build the cache-aside key
Cache-aside means the application controls the read path explicitly. On a read request, the application first checks the cache. If the value is present, it returns the cached value. If the value is absent, the application loads the canonical data from the database or service, then populates the cache, then returns the data.
For interviews, describe it this way: the application is responsible for keeping the cache warm on demand.
The tricky part is designing the key. A good key reflects every dimension that can change the result. In a multi-tenant product catalog, that might include:
- tenant ID, if product visibility or pricing differs by tenant
- user role or entitlements, if the response depends on permissions
- locale, if translated text is cached
- currency or region, if prices are rendered differently
- product ID or SKU, of course
A bad key omits one of those dimensions. Then one caller can receive another caller’s cached response. That is a data leak, even if the underlying database access is properly protected.
For example, suppose tenant A has a negotiated price of $80 and tenant B sees the standard price of $100. If the cache key is only product:42, the first tenant to request the product may populate the cache with the wrong price for the other tenant. The fix is not “add a permission check inside cache.” The fix is to make the key tenant-aware, such as tenant:A:product:42:price. If the user role also changes the answer, include it too.
Keep in mind the difference between public and private data. Public product descriptions might be safe to share across tenants, so a broader key could be acceptable. Private data should be scoped tightly. The point is not to make every key as specific as possible; it is to make each key as specific as the data variance requires.
In practice, use a stable key format and treat it as part of your API contract. That makes reasoning and invalidation easier. A common pattern is a namespaced prefix:
catalog:v1:tenant:{tenantId}:product:{productId}The v1 portion helps when schema or shaping changes. If you change the payload structure, a versioned namespace lets you avoid mixing old and new shapes.
For cache-aside, the application also owns the write path. The source of truth remains the database or service. After a product update, you might invalidate related keys or write through an updated value, depending on the design. But even then, the cache does not become the authority; it just mirrors data that the application has already decided is valid.
Another useful interview distinction is between in-process and distributed caching. An in-process cache is local to one application instance, so it is fast but not shared. A distributed cache is shared across instances, which helps scale out, but it is still just a cache unless you explicitly build stronger coordination on top. Do not assume a distributed cache gives you locking, consensus, or correctness guarantees for writes.
Failure modes
Here are the most common mistakes interviewers expect you to catch:
- Using a too-generic key. Example:
product:42. Risk: cross-tenant or cross-user leakage. - Checking permission only in the miss factory. Risk: a later cache hit skips that factory and could skip authorization. Correct approach: enforce access on both hits and misses before returning protected data; load a resource first when the policy requires it. A miss is not a deny decision.
- Caching user-specific or tenant-specific data under a shared key. Risk: one caller receives another caller’s response.
- Assuming the cache is the source of truth. Risk: stale or partial data becomes authoritative by accident.
- Ignoring schema evolution. Risk: old cache entries collide with new response shapes.
- Assuming distributed cache means distributed locking. Risk: concurrent writers or refreshers still race unless you add explicit coordination.
A good failure timeline to explain in an interview:
T1: tenant A requests product 42 -> cache miss -> load price 80 -> store under product:42 T2: tenant B requests product 42 -> cache hit -> receives price 80, but should see 100
That timeline shows why the cache key, not just the cached value, must respect tenant boundaries.
Interview drill
Use these questions to practice concise answers.
1) Why is cache-aside not an authorization mechanism?
- Correct answer: because authorization decides whether the caller may access data, while cache-aside only decides whether to load from cache or the source on a read.
- Worked explanation: a cache miss may simply mean the data is cold. The application must still enforce access rules before returning any data.
2) What should be part of a cache key in a multi-tenant product system?
- Correct answer: any dimension that changes the returned value, such as tenant ID, product ID, locale, currency, or entitlement tier.
- Worked explanation: if two callers can legitimately see different responses, they must not share a key.
3) When is it acceptable to share a cache entry across tenants?
- Correct answer: only when the cached response is truly identical and safe for all of them, such as a public product description with no tenant-specific shaping.
- Worked explanation: shared caching is fine for shared data, but private data must be isolated.
4) Does a distributed cache automatically prevent race conditions?
- Correct answer: no.
- Worked explanation: a distributed cache shares storage, not necessarily coordination semantics. It can still need explicit locking, versioning, or invalidation design.
Worked exercise: prove key isolation
Use this paper trace without any download. The source price for product 42 is 80 for tenant A and 100 for tenant B. Start with an empty cache, process A's read, then B's read, then A's read again. No writes, eviction or concurrent requests occur.
- Product-only key: A loads 80 into
product:42. B hits that same entry and incorrectly receives 80. A's final read returns 80. There is one source read, but B's result is wrong. - Structured tenant-and-product key: A loads 80 into the pair (A, 42). B misses the distinct pair (B, 42), loads 100, and stores it there. A's final read hits 80. There are two source reads and both tenant results are correct.
- Check your answer: explain why the lower source-read count in the broken design is not a performance success. It achieved fewer reads by serving the wrong response.
The structured pair above keeps its two components distinct. A distributed string-key design needs an unambiguous encoding too. For example, joining arbitrary segments with a colon makes (tenant="A:B", product="C") collide with (tenant="A", product="B:C"). Validate canonical identifiers and use an injective encoding or a structured serializer. Merely adding a tenant-shaped string is not a proof of isolation.
Derive tenant identity from trusted authenticated context, not an unchecked query parameter. Include every response-changing dimension, but do not place secrets or raw tokens in keys. A role label alone may fail to represent user-specific ownership or a changed entitlement. Recheck the actual access rule and either include the relevant variation or cache a less-shaped object.
Implementation exercise: reproduce both traces in a test and assert each returned price and source-read count. Keep the tenant-key result separate from authentication evidence: this paper trace does not configure or test an HTTP endpoint. Before applying it to an API, name the trusted tenant source, the authorization decision and each response-varying field.
Optional reading: Cache correctness companion note. The worked exercises above are self-contained.
TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·