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.
Video lesson · Chapter 1 of 5
Open the doors with empty shelves
Theory
Read or listen first. About 1 min.
What it is
A cache that has just started is cold: it is empty, so every request is a miss. Cache warming fills it with the values that will be needed, before or while traffic moves to it.
Cache monitoring measures the cache while it works: how often it has the answer, how long answers take, how full it is and how often it throws values away. Without those numbers nobody knows whether a cache is warm.
Why it exists
A database behind a cache is often sized for the misses, not for all the reads. If the cache is suddenly empty, the database sees many times its normal load and may fail, and then the cache cannot refill.
A cache also gets worse quietly. A new key format, a shorter expiry or a growing data set lowers the hit rate a little each day, until a busy day shows it. A graph and an alert show it first.
A short history
2012
The Prometheus monitoring system is started at SoundCloud.
2013
Facebook publishes a USENIX paper about running Memcached at very large scale. Its open source proxy, mcrouter, later offers cold cache warm up.
2014
PostgreSQL 9.4 adds the pg_prewarm extension, which loads table data into memory on request.
2018
PostgreSQL 11 lets pg_prewarm save what was in memory and load it again after a restart.
Words to know
- Cold and warm
- A cold cache holds little that is asked for. A warm one holds most of it.
- Hit rate
- Hits divided by hits plus misses.
- Percentile
- p99 is the time that 99% of requests beat. The slowest 1% take longer.
- Eviction
- Removing a value because memory is full.
- Expiry
- Removing a value because its time is over. Not the same as eviction.
- Alert
- A message when a measurement crosses a limit for some time.
How it works
Step through the idea, or press Play.
Load the hot keys. A list from real traffic, in small batches
Understand it
Start here
The greenhouse
Young plants arrive on a snowy day. A greenhouse can keep them alive, if it is warm before they come and somebody looks at the thermometer.
Warming without a thermometer is a guess. A thermometer without a bell needs somebody to stare at it.
The trouble
The cold cache
An example day, with assumed times
| State | What happens | Typical response |
|---|---|---|
| Cold, after a deploy or restart | Nearly all reads go to the database | 200 to 500 ms |
| Warming | Hot keys are loaded | Improving |
| Warm | Most reads are hits | 2 to 10 ms |
What the database feels
Why warm and watch
No cold start
No slow minutes after a deploy or a restart.
Steady speed
The first user gets nearly the same answer time as the last.
Early warning
Trouble shows on a graph before users feel it.
Planning
Choose the size of the cache from data.
Fill first, then switch
Way 1
Warm at start
Load known hot keys during start-up and report ready only afterwards. Good for critical data, known keys and deployments.
Ready means warm enough
How long warming takes
Way 2
Refresh before expiry
A background task renews important values before their time is over. With an expiry of one hour and a refresh at 80%, the value is renewed after 48 minutes. Users always find it, as long as the refresh works. If it keeps failing, the value expires, and that should raise an alert.
One key with refresh at 80%
Way 3
Predict from traffic
Yesterday's most read keys (example)
| Key | Reads | Warm it? |
|---|---|---|
| user 123 | 10,000 | Yes |
| product 456 | 8,500 | Yes |
| session 789 | 7,200 | No, it is gone tomorrow and must come from sign-in |
How many keys are worth it
Choose a way
| Way | Best for | Risk |
|---|---|---|
| At start | Known hot keys, new nodes, deployments | Slow start, stale list |
| Refresh before expiry | Few keys that must never miss | Work for keys nobody reads |
| Predict | Large sets with skewed traffic | The prediction can be wrong |
| Copy from a warm cache | Replacing a node or a cluster | Copies old values too |
| Shift traffic slowly | When you have no list | Some users get slow answers |
Guard
Warm without harm
Do
- Small batches with a pause
- Stop when the database is slow
- Spread the expiry times
- Use the same loader as a normal miss
- Never overwrite a newer value
Do not
- Load everything at once
- Warm all servers at the same second
- Block the start for ever
- Warm sessions or one-time values
- Treat one failed key as a failed start
Replace a cache without a cold start
Measure 1
Hit rate
Hit rate
A starting point
| Hit rate | Meaning for a read-heavy cache |
|---|---|
| Below 85% | Investigate |
| 85% to 95% | Good, can improve |
| Above 95% | Excellent |
Why it is low
Expiry too short
Values leave before they are used again.
Cache too small
Values are evicted before they are used again.
Poor keys
Every request has its own key, for example with a time in it.
Cold start
No warming after a deploy.
Measure 2
Latency percentiles
| Percentile | Meaning | Example |
|---|---|---|
| p50 | Half of requests are faster | 5 ms |
| p95 | 95 in 100 are faster | 25 ms |
| p99 | 99 in 100 are faster | 100 ms |
Average, and what it hides
Measure 3
Memory and evictions
| Memory in use | State | Action |
|---|---|---|
| Below 70% | Healthy | None |
| 70% to 85% | Watch | Plan more room |
| Above 85% | Act | Add memory or remove junk |
Values leave too early. Which way?
Where to read them in Redis
| Number | Field of the INFO command |
|---|---|
| Hits and misses | keyspace_hits, keyspace_misses |
| Evictions | evicted_keys |
| Memory | used_memory |
Collect
From the program to a graph
Collect, draw, alert
- 1
Counters
Hits, misses, evictions, errors, with the cache's name as a label. Never put a key in a label.
- 2
Histogram
Time of each call in buckets, separate for get, set and errors.
- 3
Gauges
Memory in use, number of keys.
- 4
Rates
Graph what changed in the last minutes, not the totals.
Alert
Alerts that lead to an action
| Level | Examples to start from | Reaction |
|---|---|---|
| Critical | Hit rate below 80%, p99 above 500 ms, memory above 95% where nothing can be evicted, a node unreachable | Page someone now |
| Warning | Hit rate below 95%, p99 above 100 ms, memory above 85%, more than 1,000 evictions a minute | Look during the day |
| Information | Warming finished, refresh finished, settings changed | Dashboard only |
- alert: CacheHitRateLow expr: | sum(rate(cache_hits_total[5m])) / (sum(rate(cache_hits_total[5m])) + sum(rate(cache_misses_total[5m]))) < 0.95 for: 5m labels: severity: warning annotations: summary: "Cache hit rate below 95%"Summary
The whole topic in one minute.
Warm a cache with the keys that carry most of the traffic, in small batches, and give their expiry times some spread. Check the hit rate before you send it full traffic, and refresh important keys before they expire.
Watch hit rate, latency percentiles, memory and evictions as rates over a window. Tie each alert to something a person can do, and compare with your own normal, because 95% is not right for every cache.
- A cold cache sends its reads to the database, which may not survive.
- Warm the few keys that carry most reads, slowly, with spread expiry.
- Refresh before expiry, and alert when the refresh fails.
- Watch hit rate, percentiles, memory and evictions as rates.
- Evictions mean full, expiries mean time is over.