Sub topic 16
Measuring Cache Effectiveness
This chapter assumes you know basic Python, how a client talks to a server and a database, and the difference between latency and throughput. It also assumes you have met the cache patterns and eviction policies from earlier chapters. Here you will learn which numbers show whether a cache helps, how to collect them, and how to read them.
Why measure at all
A cache adds code, memory use, and a risk of stale data. It is worth keeping only if it makes requests faster or cheaper. You can't tell that by looking at the code. A cache with a bad key design or a poor eviction policy can run for months and save almost nothing.
Three questions guide the measurements:
- How often does the cache answer a request? (hit ratio)
- How fast is it when it answers, and how slow is the miss path? (latency)
- Is it losing entries it should keep? (evictions and memory)
Hit ratio
A hit is a request served from the cache. A miss is a request that has to go to the source. The hit ratio is the share of lookups that are hits.
hit ratio = hits / (hits + misses)A ratio of 0.90 means 9 of every 10 lookups are served from the cache. A good ratio depends on the workload. A cache of user profiles may reach 0.95 or more. A cache of search results with many unique queries may stay near 0.3 and still pay off if each miss is expensive.
Count only lookups in the denominator. Writes and invalidations are not hits or misses.
Hit ratio over time
A single lifetime average hides problems. A cache that started cold, then deployed a new key format, will show a smooth average while current behavior is poor. Track the ratio over short windows, such as one minute, and watch it after deployments, restarts, and traffic changes. A cold cache after a restart shows a low ratio that climbs as it fills. That is normal. A ratio that falls while traffic is steady is not.
Hit ratio by key group
Break the ratio down by key prefix or by endpoint. One hot group with a high ratio can hide another group with a ratio near zero. The low group is occupying memory and adding lookup cost for nothing.
Latency and the break-even point
A high hit ratio does not guarantee a faster system. Every request pays for the cache lookup. Only misses also pay for the source read, and often for the fill.
The average latency of a cached read is:
average = hit_ratio * hit_latency + (1 - hit_ratio) * (lookup_latency + source_latency + fill_latency)For example, take a lookup of 1 ms, a database read of 20 ms, and a fill of 1 ms. With a hit ratio of 0.8, the average is 0.8 × 1 + 0.2 × (1 + 20 + 1) = 5.2 ms. Without the cache it is 20 ms. With a hit ratio of 0.05 it is 0.05 × 1 + 0.95 × 22 = 20.95 ms, which is slower than no cache.
The break-even hit ratio is where the cached average equals the uncached latency. With the numbers above:
h * 1 + (1 - h) * 22 = 20
22 - 21h = 20
h = 2 / 21 ≈ 0.095Below about 10% the cache costs more than it saves. When the source is fast, the break-even point rises. When the source is slow, even a modest ratio pays off.
Use percentiles, not averages
Averages hide the tail. Misses are slower than hits, so the slowest requests are usually misses, and during a stampede they can be much slower. Record p50, p95, and p99 latency for both paths. Track hit latency and miss latency as separate series. If p99 of the whole endpoint is dominated by misses, raising the hit ratio or protecting the miss path matters more than making hits faster.
Eviction, memory, and expiry metrics
Hit ratio tells you the result. These counters tell you the cause.
| Metric | What it shows | Warning sign |
|---|---|---|
| Evictions per second | Entries removed because the cache is full | Steady high rate with a falling hit ratio |
| Expirations per second | Entries removed because the TTL passed | Spikes at regular intervals |
| Memory used vs. limit | How close the cache is to capacity | Sitting at the limit |
| Item count | Number of live entries | Growth without bound |
| Average entry size | Memory cost per entry | A few huge entries crowding out many small ones |
| Fill rate | Loads from the source per second | Spikes when hit ratio drops |
A useful pattern is to read these together. If evictions are high and the hit ratio is low, the cache is probably too small for the working set, so entries are removed before they are reused. If evictions are near zero and the hit ratio is still low, the problem is elsewhere: keys that are never repeated, a TTL that is too short, or keys that include a value that changes on every request, such as a timestamp.
Instrumenting a cache in code
Counters belong inside the cache wrapper, so every caller is measured the same way. The example below extends an LRU cache with hit, miss, and eviction counters, and reports a ratio.
from collections import OrderedDict
class MeasuredLRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.items = OrderedDict()
self.hits = 0
self.misses = 0
self.evictions = 0
def get(self, key, default=None):
if key not in self.items:
self.misses += 1
return default
self.hits += 1
self.items.move_to_end(key)
return self.items[key]
def put(self, key, value):
self.items[key] = value
self.items.move_to_end(key)
if len(self.items) > self.capacity:
self.items.popitem(last=False)
self.evictions += 1
def stats(self):
lookups = self.hits + self.misses
ratio = self.hits / lookups if lookups else 0.0
return {
"hits": self.hits,
"misses": self.misses,
"evictions": self.evictions,
"hit_ratio": round(ratio, 3),
"size": len(self.items),
}
cache = MeasuredLRUCache(capacity=2)
for key in ["a", "b", "a", "c", "b", "a"]:
if cache.get(key) is None:
cache.put(key, key.upper())
print(cache.stats())Trace the run. The first a and b miss. The second a hits. c misses and evicts b, because a was used more recently. The next b misses and evicts a. The final a misses. The result is 1 hit, 5 misses, 3 evictions, and a hit ratio of 0.167. The high eviction count next to a low ratio is the pattern described above: the cache is too small for this working set.
In production you would export these counters to a metrics system and compute the ratio over a window from counter differences. Do not export the ratio itself as a counter, because ratios from several servers cannot be added together. Export hits and misses, then divide after summing.
Many cache servers expose these numbers directly. Redis reports keyspace_hits, keyspace_misses, and evicted_keys in its INFO stats output, and Memcached reports get_hits, get_misses, and evictions in its stats. These server-wide counters mix all key groups, so keep application-level counters when you need the breakdown by group.
Reading the numbers together
Each branch points to a different fix, which is why the single hit ratio number is not enough.
Common mistakes
- Measuring only the average. Report percentiles for hits and misses separately.
- Ignoring cold starts. Compare ratios only after the cache has warmed, or the numbers will mislead you after every restart.
- Counting stale reads as good hits. A hit that returns outdated data is fast but may be wrong. If staleness matters, also measure the age of served entries or how often a hit disagrees with the source in a sampled check.
- Testing with unrealistic traffic. Uniform random keys give a lower hit ratio than real traffic, which is usually skewed toward a few hot keys. Replay real request logs where you can.
- Adding a cache without a baseline. Record latency and source load before the change, so you can show the benefit.
Setting targets and alerts
Pick targets from your own break-even calculation rather than a universal number. Useful alerts include:
- Hit ratio below a threshold for several minutes, after the warm-up period.
- Eviction rate above a threshold while memory is at its limit.
- Miss-path p99 latency above a limit, which warns of source trouble or a stampede.
- A sudden jump in fills per second, which often marks a mass expiry or a bad deployment.
Alert on changes as well as absolute levels. A drop from 0.92 to 0.80 may still look healthy by a fixed threshold but signals that something changed.
Exercise
A cache lookup costs 2 ms, a database read costs 30 ms, and filling the cache after a miss costs 2 ms. Using the average-latency formula, what is the average latency at a hit ratio of 0.5, and is the cache worth keeping at that ratio?
Show answer
Miss path = 2 + 30 + 2 = 34 ms. Average = 0.5 × 2 + 0.5 × 34 = 1 + 17 = 18 ms. That is lower than the 30 ms uncached read, so the cache is worth keeping. The break-even ratio solves h × 2 + (1 - h) × 34 = 30, which gives h = 4 / 32 = 0.125.
Exercise
Your cache shows a hit ratio of 0.25, an eviction rate near zero, and memory use at 10% of the limit. Which cause is most likely, and what would you check first?
Show answer
Capacity is not the problem, because nothing is being evicted and memory is mostly free. The likely causes are keys that rarely repeat (for example a timestamp or request ID inside the key) or a TTL that is too short. Check the key format and the expiration rate first.