Cache-aside and invalidation
Cache-aside and invalidation
Cache-aside reads from a cache first, falls back to the authoritative store on a miss, and populates the cache for subsequent reads. Invalidation removes cached data when the underlying state changes.
Caching exchanges freshness, storage and complexity for potentially lower read latency. A cache miss is normal, not proof that the data does not exist. IMemoryCache stores objects in one process; it cannot synchronize replicas by itself. IDistributedCache provides a byte-oriented abstraction for a shared backend; the in-memory implementation is only a local test substitute. HybridCache, available from .NET 9, combines primary local caching, optional secondary distributed caching, serialization and coalescing of concurrent fills; verify version and cross-replica behavior rather than assuming a distributed lock. Output caching stores generated responses, while HTTP caching follows protocol rules for clients and intermediaries. For mutable data, commit the authoritative write before invalidation; a read racing with that write can still repopulate stale content. Use explicit versioning, reliable invalidation or a freshness requirement appropriate to the domain; Expiry limits eligibility to serve an entry according to the provider policy, not correctness or the exact instant of memory reclamation. Sliding expiration alone can keep frequently accessed stale entries eligible indefinitely; use an absolute limit where needed. A known revision floor can reject stale fills, but must itself be maintained consistently across the required scope. Authorize before cache access, and include trusted tenant and other relevant visibility dimensions in keys. Do not cache passwords, bearer tokens or unauthorized results under a shared key. Bound memory, payload sizes and cardinality. Monitor hit ratio, fill duration, stale reads and backend load. A cache outage needs a bounded fallback, not an unlimited surge of database traffic.
Baseline: .NET 10 / C# 14. All C# results below are reasoned, not executed. Models and isolated local integration fixtures are explicitly distinguished.
Fill once and invalidate after a write
Use a real IMemoryCache and a tiny authoritative quantity variable. No real-time expiration is needed for this deterministic sequence.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run. Requires the ASP.NET Core 10 shared framework.
using System;using Microsoft.Extensions.Caching.Memory;using var cache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 8 });int stock = 4, loads = 0;const string key = "tenant-a:book:1:v1";int GetStock() { if (cache.TryGetValue<int>(key, out int hit)) return hit; loads++; cache.Set(key, stock, new MemoryCacheEntryOptions().SetSize(1).SetAbsoluteExpiration(TimeSpan.FromMinutes(2))); return stock;}Console.WriteLine($"first={GetStock()}; loads={loads}");Console.WriteLine($"second={GetStock()}; loads={loads}");stock = 7; // Represents a successful authoritative commit.cache.Remove(key);Console.WriteLine($"after write={GetStock()}; loads={loads}");Expected result (not executed):
first=4; loads=1second=4; loads=1after write=7; loads=2One fill is reused until invalidation. The sequential example does not solve simultaneous fills or stale repopulation. Size is an application-defined unit.
Keep tenant cache entries separate
The tenant IDs are assumed to come from an already authorized context, not raw request parameters. Use distinct structured keys.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run. Requires the ASP.NET Core 10 shared framework.
using System;using Microsoft.Extensions.Caching.Memory;using var cache = new MemoryCache(new MemoryCacheOptions());cache.Set((Tenant:"north", Book:1), 4);cache.Set((Tenant:"south", Book:1), 9);Console.WriteLine(cache.Get<int>((Tenant:"north", Book:1)));cache.Remove((Tenant:"north", Book:1));Console.WriteLine(cache.TryGetValue((Tenant:"north", Book:1), out _));Console.WriteLine(cache.Get<int>((Tenant:"south", Book:1)));Expected result (not executed):
4False9Composite keys avoid this specific collision. Tenant keying is not authorization: enforce resource permissions first, and include user/role dimensions if the result varies by visibility.
Reject an old cache fill with a version fence
A single-threaded interleaving model shows why invalidation alone is not sufficient. The comparison and update would need atomic coordination in real concurrent code.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run.
using System;int sourceVersion = 1, sourceStock = 4;(int Version,int Stock)? cached = null;var pendingRead = (Version:sourceVersion, Stock:sourceStock);sourceStock = 7; sourceVersion++; cached = null;if (pendingRead.Version == sourceVersion) cached = pendingRead;Console.WriteLine(cached is null ? "stale fill rejected" : "stale fill accepted");cached = (sourceVersion, sourceStock);Console.WriteLine($"version={cached.Value.Version}; stock={cached.Value.Stock}");Expected result (not executed):
stale fill rejectedversion=2; stock=7A production implementation requires a trustworthy version and an atomic fence or a versioned key strategy. A read may still see old data if its own snapshot predates the write.
Apply the concept
A book quantity changes from 4 to 7 while two reads are in flight. Design cache keys and a freshness policy for two authorized warehouses.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cache-aside and invalidation — knowledge check
Apply the lesson concepts to the following scenarios.
Where is the source of truth in cache-aside?
What can happen after commit then invalidation?
What does an IMemoryCache instance share across replicas?
Which key is safer for tenant-specific stock?
What is HybridCache coalescing useful for?