Caching

Where to cache, cache-aside, read-through, write-through and write-behind patterns, eviction and TTLs, invalidation, stampedes, hot keys, and consistency pitfalls.

Intermediate 4 min readLesson 6 of 20 Interview Q&A

A cache stores the results of expensive work (database queries, computations, remote calls) in fast storage, so repeated requests are served quickly. Caching is the most effective performance tool in system design — and the source of some of its trickiest bugs.

"There are only two hard things in computer science: cache invalidation and naming things." — Phil Karlton

Where caches live

Browser / client cacheHTTP Cache-Control, service workersCDN edgestatic assets, cacheable API responsesReverse proxy / API gatewaynginx, VarnishApplication in-process cacheCaffeine, lru_cache — fastest, per instanceDistributed cacheRedis, Memcached — shared by all instancesDatabase buffer pool / query cachebuilt in

The closer to the user, the faster and cheaper, but the harder to invalidate.

Caching patterns

Cache-aside (lazy loading) — the most common

AppCacheDatabaseGET user:42missSELECT … WHERE id = 42rowSET user:42 (TTL 10 min)
User getUser(long id) {
    String key = "user:" + id;
    String cached = redis.get(key);
    if (cached != null) return json.read(cached, User.class);   // hit
    User u = db.findUser(id);                                     // miss
    if (u != null) redis.setex(key, 600, json.write(u));
    return u;
}

void updateUser(User u) {
    db.update(u);
    redis.del("user:" + u.id());       // invalidate (don't update) the cache
}

Other patterns

PatternWrites goProsCons
Cache-asideDB, then invalidate the cacheSimple; the cache holds only what's readFirst read is slow; possible stale windows
Read-through— (the cache loads from the DB itself on a miss)Loading logic centralised in the cache layerNeeds a cache that supports loaders
Write-throughCache and DB synchronouslyCache always freshSlower writes; caches data that's never read
Write-behind (write-back)Cache now, DB asynchronouslyVery fast writes, batchingData loss if the cache dies before flushing
Refresh-aheadRefresh popular keys before they expireAvoids miss latency for hot keysWasted refreshes

Eviction and expiry

Caches are smaller than the data, so something must go:

  • LRU — evict the least recently used. The usual default.
  • LFU — evict the least frequently used; better for stable popularity.
  • TTL — every entry expires after a time; bounds staleness even if invalidation fails.
  • Size limits and policies are configurable (maxmemory-policy allkeys-lru in Redis).

More on the algorithms: Page replacement.

Invalidation: keeping the cache honest

Strategies:

  • TTL only — accept up to TTL seconds of staleness. Simplest; often enough.
  • Explicit invalidation on write (delete the key).
  • Event-driven — publish change events (or tail the DB log) and invalidate everywhere, including in-process caches on every instance.
  • Versioned keys — user:42:v7; bump the version on change and old entries simply age out.

Failure modes

ProblemWhat happensFix
Cache stampede (thundering herd)A hot key expires and thousands of requests hit the DB at onceRequest coalescing / single-flight lock, early probabilistic refresh, stale-while-revalidate
Cache penetrationRequests for keys that don't exist always miss and hit the DB (possibly an attack)Cache negative results briefly; Bloom filter of valid keys
Cache avalancheMany keys expire at the same moment, or the cache cluster restartsAdd random jitter to TTLs; warm the cache; replicas
Hot keyOne key gets a huge share of traffic and overloads one cache nodeLocal in-process cache in front, replicate the key, split it
Cold startAfter a deploy or cache flush, everything missesWarm gradually; protect the DB with rate limits

What (not) to cache

  • ✓ Read-heavy data that changes rarely: profiles, product catalogues, configuration, rendered pages, expensive aggregations.
  • ✓ Results of slow external calls (with care about staleness).
  • ✗ Data that must always be exactly current: account balances during a transaction, inventory at checkout — read from the source of truth.
  • ✗ Highly personalised data with low reuse (a poor hit rate costs memory for nothing).

Measure the hit ratio: a cache with a 30% hit rate may cost more than it saves.

Key takeaways
  • Cache at every layer: client, CDN, proxy, in-process, distributed, database.
  • Cache-aside is the default: read from cache, on miss load from the DB and populate; on write, update the DB and delete the key.
  • Write-through keeps the cache fresh; write-behind is fast but risks loss.
  • Always use TTLs; prefer delete over update to avoid races.
  • Guard against stampedes, penetration, avalanches and hot keys.
Interview questions
QHow do you prevent a cache stampede on a very popular key?medium

Let only one request recompute the value while others wait or receive the stale value (single-flight / mutex in the cache, stale-while-revalidate), refresh the key shortly before expiry (probabilistic early expiration), and add TTL jitter so many keys don't expire together.