AlgoViz

Cache warming and monitoring

medium 27 min

Cache 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

0:00 / 3:22

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

  1. 2012

    The Prometheus monitoring system is started at SoundCloud.

  2. 2013

    Facebook publishes a USENIX paper about running Memcached at very large scale. Its open source proxy, mcrouter, later offers cold cache warm up.

  3. 2014

    PostgreSQL 9.4 adds the pg_prewarm extension, which loads table data into memory on request.

  4. 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.

Step 1 of 3

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.

Warm it before the plants arrive
2°

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

StateWhat happensTypical response
Cold, after a deploy or restartNearly all reads go to the database200 to 500 ms
WarmingHot keys are loadedImproving
WarmMost reads are hits2 to 10 ms

What the database feels

Qdb=Q×(1−h)10,000×(1−0.95)=500/s10,000×(1−0.60)=4,000/sQ_{db} = Q \times (1 - h) \qquad 10{,}000 \times (1-0.95) = 500/\text{s} \qquad 10{,}000 \times (1 - 0.60) = 4{,}000/\text{s}
With 10,000 reads a second, a drop of the hit rate from 95% to 60% means 8 times the database load.

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

A warming job reads a list of hot keys and the database, and writes the values into a new cache machine in small batches. The load balancer sends users to the application, which starts to use the new cache only when it is warm.
Orange is the warming job, blue is user traffic. They use the same database, so the job is slowed down on purpose.

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

Give the warming a time limit. A server that can never become ready is worse than a cold one.

How long warming takes

T=keysallowed rate=100,000500/s=200 sT = \frac{\text{keys}}{\text{allowed rate}} = \frac{100{,}000}{500/\text{s}} = 200\,\text{s}
The rate is what the database can spare. Warm the keys that carry most of the traffic, not all keys.

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)

KeyReadsWarm it?
user 12310,000Yes
product 4568,500Yes
session 7897,200No, it is gone tomorrow and must come from sign-in
Reads of the past predict reads of the next hour fairly well. Add what you know: the match tonight, the sale at 9.

How many keys are worth it

hwarm≈∑i=1kri∑iri10,000+8,500100,000=18.5%h_{warm} \approx \frac{\sum_{i=1}^{k} r_i}{\sum_{i} r_i} \qquad \frac{10{,}000 + 8{,}500}{100{,}000} = 18.5\%
The share of all reads that the k warmed keys carry. Here two keys carry 18.5% of 100,000 reads. Stop when the next key adds almost nothing.

Choose a way

WayBest forRisk
At startKnown hot keys, new nodes, deploymentsSlow start, stale list
Refresh before expiryFew keys that must never missWork for keys nobody reads
PredictLarge sets with skewed trafficThe prediction can be wrong
Copy from a warm cacheReplacing a node or a clusterCopies old values too
Shift traffic slowlyWhen you have no listSome 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

The old cache answers in place of the database while the new one fills. Deletions must reach both, or an old value returns.

Measure 1

Hit rate

Hit rate

h=hitshits+misses950950+50=95%h = \frac{\text{hits}}{\text{hits} + \text{misses}} \qquad \frac{950}{950 + 50} = 95\%
Compute it over a window, such as the last 5 minutes. Since the start of the server it hardly moves.

A starting point

Hit rateMeaning for a read-heavy cache
Below 85%Investigate
85% to 95%Good, can improve
Above 95%Excellent
Not a law. A search cache with many different queries may be useful at 40%. Ask what the misses cost.

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

PercentileMeaningExample
p50Half of requests are faster5 ms
p9595 in 100 are faster25 ms
p9999 in 100 are faster100 ms
The average hides the tail. The slowest 1% is often the same few busy users.

Average, and what it hides

T=h thit+(1−h) tmiss0.95(2)+0.05(100)=6.9 msT = h\,t_{hit} + (1-h)\,t_{miss} \qquad 0.95(2) + 0.05(100) = 6.9\,\text{ms}
The average is 6.9 ms. But 5% of requests are misses, so p99 is a miss time, about 100 ms. To improve p99 here, make misses faster or rarer than 1%.

Measure 3

Memory and evictions

Memory in useStateAction
Below 70%HealthyNone
70% to 85%WatchPlan more room
Above 85%ActAdd memory or remove junk
For a cache with an eviction policy, full memory is normal. Then evictions and the hit rate matter more than the percentage.

Values leave too early. Which way?

Eviction means full. Expiry means time is over. They look alike on the hit rate and need different fixes. See cache eviction.

Where to read them in Redis

NumberField of the INFO command
Hits and misseskeyspace_hits, keyspace_misses
Evictionsevicted_keys
Memoryused_memory
All of the first three only grow. Use the difference over a window.

Collect

From the program to a graph

Collect, draw, alert

The application and the cache report numbers. Prometheus collects them at intervals. Grafana draws them, and an alert goes to the person on call.
The application counts hits and misses, because it knows which cache and which kind of key.
  1. 1

    Counters

    Hits, misses, evictions, errors, with the cache's name as a label. Never put a key in a label.

  2. 2

    Histogram

    Time of each call in buckets, separate for get, set and errors.

  3. 3

    Gauges

    Memory in use, number of keys.

  4. 4

    Rates

    Graph what changed in the last minutes, not the totals.

Alert

Alerts that lead to an action

LevelExamples to start fromReaction
CriticalHit rate below 80%, p99 above 500 ms, memory above 95% where nothing can be evicted, a node unreachablePage someone now
WarningHit rate below 95%, p99 above 100 ms, memory above 85%, more than 1,000 evictions a minuteLook during the day
InformationWarming finished, refresh finished, settings changedDashboard only
Set the numbers from your own normal weeks. An alert that fires every day is soon ignored.
Text
- 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%"
A Prometheus rule. The rates look at the last five minutes, and the condition must hold for five minutes before it fires.

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.

Sources