Caching
The caching layers, the four write strategies, eviction policies, and the three failure modes — stampede, penetration, avalanche — that every serious interview eventually reaches.
#Why caching dominates
Caching is the highest-leverage performance technique available, because of the numbers in the latency ladder: memory is ~1,000× faster than SSD, and a local memory read is ~5,000× faster than a cross-region round trip.
But the real win is usually load reduction, not latency. Your hit rate is the share of lookups the cache can answer by itself; a 95% hit rate means your database sees one twentieth of the traffic. That is often the difference between one database and a whole cluster. Whenever you propose a cache, quantify it: at a 95% hit rate the database handles 5,000 requests a second instead of 100,000, which keeps you on a single machine.
Caching works because of two things that are reliably true of real traffic: temporal locality (something just read is likely to be read again shortly) and skew (a small number of items get most of the requests — the classic 80/20, and on social platforms far more lopsided than that).
#The layers
Requests pass through many caches. Know all of them — most discussions name only one.
- Browser / client cache — free, zero latency, but you can't invalidate it. Controlled by
Cache-ControlandETag. - CDN — geographically distributed edge. Best for static assets and increasingly for cacheable API responses.
- In-process (local) cache — a hash map in the application's memory. Nanosecond access, no network. Costs: each server has its own copy (memory × N), and consistency across the fleet is hard. Best for small, hot, slow-changing data (feature flags, config, hot metadata).
- Distributed cache — Redis/Memcached cluster. Shared by all app servers, so one copy and one invalidation. Costs ~0.5 ms network round trip.
- Database cache — buffer pool / page cache: the database keeps recently used disk pages in memory. Free and automatic. This is why "does the working set fit in RAM?" is the most important database performance question — the working set is the data your queries actually touch regularly. If it fits in memory, most reads never touch disk; if it doesn't, the database keeps fetching from disk and slows down sharply.
Many high-traffic systems use a two-tier cache: a small local cache in front of the distributed cache to absorb the hottest keys and cut network calls. Mentioning this is a good depth signal — with a caveat. When the data changes, you can delete it from Redis in one place, but every server's local copy stays stale. So local tiers need short TTLs (time to live: an expiry time stamped on each cache entry, after which it is thrown away), which caps how long any server can serve an old value.
#Write strategies
The four patterns. Know the tradeoffs precisely; this is a favorite follow-up.
Cache-aside (lazy loading) — the default, and what to name first. "Aside" because the cache sits beside the database rather than in front of it: your code checks the cache, and on a miss goes to the database itself and puts the answer in.
READ: check cache → hit? return
→ miss? read DB, write cache, return
WRITE: write DB → invalidate (delete) cache keyOnly requested data is cached; a cache failure degrades to slow rather than broken. The application owns the logic. Downside: every miss costs an extra round trip, and there's a subtle race (below).
Read-through — same read behavior, but the cache itself fetches on miss. Cleaner application code, requires cache support or a wrapper library.
Write-through — write to cache and DB synchronously.
Cache is never stale, but every write pays both latencies, and you cache data nobody may ever read.
Write-behind (write-back) — write to cache, acknowledge, flush to DB asynchronously.
Very fast writes, and it coalesces repeated updates to the same key: if a view counter is incremented 1,000 times between flushes, the database receives one write of the final value instead of 1,000 writes (excellent for counters). You can lose data if the cache dies before flushing. Acceptable for view counts; not for orders.
#The cache-aside race
Worth knowing because good interviewers ask:
T1: read, cache MISS, reads DB → gets v1
T2: writes v2 to DB, deletes cache key (no-op, nothing there)
T1: writes v1 into cache ← cache now permanently staleFixes:
- Short TTLs, so the stale entry expires on its own and the damage is time-bounded. Usually sufficient and cheap.
- Delayed double delete — the writer deletes the key, writes the DB, sleeps briefly, then deletes again. The second delete removes any old value that a slow reader like T1 slipped in during the gap.
- Versioned writes — store a version number with each value, and refuse to overwrite a cached value with an older version. In practice, TTL as a safety net is the pragmatic answer — and saying "every cache entry gets a TTL, because invalidation logic will eventually have a bug" is the kind of realism that scores.
#Eviction policies
When the cache is full, something must go.
- LRU — evict least recently used. The sensible default; matches temporal locality. Weakness: a large scan (a batch job reading everything once) flushes your hot set — cache pollution.
- LFU — evict least frequently used. Resistant to scan pollution, since items read once by a scan never build up a high count. But it is slow to adapt when popularity shifts: yesterday's viral post keeps its huge count and refuses to leave. So it is usually implemented with decay (as Redis's LFU does) — counts shrink over time, letting old favourites age out.
- FIFO — evict oldest inserted. Rarely what you want.
- TTL-based — evict on expiry regardless of use. Not really an eviction policy but a freshness policy; combine with LRU.
- Segmented LRU / ARC / W-TinyLFU — adaptive hybrids that resist pollution while adapting to shifts. W-TinyLFU (used by Caffeine) is what modern in-process caches use.
Choosing a TTL is a consistency decision in disguise: TTL is your bound on staleness. Short TTL = fresher data, lower hit rate, more DB load. Long TTL = the opposite. State the tradeoff explicitly when you pick one.
#The three failure modes
This is the section that decides whether the design survives contact with reality. Interviewers love these because each has multiple valid answers.
#1. Cache stampede (thundering herd)
A popular key expires. A thousand concurrent requests all miss simultaneously and all hit the database for the same value. The database was sized to handle only the small share of traffic that misses the cache, not a thousand identical queries at once — so it overloads and starts failing.
Fixes:
- Request coalescing / single-flight — let only the first request per key go to the database; everyone else waits for that one answer. Within a single server this is straightforward; across a fleet you need a short-lived lock in the cache itself (
SET key NX EX 5— set it only if absent, expiring in 5 seconds), where the winner refills and the losers either serve slightly stale data or wait and retry. - Probabilistic early refresh — as a key nears expiry, each request has a small, rising chance of proactively refreshing it. Refreshes spread out naturally; no lock needed. Elegant and cheap.
- TTL jitter — never use a fixed TTL.
ttl = base + random(0, base × 0.1)prevents keys written together from expiring together. - Serve stale while revalidating — return the expired value immediately and refresh in the background. Best user experience; requires tolerating brief staleness.
#2. Cache penetration
Requests for keys that don't exist anywhere. Every one misses the cache, hits the database, finds nothing, caches nothing — so the cache provides zero protection. Trivially weaponized: an attacker requests random nonexistent user IDs.
Fixes:
- Cache the negative result — store "this doesn't exist" for a short while (a TTL of 30–60 s). Simple and effective.
- Bloom filter of all existing keys in front of the cache. A Bloom filter is a compact structure that answers "have I seen this key?". When it says "no", it is always right, so you can reject the request without touching the database at all. (When it says "yes", it is occasionally wrong, which just costs one wasted lookup.) Costs ~1.2 GB per billion keys at 1% false-positive rate.
- Input validation — reject malformed IDs before any lookup.
#3. Cache avalanche
A large fraction of the cache expires or disappears at once — a mass TTL expiry, or a cache node/cluster failure. The full, uncached load hits the database instantly.
Fixes:
- TTL jitter again (handles the mass-expiry variant).
- Replication so a single node loss doesn't drop its keys.
- Warm-up on restart — never bring an empty cache into full traffic. Preload hot keys, or ramp traffic gradually.
- Circuit breaker in front of the DB — a guard that notices the database is overloaded (errors or timeouts rising) and starts rejecting some requests immediately instead of passing them through. When the cache is gone, shed load this way rather than let the database die. Degraded service beats no service.
A cold cache that can't refill because the database it protects is drowning is one of the classic metastable failures — an outage that keeps going after its trigger is gone.
#What not to cache
Volunteering this is a good signal, because it shows you see the cost side:
- Data that changes on nearly every read — you pay the cache write and get no hits.
- Data with no reuse — per-user, one-time queries. You're just adding a round trip and memory pressure.
- Anything where staleness is unacceptable and TTLs can't be short enough — see consistency models.
- Very large objects that evict many small hot ones. Watch the ratio of size to hit rate.
#Metrics that matter
- Hit rate. The headline number. Below ~80% for a read-heavy workload, ask whether the cache is earning its complexity.
- Latency p99, cached vs uncached, so you know what a miss actually costs.
- Eviction rate. High evictions mean the cache is undersized — you're paying for a cache that keeps throwing away things you're about to need.
- Key distribution / hot keys. A single key taking 30% of traffic can saturate one Redis node regardless of cluster size. Fix by storing copies of that key under several names (
trending:1,trending:2, …trending:8) so they hash to different nodes, and having each reader pick one at random. Or promote it to the in-process local cache on every app server.
#Check yourself
Why is load reduction usually the bigger win of a cache than latency?Show answer
Describe cache-aside reads and writes.Show answer
Why delete the cache key on a write rather than writing the new value into it?Show answer
Write-through versus write-behind: what does each trade?Show answer
A popular key expires and a thousand requests miss at once. Name three fixes.Show answer
What is cache penetration, and how do you stop it?Show answer
Why is bringing a restarted, empty cache straight into full traffic dangerous?Show answer
One key gets 30% of all traffic. Why doesn't adding cache nodes help?Show answer
#What to carry forward
- Caching works because traffic is skewed and repeats; its main win is cutting database load.
- Default to cache-aside and delete keys on write — and give every entry a TTL as a safety net.
- TTL is a staleness bound in disguise: pick it as a consistency decision.
- Plan for stampedes, penetration and avalanches: single-flight, negative caching, jitter, warm-up.
- Watch hit rate, eviction rate and hot keys; don't cache what isn't reused.