Sub topic 1
What a Cache Is and When It Pays Off
Prerequisites
This chapter assumes you can read basic Python, and that you know how a client sends a request to a server and how a server reads from a database. It also assumes you understand latency (the time one request takes) and throughput (how many requests a system handles per second). No caching experience is needed.
What a cache is
A cache is a small, fast store that keeps copies of data that is slow or expensive to get from its original source. The original source is called the source of truth, or the origin. A cache never replaces the origin. It holds a copy, and the origin still owns the correct value.
Typical origins are a database, a remote API, or the result of a heavy computation. Typical caches are process memory, a dedicated in-memory server, a CDN edge server, or a browser's local storage.
Every cache follows the same basic loop:
- A caller asks for a value by key.
- The cache looks for the key.
- If the key is present, the cache returns the stored copy. This is a hit.
- If the key is absent, the caller goes to the origin, gets the value, and usually stores a copy in the cache. This is a miss.
Hits, misses, and hit ratio
The hit ratio is the share of lookups that are hits:
hit ratio = hits / (hits + misses)If 900 of 1,000 lookups are hits, the hit ratio is 0.9, or 90%. The miss ratio is the remainder, 10% here.
A hit ratio is only meaningful for a specific workload and time window. A cache that starts empty (a cold cache) has a hit ratio near zero. As it fills (it warms up), the ratio rises. Measure after warm-up, or you will understate the cache's value.
Why caching works: locality
Caching helps because real access patterns are uneven. Two kinds of locality explain this:
- Temporal locality: data used recently is likely to be used again soon. A product page that was just viewed is likely to be viewed again in the next minute.
- Spatial locality: data near recently used data is likely to be needed next. Reading one row from a disk page loads the neighboring rows as well.
Many workloads also have a skewed popularity distribution. A small set of keys receives most of the traffic, such as a handful of popular products or the home page. Caching only that hot set can capture most of the benefit with a small amount of memory.
If every request asks for a different key and never repeats, no locality exists. A cache in that case mostly adds cost.
The cost model: when does a cache pay off?
A cache adds a lookup to every request, and it saves the origin call only on hits. The average time per request (the effective latency) is:
effective latency = hit_ratio * cache_latency + (1 - hit_ratio) * (cache_latency + origin_latency)
= cache_latency + (1 - hit_ratio) * origin_latencyMisses pay for both the cache lookup and the origin read. This is why a low hit ratio can make a system slower than having no cache.
Suppose the cache lookup takes 1 ms and the origin takes 50 ms:
| Hit ratio | Effective latency | Compared with no cache (50 ms) |
|---|---|---|
| 0% | 51 ms | Slower by 1 ms |
| 50% | 26 ms | About 1.9x faster |
| 90% | 6 ms | About 8.3x faster |
| 99% | 1.5 ms | About 33x faster |
The break-even hit ratio is the point where effective latency equals the origin latency alone. Setting cache_latency + (1 - h) * origin_latency = origin_latency gives h = cache_latency / origin_latency. Here that is 1/50, or 2%. When the cache is much faster than the origin, even a modest hit ratio pays off in latency.
You can check this calculation in code:
def effective_latency(hit_ratio, cache_ms, origin_ms):
return cache_ms + (1 - hit_ratio) * origin_ms
def break_even_hit_ratio(cache_ms, origin_ms):
return cache_ms / origin_ms
for h in (0.0, 0.5, 0.9, 0.99):
print(f"hit ratio {h:.0%}: {effective_latency(h, 1, 50):.1f} ms")
print(f"break-even: {break_even_hit_ratio(1, 50):.0%}")The output is 51.0, 26.0, 6.0, and 1.5 ms, then a break-even of 2%.
Latency is not the only benefit
Caches also reduce load on the origin. At a 90% hit ratio the origin sees one tenth of the reads. This can mean fewer database replicas, lower bills for paid APIs, and protection against traffic spikes. Throughput gains can matter more than latency gains when the origin is the bottleneck.
What a cache costs
A cache is not free. Before adding one, account for these costs:
- Staleness. The cached copy can differ from the origin after the origin changes. Later chapters cover expiration and invalidation, which limit this.
- Complexity. You now have two places where data lives, and code that keeps them in step. Bugs here are often subtle and hard to reproduce.
- Memory and infrastructure. Caches use RAM, and a shared cache is another service to run, secure, and monitor.
- Cold-start behavior. After a restart or deploy, the cache is empty and the origin takes the full load until it warms up.
- Failure modes. If the origin depends on the cache to handle normal load, a cache outage can become a full outage.
When a cache pays off
A cache is a good fit when most of these hold:
- Reads greatly outnumber writes. Each write can make cached copies obsolete, so frequently changing data gives a low hit ratio and heavy invalidation work.
- The origin is slow or expensive. Joins over large tables, remote API calls, and rendering work are good candidates.
- Keys repeat. The workload shows temporal locality or skewed popularity.
- Some staleness is acceptable. A product description that is a minute old is usually fine. An account balance used to authorize a payment usually is not.
- Values are cheap to store. Small or moderately sized values fit many entries in memory.
A cache is a poor fit when data is unique per request, changes constantly, or must always be exactly current.
A minimal example
The following code wraps a slow function with a dictionary and counts hits and misses. It runs as shown.
import time
cache = {}
hits = 0
misses = 0
def slow_lookup(key):
time.sleep(0.05) # simulate a 50 ms origin
return key.upper()
def cached_lookup(key):
global hits, misses
if key in cache:
hits += 1
return cache[key]
misses += 1
value = slow_lookup(key)
cache[key] = value
return value
keys = ["a", "b", "a", "a", "c", "b", "a", "a", "a", "b"]
start = time.perf_counter()
for k in keys:
cached_lookup(k)
elapsed = time.perf_counter() - start
print(f"hits={hits} misses={misses} ratio={hits / (hits + misses):.0%}")
print(f"elapsed={elapsed * 1000:.0f} ms (uncached would be about 500 ms)")Three distinct keys cause three misses, and the other seven lookups are hits, so the ratio is 70%. The run takes about 150 ms instead of about 500 ms.
This sketch has no expiration, no size limit, and no thread safety. The dictionary grows without bound and never refreshes. Those gaps are the subject of the chapters on TTL, eviction, and invalidation.
Common mistakes when evaluating a cache
- Judging by a cold cache. Early measurements show many misses. Measure after warm-up.
- Looking at averages only. A 90% hit ratio still leaves 10% of requests at origin speed. If your latency target is on the 99th percentile, those misses define what users see.
- Ignoring miss cost. A miss that takes longer than an uncached call, because of extra serialization or a slow cache network hop, can hurt overall latency.
- Caching data with a near-zero reuse rate. Unique keys fill the cache and can evict useful entries.
- Assuming a higher hit ratio is always better. A high ratio achieved with very long retention can mean serving stale data. The goal is the right data at an acceptable freshness.
Exercise
A cache lookup takes 2 ms and the origin takes 40 ms. Measured over a day, the hit ratio is 60%. What is the effective latency, and what is the break-even hit ratio below which the cache makes requests slower than having no cache?
Show answer
Effective latency = cachelatency + (1 - hitratio) origin_latency = 2 + 0.4 40 = 18 ms. The break-even hit ratio is cachelatency / originlatency = 2 / 40 = 5%. Below a 5% hit ratio, the average request is slower with the cache than without it.
Exercise
A service stores each user's current account balance and checks it before approving payments. Balances change several times a minute. Explain why this data is a poor candidate for a cache with a 5-minute lifetime, and name one kind of data in the same service that would be a better candidate.
Show answer
The balance changes often, so cached copies go stale quickly and the hit ratio is low. A stale balance can also cause a wrong payment approval, and this use needs exact, current values. Better candidates are data that rarely changes and tolerates staleness, such as product descriptions, currency symbol lists, or a user's display name and profile picture.