Volume 3 · Chapter 9 — Entity Framework Core and Data Access Engineering

Caching Strategies

Goutham Mayaluri 7 min read .NETC#Caching

9.1 Introduction

Caching improves performance by turning repeated expensive work - database queries, external calls, complex computations - into cheap lookups. It is one of the highest-leverage scaling tools, but it trades speed against freshness, so enterprise caching is a deliberate balance between performance and consistency. The famously hard part is invalidation: keeping cached data fresh enough that stale reads don’t cause problems.

9.2 In-Memory vs Distributed Cache

In-memory caching (IMemoryCache) stores data in the application process - extremely fast, no network hop, but local to one instance and lost on restart. Distributed caching (Redis viaIDistributedCache) is shared across all instances - essential when you run multiple instances behind a load balancer and need a consistent, shared cache (and for session state).

flowchart TB
  A["Instance A"] --> Redis["Redis (distributed cache)"]
  B["Instance B"] --> Redis
  C["Instance N"] --> Redis
  A -. "local, per-instance" .-> Mem["IMemoryCache (in A only)"]

9.3 The Cache-Aside Pattern

Cache-aside is the most common strategy: check the cache; on a hit, return it; on a miss, load from the database, store it in the cache with an expiration, and return it. It is simple and robust, and the hard parts are invalidation and stampede protection.


public async Task<Rate> GetRateAsync(string pair, CancellationToken ct)
{
    return (await _cache.GetOrCreateAsync(pair, async entry =>
    {
        entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);   // TTL
        return await _db.Rates.AsNoTracking().FirstAsync(r => r.Pair == pair, ct);  // on miss
    }))!;
}

9.4 Expiration and Invalidation

Expiration strategies include absolute (expire at a fixed time), sliding (expire after inactivity), and explicit invalidation (remove on write). Invalidation is hard because cached data becomes stale the moment the source changes; approaches are short TTLs (bounded staleness), explicit invalidation on writes, event- driven invalidation, and versioned cache keys. Stampede protection (locking so one caller recomputes on a miss, jittered expiration) prevents many simultaneous misses from overwhelming the backend.

9.5 What to Cache - and What Not To

Good to cache Avoid caching
Frequently read, slowly changing data Frequently changing data
Expensive computations Highly transactional updates
Reference/lookup data Critical real-time values (a live balance)
Senior Interview Question

Why is cache invalidation considered so difficult?

Cache invalidation is hard because the whole point of a cache is to hold a copy of data that lives elsewhere, and the moment the source data changes, the cached copy is stale - yet the application keeps happily serving that stale copy until something invalidates it. So you’re constantly fighting the tension between performance (serve from cache without checking the source) and correctness (don’t serve outdated data), and there’s no free way to know the source changed without either checking it (which defeats caching) or being told. The difficulty compounds in several ways. Timing: you must decide how stale is acceptable and set expirations accordingly, but too-short TTLs reduce the cache’s benefit while too-long ones risk serving wrong data. Explicit invalidation: invalidating on writes requires every code path that changes the data to remember to evict the right cache entries, which is easy to miss and creates coupling between writers and the cache. Distributed systems: with multiple instances and a distributed cache, you must invalidate consistently across all of them, and there are races - a write and a concurrent cache-refresh can interleave so the cache ends up holding the pre-write value even after the write. Related-data invalidation: a single change may require invalidating many derived or aggregated cache entries, and tracking those dependencies is complex. And cache stampedes: when a hot entry expires, many requests miss simultaneously and all try to reload, overwhelming the backend, so invalidation interacts with load. The mitigations - short/jittered TTLs for bounded staleness, explicit event-driven invalidation on writes, versioned cache keys, locking to prevent stampedes, and accepting eventual consistency where the business tolerates it - all help but each adds complexity and none makes it truly easy, which is why it’s proverbially one of the two hard problems in computing. The senior insight is that invalidation is fundamentally about keeping two copies of data consistent without constant checking, in a distributed, concurrent world - so I design caching deliberately: cache data that tolerates some staleness, choose an invalidation strategy matched to the freshness the business needs, protect against stampedes, and make cache correctness observable - rather than caching naively and being surprised by stale-data bugs.

Principal Engineer Question

How do you design a caching strategy for an enterprise application, and when should you not cache?

I design caching deliberately, starting from what problem it solves and what staleness the business can tolerate, because caching trades freshness and added complexity for performance and should only be applied where that trade is favorable. First I identify the expensive, repeated operations worth caching - frequent reads of the same data, costly computations, slow external calls - and confirm caching is the right fix rather than a missing index or an N+1 that a query fix would solve more cheaply (a common mistake is caching to paper over inefficient queries). Then I choose the cache type by topology: in-memory (IMemoryCache) for hot, per-instance data where a little duplication across instances is fine and speed is paramount, or a distributed cache (Redis) when the data must be shared and consistent across multiple instances behind a load balancer, or for session state. I define the expiration and invalidation strategy matched to the required freshness: short/jittered TTLs for bounded staleness on data that changes occasionally, explicit or event- driven invalidation on writes for data that must reflect changes promptly, and versioned keys where useful - and I plan stampede protection (single-flight/locking on miss, jittered expiration) so a hot key expiring doesn’t overwhelm the backend. I use the cache-aside pattern by default. Crucially, I decide whatnotto cache: I avoid caching frequently-changing data (the cache would be stale most of the time and constantly invalidated, giving little benefit and much risk), highly transactional data, and especially critical real-time values where a stale read causes real harm - a live account balance used to authorize a withdrawal, inventory at the point of sale, anything where correctness of the latest value is non-negotiable - because there the staleness risk outweighs any performance gain. Reference and lookup data, expensive aggregations, and slowly-changing read-heavy data are the sweet spot. I make cache behavior observable - monitoring hit rate, backend load, and staleness - so I can tune it and detect problems, and I keep the invalidation logic as simple and centralized as possible. So the strategy is: cache read-heavy, staleness-tolerant, expensive-to-produce data with the right cache type, a matched expiration/invalidation approach, stampede protection, and monitoring; and deliberately don’t cache rapidly-changing or correctness-critical real-time data - which delivers the performance benefit where it’s safe while avoiding the stale-data bugs and complexity that naive, blanket caching causes.

9.6 Production Scenario

A banking application serves millions of requests for slowly-changing customer profile and reference data, overloading the database at peak. The team introduces a distributed (Redis) cache-aside layer for that read-heavy reference data with short jittered TTLs and event-driven invalidation on updates, plus stampede protection - while deliberately not caching live balances (a correctness-critical real-time value). Database load drops sharply at peak, and cache hit rate is monitored to tune effectiveness.

Chapter Revision Notes

  • Caching turns repeated expensive work into cheap lookups - balance performance against freshness.
  • In-memory cache is per-instance and fast; distributed (Redis) is shared across instances.
  • Cache-aside is the default pattern; the hard parts are invalidation and stampede protection.
  • Cache read-heavy, slowly-changing data; don’t cache rapidly-changing or correctness-critical values.
  • Match invalidation (TTL, event-driven, versioned keys) to the freshness the business needs; monitor hit rate.