Caching (Redis & CDN)
System Design · Scaling & Data · Intermediate · 14 min
Keep popular answers close by so you don't recompute them.
A small desk next to a giant library. Books you use go on the desk, the one you just touched slides to the right end, and when the desk is full the book at the far left (untouched the longest) goes back to the shelf. Sticky notes on each book say when it is too old to trust.
The idea in everyday words
Your fridge is a cache; the supermarket is the database. Milk you use daily lives in the fridge (fast). When the fridge is full, you throw out what you haven't used in the longest time. That's the LRU (Least Recently Used) rule.
Where caches live
- Browser cache – images you already downloaded
- CDN (CloudFront, Cloudflare, Akamai) – copies of static files in cities near users
- App cache (Redis, Memcached) – results of slow DB queries
- DB cache – the database's own memory
Cache-aside pattern (most common)
- Check the cache.
- Hit → return it (~1 ms).
- Miss → read the DB (~50 ms), save into cache with a TTL (expiry), return.
Hard part: invalidation: when data changes, delete or update the cached copy.
Eviction policies
LRU: drop the least recently used key. LFU: drop the least frequently used key. TTL: drop after X seconds.
In LRU, every use counts: a get, a new put, and also a put that overwrites an existing key all make that key the most recent.
Write strategies and stampedes
Cache-aside (this lesson) is the default, but there are other ways to keep the cache and the database in step:
| Strategy | How | Good | Bad |
|---|---|---|---|
| Cache-aside | App reads cache, fills it on a miss; on write, update DB and delete the key | Simple, cache holds only hot data | First read after a change is slow |
| Write-through | Every write goes to cache and DB together | Cache is always fresh | Writes are slower; cache fills with data nobody reads |
| Write-behind | Write to cache, flush to DB later | Very fast writes | Risk of losing data if the cache dies |
Stampede (thundering herd): a hot key expires and 1,000 servers miss at the same moment, all hitting the database. Fixes: a short lock so only one request refills the key, refreshing popular keys a little before they expire, and adding random jitter to TTLs so keys don't all expire together.
Step by step
- GET /user/42:
Check Redis: key user:42 → MISS.
- Read DB:
Query Postgres (50ms) → got Ana.
- Fill cache:
SET user:42 'Ana' EX 300 (5 min TTL).
- Next request:
Redis HIT → 1ms. DB is resting.
Code example
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cap, self.data = capacity, OrderedDict()
def get(self, key):
if key not in self.data:
return -1
self.data.move_to_end(key) # mark as recently used
return self.data[key]
def put(self, key, value):
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.cap:
self.data.popitem(last=False) # evict oldest
c = LRUCache(2)
c.put("a", 1); c.put("b", 2); c.get("a"); c.put("c", 3)
print(list(c.data.keys())) # b was evictedInterview tips
Cloud names: AWS ElastiCache (Valkey, Redis OSS or Memcached) and DAX for DynamoDB, GCP Memorystore, Azure Managed Redis; open source Redis/Valkey, Memcached.
Mention cache stampede protection (locks or early refresh).
'Design an LRU cache' is a classic coding question: hash map + doubly linked list.
Challenge: Simulate an LRU Cache
Given capacity and a list of operations, return the results of every get.
["put", key, value]stores a value["get", key]returns the value or-1
When over capacity, evict the least recently used key. Gets and puts both count as a 'use', including a put that overwrites a key that is already there. A get for a missing key returns -1 and changes nothing.
Example: lru(2, [["put",1,1],["put",2,2],["get",1],["put",3,3],["get",2]]) → [1, -1]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- LRU Cache (Medium)
- LFU Cache (Hard)
- Time Based Key-Value Store (Medium)
- AWS: Caching best practices
More in Scaling & Data
- Scaling & Load Balancers
- Databases: SQL, NoSQL, Sharding
- Choosing a Database on AWS
- DynamoDB Data Modeling
- Consistent Hashing
Previous: Scaling & Load Balancers · Next: Databases: SQL, NoSQL, Sharding