Sub topic 16
Measuring cache effectiveness
This chapter assumes you know how cache-aside works, what a TTL is, and how eviction policies like LRU behave. It covers how to tell whether a cache is helping and where to look when it is not.
The numbers that matter
A cache is worth keeping only if it lowers the cost of a read. Track these metrics:
- Hit ratio: hits divided by total lookups. Report it over a time window, not just since startup.
- Latency: measure hits and misses separately, and use percentiles (p50, p95, p99) instead of averages. A miss that stalls for 800 ms disappears in a mean.
- Evictions: how many entries were removed to make room. Count these separately from entries that expired by TTL.
- Memory use and entry count: how close the cache is to its limit.
Is the cache paying for itself?
With cache-aside, every miss pays for the cache lookup and then the source read. The expected latency is:
t_avg = t_cache + (1 - h) * t_source
Suppose t_cache is 1 ms and t_source is 20 ms. At a 90% hit ratio, t_avg is 1 + 0.1 × 20 = 3 ms. At 50%, it is 11 ms. Without a cache it is 20 ms. The cache wins whenever h > t_cache / t_source, which here is 5%. A cache can clear that bar and still not be worth its complexity, so also consider load on the source. A 90% hit ratio cuts source traffic by 10 times.
Instrumenting a cache
Count hits and misses at the point where you read the cache, and time the loader on a miss.
import time
class MeteredCache:
def __init__(self, ttl=60):
self.ttl = ttl
self.data = {} # key -> (value, expires_at)
self.hits = 0
self.misses = 0
self.load_seconds = 0.0
def get(self, key, loader):
entry = self.data.get(key)
if entry is not None and entry[1] > time.monotonic():
self.hits += 1
return entry[0]
self.misses += 1
start = time.monotonic()
value = loader()
self.load_seconds += time.monotonic() - start
self.data[key] = (value, time.monotonic() + self.ttl)
return value
def hit_ratio(self):
total = self.hits + self.misses
return self.hits / total if total else 0.0
cache = MeteredCache()
for key in ["a", "b", "a", "a", "c", "b"]:
cache.get(key, lambda: "value")
print(f"hits={cache.hits} misses={cache.misses} ratio={cache.hit_ratio():.2f}")This prints hits=3 misses=3 ratio=0.50. In production, export the counters to a metrics system and compute the ratio per window. A lifetime counter hides a recent drop.
Diagnosing a low hit ratio
Read the hit ratio together with the eviction rate.
Common errors
- Averaging latency. Hits and misses form two clusters, so the mean describes neither.
- Ignoring warm-up. A freshly started cache is empty. Measure after it fills.
- Chasing the ratio alone. A long TTL raises the hit ratio and the staleness together.
- Counting errors as misses or hits. Track cache failures separately, or an outage looks like a cold cache.
Exercise
A cache has tcache = 2 ms and tsource = 40 ms. What is the average latency at a 75% hit ratio, and what is the minimum hit ratio at which the cache beats having no cache?
Show answer
Average latency is 2 + 0.25 × 40 = 12 ms. The break-even hit ratio is tcache / tsource = 2 / 40 = 5%.