Question presented to candidate: "Our product pages take about 20 milliseconds to load from the database, and the database is close to its limit at peak. Explain how adding a cache would help, how you would decide what to cache, and what can go wrong once the cache is in place."
What a strong answer should cover:
- The two wins: lower latency (memory is far faster than a database round trip) and offload (each hit is a query the database never sees), and why the hit ratio decides both: average latency = hit ratio x cache time + miss ratio x (cache + database time)
- Why caching works at all: skewed access (a small set of hot keys gets most reads), and why the tail latency (p99) only improves when the hit ratio passes 99%
- Read pattern cache-aside and write policies: invalidate on write, write-through, write-back, with the staleness and durability trade-off of each
- TTL and eviction (LRU/LFU), and what to cache: read-heavy, expensive to compute, tolerant of brief staleness; not per-request unique data
- Failure modes: stale data, cache stampede on a hot key expiring, cache penetration by lookups for keys that do not exist, and the database falling over when a cold cache restarts
- Layers: browser, CDN, application memory, a shared cache such as Redis or Memcached, and the database buffer pool
Clarifying questions expected:
- What is the read-to-write ratio, and how stale may a page be before it is a bug?
- How skewed is access (do a few products get most views)?
- What happens to the database if the cache is empty, for example after a restart?
Code / implementation expected: Optional β cache-aside pseudocode and the hit-ratio arithmetic are enough; the example simulates hit ratio by cache size and compares write policies.