Cache warming and monitoring
medium 27 minCache warming loads the values people will ask for before the traffic arrives, so a new or restarted cache does not send everything to the database.
See it run
Start cold, start warm, keep it warm, and read the numbers that show which of these you have.
Operations
Cold start
The cache restarts at full traffic, and nothing is in it.
Step 1 of 4
A normal day
- Hit rate
- 95%
- Database load
- 20%
95% hits. The database gets 5% of the reads and is at 20% of what it can do.
Step 1: A normal day
def read(key): value = cache.get(key) if value is None: # nearly always, at first value = database.read(key) cache.set(key, value, ttl=3600) return value- Time
- Minutes
- Database load
- Up to all reads
- Warm start
- a small, steady load
Work out the database load at a hit rate of zero. If it cannot survive that, you need a plan.
In the real world
The same cache warming and monitoring doing real jobs. Pick one and step through it.
The shop replaces its cache one hour before a sale.
Step 1 of 3
Fill the new one
- Hit rate
- 0%
- Database load
- 35%
The sale's product pages and the hottest keys are loaded slowly.
Step 1: Fill the new one
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Warming without a limit
criticalThousands of loads at once are the storm you wanted to prevent.
Wrongawait gather(*[load(k) for k in all_keys])Rightfor batch in chunks(hot_keys, 100): await gather(*[load(k) for k in batch]) await sleep(0.2)The same expiry for all warmed keys
majorThey were stored together and vanish together.
Wrongcache.set(key, value, ttl=3600)Rightcache.set(key, value, ttl=3600 * uniform(0.9, 1.1))Alerting on totals
majorA bad hour disappears in months of good numbers, and the alert never fires.
Wronghits_total / (hits_total + misses_total) < 0.95Rightrate(hits[5m]) / (rate(hits[5m]) + rate(misses[5m])) < 0.95Reading -1 as nearly expired
minorIn Redis -1 means no expiry and -2 means no key. Both look smaller than your limit.
Wrongif cache.ttl(key) < 0.2 * ttl: refresh(key)Rightleft = cache.ttl(key)if 0 <= left < 0.2 * ttl: refresh(key)
Interview tips
How to explain it
- Load the hot keys before the traffic.
- Go slowly and spread the expiry.
- Check the hit rate, then switch.
Memory trick: WARM
- Warm up before traffic.
- Analyse hit rate and latency, record metrics.
- Monitor and alert. First levels: 95-100-85.
Watch four numbers
- Hit rate over a window.
- p50, p95 and p99 from histograms.
- Memory and evictions.
Do not
- Warm everything.
- Block the start for ever.
- Mix up eviction and expiry.