Chapter 3
Caching That Doesn't Lie
Caching is the easiest performance fix to add and the hardest one to get right. In my archive, 31 engagements have hand-written caching classes, 4,484 of them. CacheManager alone appears 159 times. Most of them are a static Hashtable or a thin layer over HttpRuntime.Cache, written in an afternoon when a page got slow, and then trusted for a decade.
The trouble with those caches is not that they are slow. It is that they lie. A price list cached with no expiration shows yesterday's prices until someone recycles the app pool. A cache keyed by a string that two developers spelled differently holds two copies of the same data, one of them stale. A cache that only exists in the memory of one web server shows different answers depending on which server the load balancer picks. And when a popular entry expires at 9:00 on Monday morning, two hundred requests all miss at once and run the same expensive query against a database that was already busy.
This chapter builds caching that tells the truth, or at least tells you how old its answer is. It starts with cache-aside on IMemoryCache, adds expiration and size limits, covers invalidation, prevents stampedes, moves to a distributed cache backed by Redis, and finishes with a small typed wrapper that keeps keys and lifetimes in one place.
The listings use these NuGet packages: Microsoft.Extensions.Caching.Memory for IMemoryCache, Microsoft.Extensions.Caching.StackExchangeRedis for Redis, and Microsoft.Extensions.Caching.Hybrid for HybridCache in one variation. In an ASP.NET Core application the first is already referenced by the shared framework.
Recipes
- 3.1Cache-Aside with GetOrCreateAsyncA list of countries, tax rates or product categories is read on every request and changes a few times a year. Reading it from the database each time…
- 3.2Expiration and Size LimitsAn in-memory cache with no limits is a memory leak with a nicer name. A cache of product details keyed by product ID grows with every product anyone…
- 3.3InvalidationA user updates a price list and immediately reloads the page. The cache still holds the old list for another 25 minutes, the user files a bug, and…
- 3.4Preventing Cache StampedesA dashboard summary takes eight seconds to compute and is cached for five minutes. Every five minutes the entry expires, and every request that…
- 3.5Distributed Caching with IDistributedCache and RedisThe application now runs on four servers behind a load balancer. Each has its own in-memory cache, so each loads the same data, invalidation on one…
- 3.6A Typed Cache WrapperAfter a few years, cache keys are string literals scattered through the code, each call site picks its own lifetime, and the value type is whatever…
Chapter checklist
- Find every static
Hashtable,DictionaryandHttpRuntime.Cacheused as a cache, and give each entry an absolute expiration. - Use
IMemoryCache.GetOrCreateAsyncfor cache-aside, and cache only immutable values. - Put size-limited caches in their own
MemoryCachewithSizeLimit, and setSizeon every entry. - Invalidate after the database commit, by key or with a shared change token, and keep an absolute expiration as a safety net.
- Protect expensive entries from stampedes with a single-flight load, or with
HybridCacheon .NET 9 and later. - On more than one server, move shared data to
IDistributedCachewith Redis, serialize withSystem.Text.Json, and treat cache failures as misses. - Define every key once, with its type and lifetime, in a
CacheKeysclass, and expose hit and miss statistics somewhere you can see them.