SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
  • CDN
  • Distributed Cache Architecture
  • Cache Stampede
  • Cache Warming
  • Hot Keys
  • Cache Penetration and Cache Avalanche
  • CDN Push vs Pull
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Caching/Distributed Caching

Cache Warming

Fill the cache before users arrive, so the first visitors are not slow.

โฑ 10 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Cache warming means filling a cache with the data you expect to need before users ask for it. The first visitors then get fast answers too.

  • A new or restarted cache is cold: empty, so almost every request misses and goes to the database.
  • Warming makes it warm: the popular items are already there.
  • Warm the right data (the hot items), and do it gently so you do not hurt the database.

02Concept: What is it?

A cache learns what is popular only after users ask for it. Until then it is empty. That empty time is the cold start. During a cold start the hit ratio is near zero, pages are slow, and the database carries all the traffic.

Cold start vs warm start
Cold cache
Hit ratio at second 1about 5%
Database loadhigh
Warm cache
Hit ratio at second 1about 85%
Database loadlow
A warm cache has a high hit ratio from the first second. A cold cache takes time to learn.
๐Ÿง When is a cache cold?
After a deploy, a restart, a new node, a flush, a failover to an empty replica, a new region, or when you start a new product with no history.

03Real-Life Example

๐ŸตThe Morning Tea Stall
A tea stall opens at 6 am. If the owner starts boiling water only when the first customer asks, the first 20 people wait a long time. A smart owner arrives at 5:30 and prepares the kettle, cups and snacks that sell most. When the first customer comes, tea is ready.
Tea stall
Cache
Stall before opening
Cache after a restart (cold)
Preparing the popular items early
Cache warming
Knowing what sells most
Hot keys from logs or analytics
Preparing every item on the menu
Warming everything (wasteful)
Preparing slowly so the helper is not overworked
Throttled warming that protects the database
First customers served at once
High hit ratio from the first second
A safe deploy with warming
๐Ÿš€New cache nodeempty
โ†’โ†“
๐Ÿ”ฅWarm hot keysfrom a list or logs
โ†’โ†“
โœ…Check hit ratiois it ready?
โ†’โ†“
๐ŸšฆSend usersstart traffic

04Why Do We Need It?

โšกFast from the start
The first users do not pay the price of an empty cache.
๐Ÿ›ก๏ธProtect the database
A cold cache sends all the traffic to it. Warming avoids that wave.
๐Ÿš€Safe deploys
You can restart or replace cache nodes without a slow period.
๐ŸŒNew regions and nodes
A new data centre starts with a useful cache.
๐ŸŽŸ๏ธPlanned spikes
Warm the sale pages before the sale begins.
๐Ÿ˜€Better first impression
Many users arrive right after a launch.
Do the slow work before the crowd arrives, not while they wait.

05Where Do We Use It?

๐Ÿ”Deploys and restarts
Cache nodes or in-memory caches inside new app servers.
๐Ÿ›’Before a sale or launch
Product pages and prices for a big event.
๐ŸŒCDN edges
Pre-load big files (a game update, a new video) to the edges.
๐Ÿ—„๏ธDatabase buffer cache
Databases warm their own memory after a restart.
๐ŸงฎSearch and ML models
Load indexes and models into memory before serving.
๐ŸšฆAuto-scaling
New servers get a useful cache before they take traffic.

06Types / Parts / How It Works

Ways to warm a cache

ApproachHow it worksGood and bad
Preload a listA script reads a list of known hot keys (or top products) and loads them.Simple and fast. The list can be out of date.
Replay recent trafficTake the most-read keys from recent logs or analytics, and read them through the cache.Matches real behaviour. Needs good logs.
Copy from another cacheDump from an existing cache or replica, then load it into the new one.Very complete. Can be large, and the data may be a little old.
Lazy, throttled warmingLoad the hottest keys a little at a time, while real traffic flows.Gentle on the database. Takes longer.
Scheduled refreshA job rebuilds hot items on a timer, so they never go cold.Keeps data fresh. Costs steady background work.
Shift traffic slowlySend 1 percent, then 10 percent, then all traffic to a new node.Lets the cache fill by itself. Needs a smart load balancer.
Cold start
Do nothing
  • Slow first requests
  • Big spike on the database
  • Can trigger a stampede
  • No extra work
Warm start
Prepare first
  • Fast from the first request
  • Gentle, predictable database load
  • Needs a list or logs
  • Extra code and time to run
Where warming data comes from
๐Ÿ“ŠAnalyticstop pages
๐Ÿ“œAccess logsrecent reads
๐Ÿ“‹A fixed listsale items
โ†’โ†“
๐Ÿ”ฅWarming job
โ†’โ†“throttled
โšกCache
Where hot keys come from The job Result
Any of these can feed the warming job.
VisualizerCold cache vs warm cache after a deploySlide the number of preloaded items to 0, then raise it. Try the three strategies and more traffic.
Warming strategy

Replay recent real traffic (or the most-read keys from the logs) into the new cache. The best match, but you need those logs.

Cache contents at second 39 (each square is one item, item 1 is the most popular; bright border = one of the 20 hottest)
Cache hit ratio per second (faint grey = cold start, cyan = warmed)
Database queries per second
0 s20 s40 s
Hot items ready
20/20
Cold: seconds over limit
1
peak 200 q/s
Warm: seconds over limit
0
peak 61 q/s
Warm-up cost
20
database reads to fill it
Warm cache: the first second starts at 69% hit ratio and 61 database queries. A cold cache would start at 0% and 200 queries.

A simplified model with a simulated clock and expected values (no random numbers). The red dashed line is what the database can handle (120 queries per second). Do not warm everything: warm the hot keys, and warm slowly enough that the database is not hurt.

07How to Use It / Steps / Implementation

Warming without causing a new problem

  1. 1
    Find what is hot
    Use logs, analytics or last week's top items. A small number of items usually gets most of the traffic.
  2. 2
    Warm only the hot part
    Warming everything wastes memory and database reads. Start with the top few percent.
  3. 3
    Throttle the job
    Limit how many reads per second the warmer makes, so it never overloads the database.
  4. 4
    Warm before traffic arrives
    Fill the cache, check the hit ratio, and only then add the node to the load balancer.
  5. 5
    Use the same code path as real reads
    Warm through the normal cache-aside code, so keys and formats match exactly.
  6. 6
    Set sensible TTLs with jitter
    Items you warm together should not all expire together.
  7. 7
    Measure
    Compare hit ratio, latency and database load with and without warming.
โš ๏ธWarming can hurt
If the warming job reads too fast, it can overload the database on its own. If it warms the wrong keys, you pay and get nothing. And if everything is warmed with the same TTL, it can all expire at once (see Cache Stampede).
Hit ratio goal before sending trafficfor example 80% or more of normal

08Key Terms to Know

TermMeaning in easy words
Cold cacheAn empty or nearly empty cache with a very low hit ratio
Warm cacheA cache that already holds the popular items
Cache warming / primingFilling a cache before users ask
Hit ratioThe share of reads served from the cache
Hot keyA key that gets a lot of reads
Cold startThe slow period right after a cache or server starts
ThrottlingLimiting the speed of a job so it does not overload others
Pre-fetchingLoading something before it is requested
Canary / gradual rolloutSending a small share of traffic to a new node first
TTL jitterA random extra time added to expiry to spread it out

09Pros, Cons and Trade-offs

โœ… Pros
  • Fast responses from the first request
  • A calm database after deploys and restarts
  • Safer scaling and failover
  • Good for planned events
โš ๏ธ Cons
  • Extra code and a job to maintain
  • You must know what is hot
  • Wasted memory and reads if you guess wrong
  • Can overload the database if not throttled
  • Warm data can be a little out of date

Trade-offs

ChoiceWe gainWe lose
Warm many itemsHigher hit ratio soonerMore memory, more database reads
Warm few itemsCheap and gentleSome users still hit a cold cache
Warm fastReady soonerRisk to the database
Warm slowlySafe for the databaseLonger cold period
Do not warmSimplestSlow starts and big spikes

10Common Problems and Mistakes

Common mistakes

  1. Warming everything. It takes long, wastes memory and may push out useful keys.
  2. An un-throttled warming job. It becomes a stampede that you caused yourself.
  3. A stale warming list. The list still names products that no one buys.
  4. Sending traffic before the cache is ready. The load balancer should wait for a readiness check.
  5. Same TTL for all warmed items. They all expire at the same moment later.
  6. Warming with a different key format. The cache is full of keys the app never asks for.

Things to watch

๐ŸŒŠStampede later
Items warmed together expire together. Use jitter.
๐Ÿ’พMemory pressure
Over-warming can push out better entries (eviction).
๐Ÿ•ฐ๏ธOld data
Warm data may be older than live data. Pick a fresh source.
๐Ÿ”’Private data
Do not warm user-specific data into a shared cache without care.

11Real-World Examples

๐Ÿ›’Sale and launch events
Teams preload product pages and prices before a big sale starts.
๐ŸŒCDNs
Providers can pre-load or โ€œprefetchโ€ large files to edges before a release (general idea).
๐Ÿ—„๏ธDatabases
Many databases warm their buffer pool after a restart so queries are not slow at first.
๐Ÿš€Auto-scaling groups
New servers run a readiness check and a warm-up step before they join the load balancer.
๐Ÿค–ML and search services
Models and indexes are loaded into memory before taking requests.
๐ŸŽฌStreaming apps
New popular titles are copied to edge servers before a premiere (general idea).
๐Ÿ“Note
These are general ideas. Each system has its own tools.
Mini case: replacing a cache cluster
๐Ÿ‘ฅUsers
โ†’โ†“100%
โšกOld cachefull
โ‡ขโ‡ฃcopy hot keys (throttled)
โšกNew cachewarming โ†’ warm
โ†’โ†“1% โ†’ 10% โ†’ 100%
โœ…Switch done
Warm the new cluster, then move traffic over in steps. The database never sees a big wave.

12Related Topics to Read Next

What is Caching?โ†’

Hits, misses and the idea of a cold cache.

Cache Stampedeโ†’

A cold cache or an over-eager warmer can cause one.

Distributed Cache Architectureโ†’

Where new nodes and failovers make cold caches.

CDNโ†’

Edges can be pre-loaded with big files.

Cache Eviction Policiesโ†’

Over-warming pushes other items out.

What are Load Balancers?โ†’

Send traffic only when the node is ready.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: fill the cache with likely-needed data before users arrive.
  • โœ”Why: a cold cache means slow requests and a database spike.
  • โœ”Warm: the hot items only. Use logs, analytics or a planned list.
  • โœ”How: preload a list, replay traffic, copy from another cache, or shift traffic slowly.
  • โœ”Be gentle: throttle the job, so the database stays safe.
  • โœ”Be careful: use TTL jitter, and do not send traffic before the node is ready.
  • โœ”Measure: hit ratio, latency and database load.
  • โœ”One line: โ€œPrepare the popular items before the crowd arrives, and do it gently.โ€
โ† Previous
Cache Stampede
Next โ†’
Hot Keys