Course contents

06. Caching Lesson 1 of 8

Why Caching Exists

See why repeated reads waste database capacity, how locality lets a small cache serve most reads, and how hit ratio drives latency and database load.

12 minIntermediate7 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A cache keeps recent answers in fast memory so repeated reads skip the expensive work.
  • It works because access is skewed: a small hot set gets most of the reads (locality).
  • Database load = requests × miss ratio; average latency is a hit-ratio-weighted mix of hit and miss time.
  • Without locality, hit ratio ≈ cache size / data size, and the cache is overhead.
  • Once a cache carries load it is capacity: the database is sized for the misses.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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-Control semantics.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. Every page view is a database query

    Users open product pages at 120 requests per second. Each page needs a query that joins product, price and stock tables: about 40 ms of database work.

    The database has 8 connections, so it can do at most about 200 of these per second. At 120 it is around 60% busy, and every single request reaches it, even the hundredth view of the same product this minute.

    Scene: Users call the Shop API at 120 requests per second; every request runs a 40 ms query on the database, which is around 60% busy. Nothing fails.

    Key idea: Without a cache, the database repeats the full work for every read, however often the answer is the same.

  2. 2. Traffic outgrows the database

    A sale doubles traffic to 260 requests per second, more than the 200 reads per second the database can do. Queries queue for connections, the API’s workers sit waiting on them, its own queue fills and new requests are rejected. Latency for the rest climbs past half a second.

    You could buy a bigger database. But look at what it is doing: answering the same questions about the same popular products over and over.

    Scene: At 260 requests per second the database is saturated: queries wait for connections, the API backs up and rejects some requests, and latency rises above half a second.

    Key idea: A database has a fixed read capacity. Repeated identical reads waste it.

  3. 3. Keep recent answers in memory

    We add an in-memory cache that holds the last 1,000 products read (10% of the catalogue). The API checks it first; only a miss goes to the database, and the answer is kept for next time.

    A hit costs about a millisecond instead of a 40 ms query. Most reads now never reach the database, so it drops to well under half busy, rejections stop and the median request is faster than it was even at 120 requests per second. Most of what remains is the network trip to the user.

    The cache-aside lesson walks through this read path step by step; here we look at why it works.

    Scene: A cache holding 1,000 products sits beside the database. The API checks it first; only misses reach the database, which is now well under half busy. Nothing fails and the median latency drops.

    Key idea: A cache trades a little memory for not repeating expensive work: hits are fast and never reach the database.

  4. 4. Why 10% of the data serves most reads

    The cache holds 10% of the products but serves well over half of the reads. That only works because popularity is skewed: a few products get most of the views, a long tail is rarely opened. This is called locality, and real traffic is full of it (home page items, trending posts, the logged-in user’s own profile).

    We model it with a Zipf distribution: the k-th most popular product is read about 1/k as often as the top one. The least recently used entries are evicted, so the popular ones stay.

    Scene: Same system. Product popularity is skewed (Zipf), so the 1,000 cached products, 10% of the catalogue, answer well over half of all reads.

    Key idea: Caches work because access is skewed: a small hot set gets most of the traffic.

  5. 5. Hit ratio sets latency and database load

    We shrink the cache to 100 products, 1% of the catalogue. Thanks to the skew it still answers more than a third of reads, but fewer than before, and both things we care about get worse:

    Average latency ≈ hit ratio × hit time + (1 − hit ratio) × miss time. A miss costs the full query plus the cache check, so every point of hit ratio lost moves the average toward the slow path.

    Database load = requests × (1 − hit ratio). Going from about 65% to 40% hits does not sound dramatic, but it is the difference between 35 and 60 misses out of every 100 reads: the database does about 70% more work.

    Scene: The cache now holds only 100 products. It still answers more than a third of reads, but more requests miss: the database is busier and average latency is higher than with 1,000 entries.

    Key idea: Database load is proportional to the miss ratio, so small hit-ratio changes are big load changes.

  6. 6. When every key is equally likely

    Back to 1,000 entries, but now every product is equally likely to be read, like a crawler walking the whole catalogue or an export job. Nothing is hotter than anything else, so the cache can only hit about as often as the fraction of keys it holds: roughly 10%.

    Nine out of ten reads still go to the database, it saturates again and requests fail. The cache is now pure overhead: memory, a network hop and another component that can break.

    Scene: Every product is now equally likely. The 1,000-entry cache hits only about 10% of reads, the database saturates again and some requests fail.

    Key idea: Without locality, hit ratio ≈ cache size / data size. Caching uniform or one-off reads does not help.

  7. 7. When a cache earns its place

    Skewed popularity is back and the cache absorbs most reads again. A cache pays off when reads repeat (locality), when a miss is much more expensive than a hit, and when slightly old data is acceptable. Check those three before adding one.

    Once it carries load, it is part of your capacity: the database is now sized for the misses, not the traffic. The next lessons cover who loads and writes the cache: cache aside, read-through, write-through and write-behind.

    Scene: Zipf popularity is back. The 1,000-product cache answers most reads, the database is lightly loaded and nothing fails.

    Key idea: Cache when reads repeat, misses are expensive and some staleness is fine; then size the database for the misses.