Sub topic 1
What a Cache Is and When It Pays Off
Prerequisites
This chapter assumes you can read basic Python, know how a client sends requests to a server that queries a database, and understand latency (time for one request) and throughput (requests handled per second).
What a cache is
A cache is a small, fast store that keeps copies of data that is expensive to fetch or compute. When code needs the data, it looks in the cache first. The original source, such as a database, is called the source of truth.
Two outcomes are possible on each lookup:
- A hit: the cache has the data, and you return it quickly.
- A miss: the cache does not have it, so you read from the source and usually store the result for next time.
Hit ratio and the cost of a lookup
The hit ratio is hits divided by total lookups. If 90 of 100 lookups hit, the ratio is 0.9.
Average latency depends on the hit ratio and on both latencies:
average = hitratio × cachelatency + (1 − hitratio) × (cachelatency + source_latency)
A miss pays for the cache lookup and then the source read. That is why a cache with a low hit ratio can make things slower.
def average_latency(hit_ratio, cache_ms, source_ms):
miss_ratio = 1 - hit_ratio
return hit_ratio * cache_ms + miss_ratio * (cache_ms + source_ms)
for ratio in (0.0, 0.5, 0.9, 0.99):
print(ratio, round(average_latency(ratio, cache_ms=1, source_ms=50), 2))With a 1 ms cache and a 50 ms database, the output is 51.0, 26.0, 6.0, and 1.5 ms. At a ratio of 0 the cache only adds 1 ms to every request.
Why hit ratios can be high: locality
Caches work because real access patterns are uneven. Two kinds of locality explain this:
- Temporal locality: data used recently is likely to be used again soon.
- Spatial locality: data near recently used data is likely to be used next.
A few popular items, such as a front-page article or a top product, often receive most of the reads. Caching just those items can give a high hit ratio with a small cache.
When a cache pays off
A cache is worth adding when most of these hold:
- Reads far outnumber writes.
- The source is slow or costly, or it is a bottleneck under load.
- The same keys are requested repeatedly.
- Slightly stale data is acceptable.
It pays off poorly when data changes on nearly every read, when every request asks for a different key, or when the source is already as fast as the cache.
Check your understanding
Exercise
A cache lookup takes 2 ms and a database read takes 40 ms. The hit ratio is 0.75. What is the average latency, and would the cache help if the hit ratio were 0?
Show answer
Average = 0.75 × 2 + 0.25 × (2 + 40) = 1.5 + 10.5 = 12 ms. At a hit ratio of 0, every request takes 2 + 40 = 42 ms, which is 2 ms slower than having no cache, so the cache would not help.