The purpose of caching, the in-process, distributed and HTTP/CDN layers, IMemoryCache basics (expiration, eviction, GetOrCreateAsync) and why SizeLimit matters.
We cache to avoid repeating expensive work: a database query, a remote call or a computation whose result is read far more often than it changes. There are three common layers:
IMemoryCache): lowest latency, but per instance, so pods can disagree, and lost on restart.IDistributedCache over Redis): shared by all instances, a network hop away.Cache-Control headers let browsers, proxies and edge nodes serve responses without hitting the app.IMemoryCache holds references to the cached objects (so mutating one changes it for every caller), with absolute or sliding expiration. By default it is unbounded, so I set SizeLimit, give every entry a Size, and watch the hit ratio. The trade-off is always freshness and memory versus latency and load.
"Caching means keeping a copy of a result closer to where it's needed so you don't pay to produce it again. It's worth it when data is read much more often than it changes and producing it is slow or expensive: a 40 ms database query, a call to a partner API with a rate limit, or a price calculation. What you give up is freshness, because the copy can be out of date, and memory.
In .NET I think in layers. The closest is in-process memory with
IMemoryCache: a lookup is a dictionary read, so it's nanoseconds, but each instance has its own copy, so three pods can hold three different versions and it all disappears on a restart. Next is a distributed cache such as Redis behindIDistributedCache: every instance sees the same value and it survives deployments, but each read is a network round trip of roughly half a millisecond to a couple of milliseconds plus serialisation. Furthest out is HTTP caching:Cache-Controlheaders let the browser or a CDN like Azure Front Door answer without the request reaching us at all.The mistake I see is treating
IMemoryCacheas free. It's unbounded by default, so a cache keyed by user or search term just grows until the process runs out of memory. I setSizeLimitand aSizeon every entry, always use an absolute expiration, and watch the hit ratio. A cache with a 10% hit ratio is just a memory leak with extra steps."
| Layer | Typical latency | Shared across instances | Survives restart | Good for |
|---|---|---|---|---|
IMemoryCache |
~50-100 ns | No | No | Reference data, config, hot lookups |
| Distributed (Redis) | ~0.5-2 ms in the same region | Yes | Yes | Session-like data, shared results, rate limits |
| HTTP/CDN | 0 ms to the app (served at the edge) | Yes (per edge node) | Yes | Public, cacheable GET responses, static assets |
HybridCache (.NET 9+ library) |
L1 hit = memory, miss = L2 | L2 yes | L2 yes | Most new code: both layers plus stampede protection |
| Option | What it does | Watch out for |
|---|---|---|
AbsoluteExpirationRelativeToNow |
Entry expires a fixed time after it was set | Pick from how stale the data may be |
SlidingExpiration |
Expires if not read for the period | Hot entries never refresh on their own; combine with absolute |
Size + SizeLimit |
Bounds the total "units" in the cache | Once SizeLimit is set, every entry must have a Size or Set throws |
Priority |
Order of eviction during compaction | NeverRemove entries are never evicted by compaction |
GetOrCreateAsync |
Read-through helper | Not stampede-safe: concurrent misses all run the factory |
A product-catalogue API read the same 2,000 category rows on every request at about 35 ms each. Caching them in IMemoryCache for 5 minutes with a SizeLimit brought the endpoint's p95 from 120 ms to 70 ms and cut database CPU by about 30%, with a measured hit ratio of 99.6%.
Checks that the candidate understands what caching buys and costs, knows the layers and their latency, and can use IMemoryCache safely.
Green flags
IMemoryCache is per instance and unbounded by defaultSizeLimit, Size, absolute versus sliding expirationRed flags
Caching exploits locality: a small set of keys gets most of the reads (often an 80/20 or steeper distribution). If a read costs C_source and a cache hit costs C_cache, the average cost is:
avg = hitRatio * C_cache + (1 - hitRatio) * (C_cache + C_source)
With a 95% hit ratio, a 1 ms Redis read and a 40 ms query, the average falls from 40 ms to about 3 ms. With a 30% hit ratio it barely moves, and you have added a moving part.
Browser cache -> CDN / Front Door -> Load balancer -> App instance
|-> IMemoryCache (L1, per pod)
|-> Redis (L2, shared)
\-> SQL Server (source of truth)
The closer the layer is to the user, the faster and cheaper the hit, and the harder it is to invalidate. Choosing a per-instance layer is an architecture decision: it is only safe for data where two pods briefly returning different values is acceptable.
MemoryCache (in Microsoft.Extensions.Caching.Memory) is built on a ConcurrentDictionary<object, CacheEntry>, so concurrent reads and writes from many request threads are thread-safe without a global lock. That safety covers the dictionary, not your objects: it stores references, so a cached object is shared by every caller, and if one caller mutates it everyone sees the change (and may see it half-done). Cache immutable records. Note also that GetOrCreate/GetOrCreateAsync are not atomic: two threads that miss at the same time both run the factory.
Expired entries are removed lazily on access and by a periodic scan (ExpirationScanFrequency, default 1 minute). There is no automatic eviction just because the process is short of memory: compaction happens when SizeLimit would be exceeded or when you call Compact(percentage).
SizeLimit has no unit; you decide what a unit means (one entry, approximate KB). When adding an entry would exceed the limit, the cache refuses the new entry and schedules a compaction that removes expired entries, then by priority, then least recently used. Register a dedicated, bounded instance for large or user-driven data instead of sharing the framework's default one.
CancellationTokenSource or config changes.Turn on TrackStatistics and publish hits, misses and entry count as metrics. If the hit ratio is low, shorten the key space or stop caching; if memory climbs, lower SizeLimit or expiry.
GetOrCreateAsync and measure with BenchmarkDotNet or a simple k6 run before and after.SizeLimit = 100 and add 200 entries with Size = 1; observe which survive after compaction.MemoryCacheStatistics (TrackStatistics = true, GetCurrentStatistics()) to log hit ratio and entry count.Cache-Control: public, max-age=60 to a GET endpoint and watch the browser serve it from disk cache.A bounded IMemoryCache for a reference-data lookup, with statistics so you can measure the hit ratio.
using Microsoft.Extensions.Caching.Memory;
namespace Catalogue.Caching;
public sealed record Category(int Id, string Name);
public interface ICategoryRepository
{
Task<IReadOnlyList<Category>> GetAllAsync(CancellationToken ct);
}
public sealed class CategoryCache(IMemoryCache cache, ICategoryRepository repository)
{
private const string Key = "categories:all:v1";
public async Task<IReadOnlyList<Category>> GetAllAsync(CancellationToken ct)
{
// GetOrCreateAsync is fine for cheap, low-contention data;
// concurrent misses may each call the repository (no stampede protection).
var categories = await cache.GetOrCreateAsync(Key, async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5); // staleness bound
entry.Size = 1; // required once SizeLimit is set
return await repository.GetAllAsync(ct);
});
return categories ?? [];
}
}
// Program.cs
builder.Services.AddMemoryCache(options =>
{
options.SizeLimit = 10_000; // units are yours: here, one per entry
options.TrackStatistics = true; // enables GetCurrentStatistics() for hit-ratio metrics
});
builder.Services.AddSingleton<CategoryCache>();
IMemoryCache unbounded with user-driven keys. Why it is wrong: Memory grows until the pod is OOM-killed. Instead: Set SizeLimit, give each entry a Size, and always set an absolute expiration.IMemoryCache. Why it is wrong: The cache holds a reference, so every caller sees the change. Instead: Cache immutable records or copies.IMemoryCache is consistent across instances. Why it is wrong: Each pod has its own copy; users can see different values depending on the pod. Instead: Use a distributed cache or HybridCache when consistency across instances matters.Even at junior level, the strong answer is about when to cache: the read/write ratio, how stale the data may be, and how you'll know it's working (hit ratio, source latency, memory). For new code in .NET 9 and 10, Microsoft recommends HybridCache (Microsoft.Extensions.Caching.Hybrid, GA March 2025): one GetOrCreateAsync call that uses an in-process cache first and a distributed cache (such as Redis) second, and makes concurrent misses for the same key share one call to the source. That removes the hand-written "check memory, check Redis, query, write both" code and its stampede bug, so I'd start there rather than combining IMemoryCache and IDistributedCache by hand.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
IMemoryCache |
Small, per-instance reference data | Memory per pod, inconsistency between pods | Data that must agree across instances |
Redis via IDistributedCache |
Shared data, survives deploys | Network hop, serialisation, another service to run | Tiny hot lookups called thousands of times per request |
| HybridCache | Most new application caching | A NuGet package and configuration | When you need raw Redis structures (sorted sets, streams) |
| HTTP/CDN | Public GET responses | Hard to invalidate; must vary correctly | Personalised or authenticated responses |
They solve different problems:
AddOutputCache, .NET 7+) stores the whole response on the server and replays it without running the endpoint. The app controls the policy: expiry, vary-by, tags for eviction, and stampede-preventing locking.Cache-Control rules, so clients can bypass it; its headers mainly matter for browser and CDN caching.For server-side caching of API responses I choose output caching. The trade-off is freshness: anything cached can be stale until it expires or is evicted.
LinkedList<T> is a doubly linked list of LinkedListNode<T> objects, each with Value, Next, Previous and List. Given a node, AddBefore, AddAfter, Remove(node), AddFirst and AddLast are O(1). But finding a node by value (Find, Remove(value), Contains) is O(n), there is no indexer, every element is a separate heap object (about 48 bytes for an int on 64-bit), and walking it misses the CPU cache. So List<T> is faster for almost everything. Use LinkedList<T> when you already hold node references and need O(1) reordering, the classic case being an LRU cache: Dictionary<TKey, LinkedListNode<Entry>> plus a LinkedList<Entry> ordered by recent use.
I choose by state and thread safety, then check dependencies:
So: DbContext is scoped (not thread-safe, one unit of work), or created per operation with IDbContextFactory<T> outside requests. HttpClient comes from IHttpClientFactory (pooled handlers, DNS refresh) or is one singleton with PooledConnectionLifetime. IMemoryCache is a singleton. The trade-off is sharing versus safety: wider lifetimes save allocations but demand thread safety and stricter dependencies.
Last updated 23 Nov 2026.