What it is
A cache is a small, fast store that keeps copies of answers you have already computed or fetched, so that the next request for the same thing can skip the expensive work. A request the cache can answer is a hit; one it cannot is a miss, which does the full work (a database query, a remote call, a rendering step) and usually stores the result for next time.
Caches appear at every layer: CPU caches, the database's own buffer pool, in-process maps, shared caches such as Redis or Memcached, CDNs, and the browser. This lesson is about the reason they all exist; the following lessons cover who fills and updates a shared application cache.
Why it exists
Two facts make caching worthwhile.
The cost gap. Reading a value from memory in the same process takes well under a microsecond; a round trip to a cache server in the same data centre typically takes a fraction of a millisecond; a database query that touches several tables or the disk can take milliseconds to tens of milliseconds, and it occupies a connection and CPU on a shared, hard-to-scale machine while it runs. The lesson uses 1 ms for a cache hit and 40 ms for the query (illustrative values).
Repetition. Real traffic asks the same questions again and again: the same product pages, the same user's profile, the same configuration. Without a cache, the database recomputes identical answers, and its fixed capacity is spent on repeats instead of work only it can do.
How it works
Read path. Look in the cache; on a hit return the value; on a miss do the work, return the value and keep a copy. Which component does the loading and how writes keep copies current is what distinguishes cache aside, read-through, write-through and write-behind.
Locality. A cache only holds a fraction of the data, so it works when a small set of items gets most of the requests. Popularity on the web is commonly heavy-tailed; a Zipf distribution, where the k-th most popular item is requested about 1/k as often as the top one, is a standard model. In the lesson, a least-recently-used (LRU) cache holding 10% of 10,000 products serves roughly two thirds of reads, and one holding 1% still serves more than a third.
Two formulas.
- Database load = request rate × (1 − hit ratio). At 260 requests/s, a 65% hit ratio leaves about 90 misses/s; at 40% it is about 155.
- Average latency ≈ hit ratio × hit time + (1 − hit ratio) × miss time. Because a miss costs tens of times more than a hit, the misses dominate the average and set the tail (P95, P99) even when they are a minority.
Diminishing returns. Under skewed access, the first small slice of hot keys produces most of the hits. Every further increase in size adds colder keys, so the hit ratio grows much more slowly than the cache.
No locality, no benefit. If every key is equally likely (a crawler, an export, a full scan), the best an LRU cache can do is hit about as often as the fraction of keys it holds: 1,000 of 10,000 gives about 10%.
When to use it
- Reads repeat: a hot set exists and is much smaller than the data.
- A miss is expensive compared to a hit (slow query, remote call, heavy computation).
- Readers can tolerate data that is slightly old for a bounded time, or you can keep the cache current on writes.
- The database or downstream service is near its read capacity, or latency targets cannot be met by it alone.
When not to
- Access is uniform or one-off (scans, exports, unique keys): the hit ratio will be close to the fraction of data cached.
- Each value must reflect every write immediately and you cannot keep the cache reliably in sync.
- The source is already fast and lightly loaded: the cache adds a hop, memory, a consistency problem and a component that can fail.
- Write-heavy data that is rarely read back.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Add a cache | Lower latency, less database load | Staleness, another component, cold-start risk |
| Bigger cache | Higher hit ratio (diminishing) | Memory; little gain once the hot set fits |
| Longer TTL | More hits | Older data when invalidation is missed |
| Cache closer to the user (process, CDN) | Fewer hops, less shared load | Many copies to keep current |
Alternatives
- Make the source faster: indexes, better queries, denormalised read models or materialised views.
- Read replicas: more read capacity without a second consistency mechanism (but with replication lag).
- Precompute: build results ahead of time (static pages, batch jobs) when the set of answers is known.
- HTTP caching and CDNs: cache whole responses at the edge, using standard
Cache-Controlsemantics.
Failure modes
- Cold cache: after a restart or deploy the hit ratio is near zero and the database briefly takes all reads.
- Cache outage: if the database is sized only for misses, it can saturate when the cache disappears.
- Scan pollution: a one-off scan evicts the hot set and lowers the hit ratio for everyone afterwards.
- Stale data: cached values outlive the truth until invalidated or expired.
- Hot keys: a single very popular key concentrates load on one cache node.
In production
Decide with numbers: request rate, read/write ratio, estimated hit ratio from real access logs, cost of a miss, database capacity. Size the database (or a load-shedding plan) for the hit ratio dropping, not just for steady state. Monitor hit ratio, evictions, cache latency and database load together; a falling hit ratio predicts database trouble. Keep scans and exports away from the shared cache.
Common misconceptions
- "A bigger cache always helps proportionally." Under skewed access, returns diminish quickly.
- "A cache makes the database unimportant." Every miss, expiry and outage still lands on it.
- "Hit ratio is a vanity metric." Database load is proportional to the miss ratio: 95% → 90% hits doubles it.
- "Caching helps any read workload." Without repetition it is pure overhead.
Interview angle
Justify a cache with numbers: "reads are 20× writes, the top 1% of items take most reads, a miss is a 30 ms query, so a cache with a 90% hit ratio cuts database reads tenfold." Then say where it sits, what it costs when the hit ratio drops, how stale data is handled, and which loading pattern you would use (cache aside, read-through) and why.
Model assumptions
The simulation is a simplified model, not a benchmark. Users read 10,000 products with Zipf(1) popularity (uniform in the "No locality" step), arriving as a Poisson process. Only reads are modelled. The Shop API has 32 workers and holds one while it waits for the cache and the database. The database has 8 connections and a 40 ms mean query (lognormal, cv 0.4), about 200 reads per second at most; requests waiting longer than 300 ms for a connection fail, and the API rejects requests when its own queue is full. The cache is an LRU answering in about 1 ms and is filled after each database read (the cache-aside pattern). The hit-ratio tile counts every lookup since the simulation started, including warm-up. Numbers show behaviour and orders of magnitude only.