SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
  • What is Caching?
  • Caching Strategies
  • Cache Eviction Policies
  • Cache Invalidation
  • HTTP Caching (Cache-Control, ETag)
  • Redis vs Memcached
  • Local Cache vs Distributed Cache
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/Caching Basics

What is Caching?

Keep a copy of popular data in a fast place, so you do not fetch it from the slow place every time.

โฑ 13 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A cache is a fast, small place where we keep a copy of data that people ask for again and again. Next time, we answer from the copy and skip the slow work.

  • Fast memory is small and costly. Slow storage is big and cheap. A cache gives us the speed of the first with the size of the second.
  • A hit means the data was in the cache. A miss means it was not, so we go to the slow place.
  • Caching works because people ask for the same things often. A few items get most of the requests.

02Concept: What is it?

Caching means saving the result of slow work (a database query, a calculation, a file download) so we can reuse it. The saved copy is kept in something faster or closer to the user.

Without a cache and with a cache
Without a cache
๐Ÿ‘คUser
โ†’โ†“
๐Ÿ–ฅ๏ธApp
โ†’โ†“every time
๐Ÿ—„๏ธDatabaseslow, ~50 ms
With a cache
๐Ÿ‘คUser
โ†’โ†“
๐Ÿ–ฅ๏ธApp
โ†’โ†“hit: ~1 ms
โšกCache
โ‡ขโ‡ฃmiss only
๐Ÿ—„๏ธDatabase
With a cache, most requests stop at the fast box. Only a miss goes on to the database.

Three words you must know

โœ…Cache hit
The data is in the cache. Fast answer.
โŒCache miss
The data is not in the cache. We fetch it from the slow place and usually save a copy.
๐Ÿ“ŠHit ratio
hits รท (hits + misses). 90% means 9 out of 10 requests were answered by the cache.

Why does caching work? Locality of reference

  • Temporal locality: if you used something just now, you will probably use it again soon (a trending video).
  • Spatial locality: if you used one item, you will probably use items next to it (the next page of a list).
  • Skewed popularity: a small number of items get most of the traffic. Caching only the hot items already helps a lot.

03Real-Life Example

๐ŸตThe tea stall again, and the sugar jar
Our tea stall owner needs sugar for every cup. The sugar is in a big sack in the shop next door (5 minutes away). Walking there for every cup would be silly. So he keeps a small jar on his counter and fills it from the sack. Most cups use the jar. Only when the jar is empty does he walk to the sack.
Tea stall
Software system
Sugar jar on the counter
Cache (small, fast, close)
Big sack next door
Database (big, slow, far)
Jar has sugar: use it
Cache hit
Jar is empty: walk to the sack
Cache miss
Jar is small, so only enough for today
Cache has limited size, so we must choose what to keep
Sugar gets old or the price changes
Cached data can get stale
๐Ÿ“Another everyday example
Your phone remembers your favourite contacts and recent apps. It does not search the whole phone each time. That is a cache too.

04Why Do We Need It?

โšกFaster answers
Reading memory takes microseconds. A database or a far server takes milliseconds or more.
๐Ÿ—„๏ธLess load on the database
If 9 of 10 requests stop at the cache, the database sees only 1 of 10.
๐Ÿ’ฐLower cost
Fewer database servers and less network traffic are needed.
๐Ÿ“ˆHandles spikes
Popular items are answered from memory, even when thousands ask at once.
๐Ÿ›ŸSome safety
If the slow service is down for a moment, cached answers can still be served.
๐Ÿ˜€Happy users
Pages load faster, so users stay.
A cache trades a little memory for a lot of speed.

05Where Do We Use It?

A request passes many places. Each one can keep a copy.

Caches along the way
๐ŸŒBrowser cacheimages, scripts
โ†’โ†“
๐ŸŒCDNnear the user
โ†’โ†“
โš–๏ธReverse proxywhole pages
โ†’โ†“
๐Ÿ–ฅ๏ธApp memorysmall objects
โ†’โ†“
โšกRedis / Memcachedshared by all servers
โ†’โ†“
๐Ÿ—„๏ธDatabase cachebuffer pool
The closer the cache is to the user, the faster the answer. But it is also harder to keep correct.
WhereWhat it keepsExample
BrowserImages, scripts, styles, API answersYour browser skips downloading the logo again
CDNStatic files and sometimes pages, in many citiesA video chunk served from a nearby city
App memorySmall, hot objects inside one serverA list of countries loaded once
Distributed cacheData shared by many app serversUser sessions, product details in Redis
DatabaseRecently read pages and query plansThe database keeps hot rows in RAM
CPUTiny, super-fast copies of memoryL1, L2, L3 caches (you do not manage these)

06Types / Parts / How It Works

The speed ladder

Each step down is much slower but much bigger and cheaper. Caching is about staying high on this ladder. The numbers are rough and change with hardware.

Roughly how long each takes
CPU cache~1 ns
Main memory (RAM)~100 ns
SSD read~100 ยตs
Network in the same data centre~0.5 ms
Hard disk seek~10 ms
Network across the world~150 ms
Not drawn exactly to scale. Think โ€œeach step is about 10 to 1000 times slowerโ€.

The questions every cache must answer

  1. 1
    What do we cache?
    Hot, read-often, change-rarely data. Not data that changes every second.
  2. 2
    How do the cache and database stay in step?
    That is the job of a caching strategy (next topic).
  3. 3
    What do we remove when it is full?
    That is an eviction policy (LRU, LFU...).
  4. 4
    How do we remove old data?
    That is cache invalidation (TTL, purge, versions).
๐Ÿ’กGood things to cache
Product pages, user profiles, search results, config, results of slow calculations, API answers from other services.
VisualizerHits, misses and average speedChange the cache size and how popular the hot items are. Then send requests.
๐Ÿ‘คUser
โ†’โ†“
๐Ÿ–ฅ๏ธApp
โ†’โ†“
โšกCache0/4 items
โ‡ขโ‡ฃonly on a miss
๐Ÿ—„๏ธDatabase~50 ms
Items in the cache (newest first)
empty
Hits
0
Misses
0
Hit ratio
0%
Average time
-
without cache: 50 ms
Press โ€œRequest 1 itemโ€ to start. Popular items (k1 to k4) get asked for more often.

Times are illustrative (cache 1 ms, database 50 ms). Real numbers depend on your hardware and network.

07How to Use It / Steps / Implementation

The simplest way: read the cache first

  1. 1
    Make a key
    A name for the data, like user:42 or product:9:price.
  2. 2
    Look in the cache
    If the key is there, return it. That is a hit.
  3. 3
    On a miss, go to the database
    Read the data from the slow place.
  4. 4
    Save a copy in the cache
    Give it a time to live (TTL) so it does not stay for ever.
  5. 5
    Return the data
    The next request for the same key will be a hit.

Do the maths before you cache

Average time = hit ratio ร— cache time + (1 โˆ’ hit ratio) ร— database time.

Hit ratioAverage time (cache 1 ms, database 50 ms)Database requests per 1000
0%50 ms1000
50%25.5 ms500
90%5.9 ms100
99%1.5 ms10
๐Ÿ“Note
The numbers are illustrative. But the lesson is real: going from 90% to 99% cuts database load by 10 times.

Tips

  • Always set a TTL, even a long one. It is your safety net.
  • Measure your hit ratio. If it is low, the cache may be doing nothing.
  • Cache the final result when you can (the built page), not only the raw rows.

08Key Terms to Know

TermMeaning in easy words
CacheA fast, small store that keeps copies of data
Hit / MissThe data was / was not in the cache
Hit ratioShare of requests answered by the cache
TTLTime to live: how long a cached copy is allowed to live before it expires
EvictionRemoving an item to make room when the cache is full
InvalidationRemoving or updating a cached item because the real data changed
Stale dataA cached copy that no longer matches the real data
Cold cacheAn empty cache, so almost every request is a miss
Warm cacheA cache that already holds the popular items
KeyThe name used to find an item in the cache
Locality of referenceThe habit of programs to reuse the same or nearby data

09Pros, Cons and Trade-offs

โœ… Pros
  • Much faster answers
  • Less load on the database and backend
  • Lower cost at scale
  • Absorbs sudden spikes
  • Can hide short outages of the source
โš ๏ธ Cons
  • Data can be stale
  • Another thing to run, monitor and pay for
  • Hard to keep correct (invalidation)
  • Cold start: an empty cache is slow
  • Bugs can be hidden or confusing (โ€œbut the database is right!โ€)

Trade-offs

ChoiceWe gainWe lose
Bigger cacheMore hitsMore memory cost
Longer TTLMore hits, less database loadStaler data
Shorter TTLFresher dataMore misses
Cache closer to the userLower latencyHarder to invalidate
Cache the whole pageBiggest speed-upLess flexible, one change can ruin it all
โš ๏ธDo not cache everything
Data that changes every second, data that is private to each user (unless the key is per user), and data that is rarely asked for gain little from a cache.

10Common Problems and Mistakes

Common mistakes

  1. No TTL. Wrong data can live for ever.
  2. Caching data that is not hot. The cache fills with items nobody asks for again.
  3. Forgetting the cache can be wrong. Do not use a cached value for money or stock checks without care.
  4. Treating the cache as the source of truth. A cache can lose data any time. The database must hold the real copy.
  5. Not measuring. Without hit ratio and latency numbers you do not know if the cache helps.
  6. One cache key for different users. A page with the user name cached under a shared key shows it to everybody.

Problems when caches grow

๐ŸฅถCold start
After a restart the cache is empty and the database gets hit hard.
๐Ÿ˜Cache stampede
A hot item expires and many requests all go to the database together.
๐Ÿ•ณ๏ธCache penetration
Requests for items that do not exist always miss. Save a short โ€œnot foundโ€ answer (negative caching).
๐Ÿ”ฅHot key
One key gets so much traffic that one cache server cannot keep up.

11Real-World Examples

๐ŸŽฌVideo streaming
Popular videos are kept near viewers (a CDN) so playback starts fast.
๐Ÿ›’Shopping sites
Product pages and prices are cached. Stock is checked more carefully.
๐Ÿ“ธSocial media
Timelines and profile data are served from in-memory caches such as Redis or Memcached.
๐Ÿ”ŽSearch engines
Answers for very common searches can be reused.
๐ŸŒWebsites
Your browser keeps images and scripts, so the second visit is quicker.
๐ŸงฎDatabases
They keep recently used data pages in memory (a buffer pool).
๐Ÿ“Note
These are general ideas. The exact set-up inside each company is more complex.

12Related Topics to Read Next

Caching Strategiesโ†’

How the cache and the database work together on reads and writes.

Cache Eviction Policiesโ†’

What to remove when the cache is full.

Cache Invalidationโ†’

How to stop users seeing old data.

CDNโ†’

A cache spread across the world.

Distributed Cache Architectureโ†’

A cache shared by many servers.

Latency vs Throughput vs Bandwidthโ†’

The speed words behind why caches matter.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: a fast copy of data that is asked for often.
  • โœ”Hit / miss: in the cache / not in the cache. Watch the hit ratio.
  • โœ”Why it works: locality of reference and a few hot items.
  • โœ”Average time: hit ratio ร— cache time + miss ratio ร— database time.
  • โœ”Where: browser, CDN, proxy, app, Redis or Memcached, database.
  • โœ”Always: set a TTL, and keep the database as the source of truth.
  • โœ”Hard parts: strategies, eviction and invalidation (the next three topics).
  • โœ”One line: โ€œA cache trades a little memory for a lot of speed.โ€
โ† Previous
Task Queues, Workers and Scheduled Jobs
Next โ†’
Caching Strategies