Caching strategies & CDNs
Pick cache-aside, write-through or write-back and handle invalidation and stampedes.
By Invicly Tech, , in System Design Deep Dive. About 11 minutes to read.
In short
A cache stores hot data in fast memory so repeated reads skip the slower database. The hard parts are choosing a write strategy, keeping data fresh with TTLs and invalidation, and preventing stampedes when hot keys expire.
Think of it like this: Keeping your most-used tools on the desk instead of walking to the shed.
Explained simply
A cache is a small, fast store that keeps copies of things you need often. Reading from memory takes microseconds, a database query takes milliseconds, and fetching from the other side of the world takes hundreds of milliseconds. A cache keeps answers close and quick.
Think of your fridge. You do not drive to the shop every time you want milk. You keep some at home, and when it goes off you buy fresh. A cache is the fridge, the database is the shop, and the use-by date is the TTL.
Caches exist at many layers: your browser, a CDN near your city, the app server's memory, a shared Redis server and even inside the database. Each layer saves a trip to the slower layer behind it.
The catch is that copies can go out of date. A famous joke says the two hardest things in computing are cache invalidation and naming things. So for every cache, decide how stale is acceptable: one second, one minute or one day.
Press Play on a diagram to walk through it one step at a time.
- 1Read from cache
App checks Redis for the key first
- 2Miss: query database
Fetch the value from the source of truth
- 3Populate cache
Store the value with a TTL
- 4Write to database
Updates go to the database first
- 5Invalidate key
Delete cached entry so next read refreshes
- Back to step 1
- App manages cache explicitly
- Only requested data cached
- First read is a miss
- Most common default
- Write cache and DB together
- Cache always fresh
- Slower writes
- Caches data never read
- Write cache, flush DB later
- Very fast writes
- Data loss risk on crash
- Good for counters, metrics
- 1Browser cache
0 ms: no network at all
- 2CDN edge
~10–30 ms: a server in the user's region
- 3In-process app cache
Microseconds, but per server
- 4Shared Redis
~0.5–1 ms over the data-centre network
- 5Database buffer pool
Pages already in database memory
- 6Disk
The slowest layer and the source of truth
- Reader to Cache: GET user:7 → miss1GET user:7 → miss
- Reader to Database: Read user:7 (old value)2Read user:7 (old value)
- Writer to Database: UPDATE user:73UPDATE user:7
- Writer to Cache: DELETE user:74DELETE user:7
- Reader to Cache: SET user:7 = old value (now stale)5SET user:7 = old value (now stale)
In depth
Hit ratio is the number that matters
The database only sees cache misses. At a 90 percent hit ratio it receives 10 percent of reads. At 99 percent it receives 1 percent. So going from 90 to 99 percent cuts database load by ten times, even though it sounds like a small change.
Measure hits and misses for every cache. A low hit ratio usually has one of three causes: keys that are too specific (each user's slightly different query cached separately), TTLs that are too short, or a cache too small for the hot data so items are pushed out before they are reused.
A race that leaves stale data
Cache-aside has a subtle race. A reader misses the cache and reads the old value from the database. Before it stores that value, a writer updates the database and deletes the cache key. Then the slow reader finally writes the old value into the cache. The cache is now wrong until the TTL runs out.
This is rare but real at high traffic. Defences: always set a TTL as a safety net, delete the key a second time shortly after the write (a delayed double delete), or update the cache from the database's change stream so writes are applied in order.
Stampedes: beyond simple locks
When a hot key expires, thousands of requests can miss at once and hammer the database. Besides letting one request rebuild while others wait, two gentler techniques exist.
Stale-while-revalidate keeps serving the old value for a short grace period while one background request fetches a fresh one, so nobody waits. Probabilistic early refresh gives each read a small and growing chance to refresh the key just before it expires, so one lucky request renews it early. Also plan for a cold start: after a cache restart, every key is a miss, so warm the most popular keys before sending full traffic.
- One request rebuilds the key
- Others wait for it
- Simple, but adds waiting
- Serve the old value for a grace period
- One background refresh
- Nobody waits
- Growing chance to refresh near expiry
- One lucky request renews early
- Key never expires under load
HTTP caching and CDNs
Browsers and CDNs follow the Cache-Control header. For files whose name includes a content hash, like app.3f9a2c.js, send "public, max-age=31536000, immutable": the file can be cached for a year because a new version gets a new name. For HTML, send "no-cache", which means store it but check with the server each time. For personal data, send "private, no-store" so shared caches never keep it.
Revalidation is cheap with ETags. The server tags each response, the browser sends If-None-Match with that tag, and the server replies 304 Not Modified with no body if nothing changed.
- Hashed files (app.3f9a2c.js)
- public, max-age=31536000, immutable
- HTML pages
- no-cache
- Stored, but checked every time
- Personal data
- private, no-store
- Revalidation
- ETag + If-None-Match
- 304 Not Modified, no body
When memory fills up
A cache has limited memory, so it must evict something. LRU drops the item unused for the longest. LFU drops the item used least often, which suits steady favourites. In Redis, set maxmemory and a policy such as allkeys-lru for a pure cache. The default noeviction makes writes fail when memory is full, which surprises many teams.
Also cache misses on purpose. If many requests ask for an ID that does not exist, each one goes to the database. Caching "not found" for a short time, say 30 seconds, stops that, including from attackers probing random IDs.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Compare cache-aside, write-through and write-back~45m
- 2Choose TTLs and invalidation~45m
- 3Prevent cache stampedes~45m
- 4Use a CDN for static content~45m
Key points
- Cache data that is read often and changes rarely.
- TTLs bound staleness even when invalidation fails.
- Prevent stampedes with request coalescing, locks or jittered TTLs.
- CDNs cache static assets at the edge, close to users.
- Eviction policies like LRU decide what to drop when memory fills.
Key terms
Tap a card to flip it. 0/5 known
Examples
def get_user(user_id):
key = f"user:{user_id}"
cached = redis.get(key)
if cached:
return json.loads(cached)
user = db.query("SELECT * FROM users WHERE id=%s", user_id)
ttl = 3600 + random.randint(0, 300) # jitter avoids stampedes
redis.set(key, json.dumps(user), ex=ttl)
return user
def update_user(user_id, fields):
db.update("users", user_id, fields)
redis.delete(f"user:{user_id}") # invalidate after writeCache-aside with jittered TTL and delete-on-write.
Cache headers for a typical web app
Step 1: built JavaScript and CSS have a content hash in their names, so they are cached for a year and never revalidated. Step 2: index.html must always point at the latest files, so it is revalidated on each visit using its ETag. Step 3: a public product API is cached at the CDN for 60 seconds (s-maxage) but not in browsers (max-age=0). Step 4: the logged-in user's profile must never sit in a shared cache.
/assets/app.3f9a2c.js Cache-Control: public, max-age=31536000, immutable
/index.html Cache-Control: no-cache (revalidate via ETag)
/api/products/42 Cache-Control: public, s-maxage=60, max-age=0
/api/me Cache-Control: private, no-storeLetting only one request rebuild a hot key
On a miss, each caller tries to take a short lock with SET NX (set only if not exists) and a 10-second expiry. The winner loads from the database, fills the cache and releases the lock. Everyone else sleeps for 50 ms and tries again, by which time the value is usually cached. The lock's expiry means a crashed winner cannot block others forever. In production, also cap the number of retries.
def get_product(pid):
key = f"product:{pid}"
val = r.get(key)
if val is not None:
return json.loads(val)
# only one caller rebuilds; the rest wait briefly and retry
if r.set(f"lock:{key}", "1", nx=True, ex=10):
try:
data = load_product_from_db(pid)
r.set(key, json.dumps(data), ex=300)
return data
finally:
r.delete(f"lock:{key}")
time.sleep(0.05)
return get_product(pid)Quick reference
- Hit ratio 90% → DB sees 10% of reads; 99% → just 1%
- Hashed file names + Cache-Control: public, max-age=31536000, immutable
- Personal data: Cache-Control: private, no-store
- Stale-while-revalidate: serve the old value while one request refreshes it
- Redis as a pure cache: set maxmemory and maxmemory-policy allkeys-lru
- Cache "not found" results for ~30 s to stop repeated misses
- Always set a TTL, even when you also invalidate on write
Common mistakes
- Updating the cache before the database, leaving stale data on failure.
- Giving every key the same TTL so they all expire together.
- Caching personalised responses at a shared CDN by mistake.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
A service gets 50,000 reads per second. How many reach the database at 95 percent and at 99 percent hit ratio? What does this tell you?
- Exercise 2medium
Choose Cache-Control headers for: a logo with a hash in its file name, the homepage HTML, public search results that may be 30 seconds old, and a user's order history.
- Exercise 3hard
During a flash sale, one product page gets 200,000 requests per second, all for the same cache key. Design the caching so neither Redis nor the database falls over, while stock counts stay roughly correct.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use Redis or Memcached?
- Both are fast in-memory caches. Redis is the common default because it also has data structures, persistence and replication; Memcached is simpler and very efficient for plain key-value caching.
- Should I cache everything?
- No. Cache data that is read often and can be slightly stale. Caching rarely read or constantly changing data wastes memory and adds bugs without much benefit.
- What TTL should I choose?
- Ask how stale the data can be without hurting users. Product details might live 5 minutes, a news homepage 30 seconds, and a stock price a second or less.