Caching

The speed layer in front of the database: cache-aside vs write-through, eviction, invalidation, thundering herd.

Intermediate8 min read
Language
Theme
AppCache (Redis)RAM, TTL setDatabasedisk1. GET keyhit: return2. miss3. fill cacheStrategiescache-aside / write-through / write-backOn writes: delete or update the cache, and always keep a TTL
Key idea at a glance
INTERACTIVE

Playground: cache hits, misses and LRU eviction

Capacity is 4. Request keys and watch hits (green), misses (yellow) and which key gets evicted. Watch the hit rate climb when you repeat keys.

Database
slow: ~5-50 ms

Why caching is the highest-ROI technique in this course

The physics from lesson 3: RAM ~100 ns, SSD ~100 us, network round trip ~0.5-150 ms. A cache keeps the result of expensive work in RAM, close to the app. A 90% cache hit rate on a read-heavy system removes 90% of database load: often the difference between one DB server and ten. Caches exist at every layer: CPU cache, browser cache, CDN, application cache (Redis/Memcached), database buffer pool. The principle is identical everywhere; the eviction and invalidation details differ.

Cache-aside (the default pattern), step by step

  1. Read: ask the cache. Hit: return, done (~1 ms total).
  2. Miss: read the DB (~5 ms), write the value into the cache with a TTL, return.
  3. Write: update the DB, then delete the cache key (next read repopulates it).

Why delete instead of update on writes? Updating risks race conditions (two concurrent writes leave the cache with the older value); deleting is idempotent and simple. The cost: the first read after each write is a miss.

Write-through and write-back

  • Write-through: writes go to cache and DB together, synchronously. Cache is always fresh; writes are slower (two writes per operation). Good for read-heavy spots where stale data is dangerous.
  • Write-back: write only to the cache, flush to the DB later in batches. Very fast writes, but a cache crash loses unflushed data. Use for counters and metrics where small loss is acceptable, never for money.

Eviction: what leaves when the cache is full

  • LRU (Least Recently Used): evict what was read longest ago. The default; matches most workloads' recency bias.
  • LFU (Least Frequently Used): evict what is used least. Better when old items can stay hot (a classic video from 2015).
  • TTL: every entry expires after N seconds regardless. A staleness safety net; always set one even with LRU.

The failure modes that separate juniors from seniors

  • Thundering herd / cache stampede: a hot key expires; 10,000 concurrent requests all miss and hammer the DB. Fixes: request coalescing (first requester fetches, others wait for that same result), stale-while-revalidate (serve the old value while refreshing in background), TTL jitter (random +/- so keys do not expire together).
  • Cache penetration: queries for keys that do not exist (e.g. user id -1) always miss and hit the DB; an attacker can exploit this. Fix: cache negative results briefly, or a Bloom filter in front.
  • Cache avalanche: many keys set at the same time (deploy, warmup) expire at the same time. Fix: TTL jitter.
  • Hot key: one celebrity key does 30% of traffic; one Redis shard melts. Fix: replicate the hot key across slots, or keep a local in-process cache for it.

Worked example: session store at 50k reads/sec

Sessions: 1 KB each, 10M active users = 10 GB: fits one Redis node, but run a replica for failover. Cache-aside with 24h TTL (sliding), LRU eviction, delete-on-write when the user logs out or changes roles. Session reads hit ~99% because every authenticated request reads the session.

Common interview traps

  • "Add Redis" with no invalidation strategy.
  • No answer for "what happens when a very hot key expires?"
  • Caching per-user data on a shared key (user A sees user B's page).
  • Caching everything: rapidly changing data cached long is worse than no cache.

Interview Q&A

Q: How do you keep cache and DB consistent?
A: You do not, perfectly; you bound the staleness. Cache-aside with delete-on-write plus a TTL gives a small stale window. Stricter needs use write-through, or a change-data-capture stream (Debezium) that invalidates cache keys from the DB log.

Q: Redis vs Memcached?
A: Redis: richer data structures (lists, sorted sets for feeds and leaderboards), persistence options, replication, Lua scripts, pub-sub. Memcached: simpler, multi-threaded, pure LRU cache. Modern default is Redis.

Key takeaways

Interview pointer

The moment you say cache, the interviewer asks: 'how will you invalidate it?' and 'what about a cache miss storm?' Have both ready: delete-on-write plus TTL, and request coalescing for stampedes.