10. Caching
Where this fits: Your database is the filing cabinet. But walking to the back office for every question is slow. Caching keeps the answers you need most often within arm's reach.
Learning goals
By the end of this lesson, you should be able to:
- Explain why caching exists using the fridge vs grocery store analogy
- Define cache hit, cache miss, and hit ratio
- Implement cache-aside (lazy loading) step by step
- Compare common caching patterns: cache-aside, read-through, write-through, write-behind
- Use TTL (time to live) wisely and explain why it is a safety net
- Describe cache invalidation strategies and why they are hard
- Recognize and mitigate cache stampede (thundering herd)
- Decide what to cache and what to leave in the database only
- Place caching correctly in an HLD diagram
The big picture
Databases are durable but relatively slow compared to in-memory stores. Under heavy read load, hitting the database for every request wastes CPU, increases latency, and costs money.
A cache is a fast storage layer โ usually RAM โ that holds copies of hot data close to your application.
Everyday analogy โ fridge vs grocery store:
| Grocery store (database) | Fridge (cache) | |
|---|---|---|
| Capacity | Huge โ everything exists | Small โ only what you use often |
| Speed | Drive there, walk aisles, checkout | Walk to kitchen, open door |
| Freshness | Always the "official" inventory | Might be yesterday's milk |
| Cost | Trip time + effort every time | Upfront space; restock occasionally |
| Disaster | Store fire = big problem (source of truth) | Power outage = inconvenience; store still has food |
Smart households keep eggs, butter, and coffee in the fridge (hot data). They don't refrigerate a single spice they use once a year (cold data).
Smart apps cache user sessions, hot product pages, and URL mappings โ not every archived log line.
Cache hit vs cache miss
Hit โ found in cache
GET cache["user:42"] โ { "name": "Alice", "avatar": "..." }
โ
HIT โ return immediately (~1 ms)
Miss โ not in cache
GET cache["user:42"] โ (nil)
โ MISS โ query database (~20โ50 ms)
SET cache["user:42"] = {...} EX 300
return to user
Hit ratio
Hit ratio = cache hits / (cache hits + cache misses)
| Hit ratio | Meaning |
|---|---|
| 95%+ | Excellent for read-heavy workloads |
| 80โ95% | Good; investigate miss patterns |
| < 80% | Cache may be too small, wrong keys, or TTL too aggressive |
Example: 10,000 requests/minute, 95% hit ratio โ only 500 DB queries/min instead of 10,000.
Where caches live in the stack
Client โ CDN (edge cache for static/media)
โ Load Balancer โ App Server โ Redis (app cache) โ Database
| Cache layer | What it caches | Typical TTL |
|---|---|---|
| Browser | Static assets, API responses (HTTP cache headers) | Minutes to days |
| CDN | Images, JS, CSS, video | Hours to weeks |
| App cache (Redis) | Sessions, profiles, computed results | Seconds to hours |
| Database buffer pool | Disk pages in RAM (automatic) | Managed by DB |
This lesson focuses on application caches (Redis, Memcached). CDN is covered in lesson 13.
Four caching patterns โ bird's-eye view
All four patterns answer two questions: Who loads the cache on a miss? and What happens on a write?
Memory cheat sheet โ one line each
| Pattern | Remember as | Mnemonic |
|---|---|---|
| Cache-aside | "App is the librarian" | Lazy โ app checks shelf, fetches from warehouse if missing |
| Read-through | "Cache is the librarian" | Auto-read โ app only asks cache; cache fetches on miss |
| Write-through | "Cache and DB update together" | Sync write โ cache always warm; slower writes |
| Write-behind | "Cache first, DB catches up" | Async write โ fast now; durability risk if cache dies |
| Need | Pick |
|---|---|
| General purpose / interviews | Cache-aside |
| Cache product owns reads | Read-through |
| Cache must stay warm after every write | Write-through |
| View counts, analytics buffers | Write-behind |
Interview default: Start with cache-aside unless you have a reason for the others. Pair with TTL + delete-on-write.
Pattern 1: Cache-aside (lazy loading) โ the default
The application manages the cache explicitly. This is the most common pattern in industry.
Mental model: You keep a personal notebook (cache). On read, you check the notebook first; if blank, you look up the official record (DB) and copy it in. On write, you update the official record first, then tear out the stale notebook page.
Read path
def get_user(user_id):
key = f"user:{user_id}"
# 1. Try cache
cached = redis.get(key)
if cached:
return json.loads(cached) # HIT
# 2. MISS โ load from DB
user = db.query("SELECT * FROM users WHERE id = ?", user_id)
# 3. Populate cache
redis.set(key, json.dumps(user), ex=300) # TTL 5 min
return user
Write path
def update_user(user_id, new_name):
# 1. Write to DB first (source of truth)
db.execute("UPDATE users SET name = ? WHERE id = ?", new_name, user_id)
# 2. Invalidate cache (delete stale copy)
redis.delete(f"user:{user_id}")
| Pros | Cons |
|---|---|
| App controls exactly what is cached | More app code than read-through |
| Cache can fail โ fallback to DB still works | Easy to forget invalidation on write |
| Works with any database | Two hops on every miss |
Pattern 2: Read-through
The cache layer loads from DB automatically on miss. The app only talks to the cache โ it never queries the DB directly on reads.
Mental model: You ask a librarian (cache). If the book isn't on the shelf, the librarian fetches it from the warehouse (DB) and shelves it for you โ you never visit the warehouse yourself.
Write path: Usually still cache-aside style โ app writes DB, then invalidates cache. Read-through only changes who loads on miss.
| Pros | Cons |
|---|---|
| Cleaner app read code | Cache provider must understand your schema |
| Consistent read entry point | Less flexible than hand-rolled cache-aside |
| Good fit for cache libraries / ORM plugins | Vendor lock-in to cache product |
When to use: Managed cache products (e.g. some CDN / edge KV layers) or frameworks that bundle read-through loaders.
Pattern 3: Write-through
On write, the app sends data to the cache first; the cache synchronously writes to the DB before acknowledging.
Mental model: You hand a form to a clerk (cache). The clerk files it in the official cabinet (DB) before handing you a receipt โ your copy and the official record always match.
| Pros | Cons |
|---|---|
| Cache always warm after write | Write latency = cache + DB round trip |
| No stale cache after write | Caches rows that may never be read |
| Strong consistency between cache and DB on write | Cache layer must support DB writes |
When to use: Read-heavy data that is also written often and must stay consistent in cache (session stores, config with read-through pairing).
Pattern 4: Write-behind (write-back)
Write to cache immediately; flush to DB asynchronously in batches or on a timer.
Mental model: You jot notes on a sticky pad (cache) instantly. A assistant copies them into the ledger (DB) every few minutes. If the pad burns before copying โ notes are lost.
| Pros | Cons |
|---|---|
| Very fast writes โ user doesn't wait for DB | Data loss if cache dies before flush |
| Batches DB writes โ fewer IOPS | Harder to debug; DB lags cache |
| Great for high-volume counters / analytics | Not for money, inventory, or auth |
When to use: View counts, click analytics, metrics buffers โ where approximate durability and speed beat strict sync.
All four patterns โ side-by-side
Pattern comparison table
| Pattern | Who loads on miss? | Write order | Cache after write | Durability | Start here? |
|---|---|---|---|---|---|
| Cache-aside | App | DB โ delete cache | Cold until next read | Strong | โ Yes |
| Read-through | Cache | DB โ delete cache | Cold until next read | Strong | If cache product supports it |
| Write-through | Cache or app | Cache โ DB sync | Warm | Strong | Read + write heavy |
| Write-behind | N/A for writes | Cache โ DB async | Warm | โ ๏ธ Weaker | Counters / analytics only |
Quick decision tree
TTL โ time to live
Every cached entry should usually expire.
SET user:42 "{...}" EX 300 # Redis: expire in 300 seconds
SET url:aZ9kQ2 "https://..." EX 86400 # 24 hours
Why TTL matters
| Reason | Explanation |
|---|---|
| Bounds staleness | Even if invalidation bugs exist, data refreshes eventually |
| Memory management | Old keys disappear instead of filling RAM forever |
| Changing access patterns | Yesterday's viral post cools off; evict automatically |
Everyday analogy: Milk in the fridge has a "best by" date. Even if you forget you bought it, you'll eventually throw it out and buy fresh โ TTL prevents serving month-old data forever.
Choosing TTL values
| Data type | Typical TTL | Why |
|---|---|---|
| User session | 24h โ 7d | Security vs convenience trade-off |
| Public user profile | 5 โ 15 min | Changes infrequently |
| URL shortener mapping | 1 โ 24h | Stable, high read volume |
| Product catalog page | 1 โ 5 min | Price/inventory changes |
| Leaderboard top 10 | 30 โ 60 sec | Competitive freshness |
| Config / feature flags | 30 โ 60 sec | Fast propagation needed |
Rule of thumb: Shorter TTL = fresher data, more DB load. Longer TTL = higher hit ratio, staler data.
Cache invalidation โ the hard part
When data changes in the DB, cached copies can be wrong.
"There are only two hard things in Computer Science: cache invalidation and naming things." โ Phil Karlton
Strategy 1: Delete on write (recommended baseline)
def update_user(user_id, data):
db.update(user_id, data)
redis.delete(f"user:{user_id}") # force reload on next read
Simple and effective. Next read is a miss โ fresh data from DB.
Strategy 2: Update cache on write
def update_user(user_id, data):
db.update(user_id, data)
redis.set(f"user:{user_id}", json.dumps(data), ex=300)
Avoids miss penalty but race conditions possible if two writes interleave.
Strategy 3: Short TTL + accept staleness
Don't invalidate; let TTL expire. Good for like counts, view counts where exact real-time value doesn't matter.
Strategy 4: Versioned keys
user:42:v7 โ current cached version
# On update, increment version โ user:42:v8
# Old v7 entries naturally die unused
Useful for CDN and immutable content patterns.
Invalidation failure modes
| Bug | Symptom | Fix |
|---|---|---|
| Forgot to invalidate on write | Users see old data until TTL | Add delete to write path; integration tests |
| Invalidated wrong key | Some users still stale | Key naming convention docs |
| Race: read during write | Brief inconsistency | TTL as safety net; or write-through |
| Cached null forever | "User not found" stuck after user created | Cache nulls with short TTL only |
Cache stampede (thundering herd)
Many requests miss the same key simultaneously โ all hammer the database at once.
Scenario: Popular key expires at T=0
T=0.000: Request 1 โ MISS โ query DB
T=0.001: Request 2 โ MISS โ query DB
T=0.002: Request 3 โ MISS โ query DB
...
T=0.050: Request 500 โ MISS โ query DB โ DB overwhelmed
Mitigations
| Technique | How it works |
|---|---|
| Single-flight / lock | Only one request loads DB; others wait for result |
| Probabilistic early refresh | Refresh cache before TTL expires (random jitter) |
| Soft TTL + hard TTL | Serve slightly stale data while one worker refreshes |
| Never expire hot keys synchronously | Background refresh job |
| Request coalescing | Middleware deduplicates in-flight identical queries |
# Single-flight (conceptual)
def get_with_lock(key):
if redis.set(f"lock:{key}", "1", nx=True, ex=10):
data = load_from_db(key)
redis.set(key, data, ex=300)
redis.delete(f"lock:{key}")
return data
else:
time.sleep(0.05) # wait for winner
return redis.get(key) or get_with_lock(key)
Everyday analogy: Black Friday doorbuster โ one person shouldn't hold the door while 500 people all rush the stockroom. One employee restocks the display (single-flight); shoppers wait in line for the refreshed shelf.
What to cache (and what not to)
Good cache candidates โ
| Data | Why |
|---|---|
| User sessions | Read every request; rarely changes mid-session |
| Public profiles | Same data served to many users |
| URL shortener mappings | Massive read:write ratio |
| Hot product pages | Catalog browsing is repetitive |
| Feed first page | Most users only scroll top N |
| Config / feature flags | Read constantly; changes rarely |
| Computed aggregates | "Top 10 posts today" โ expensive to compute |
| Auth permissions | Role checks on every API call |
Poor cache candidates โ
| Data | Why not |
|---|---|
| Bank balances (strong consistency) | Stale = financial error unless carefully designed |
| Rarely read rows | Wastes RAM; never pays back |
| Huge objects (10 MB JSON) | Evicts useful small keys; serialization cost |
| Unique one-off queries | No repeat benefit |
| Write-heavy counters (without strategy) | Invalidation every write โ no benefit |
Cache sizing intuition
If item = 2 KB, Redis has 4 GB RAM for this cache:
Max entries โ 4 GB / 2 KB โ 2 million keys
Use LRU eviction (Least Recently Used) โ when full, drop coldest keys. Hot data stays; long tail falls off.
Worked example: URL shortener redirect
Key: url:aZ9kQ2
Value: https://example.com/very/long/path?utm=...
TTL: 86400 (24 hours)
def redirect(short_code):
key = f"url:{short_code}"
long_url = redis.get(key)
if long_url:
return redirect_302(long_url) # ~1ms total
row = db.get_url(short_code)
if not row:
return 404
redis.set(key, row.long_url, ex=86400)
return redirect_302(row.long_url)
On URL update/delete: delete url:{short_code} from Redis.
Expected hit ratio: 99%+ for popular links โ one DB read per link per day at most.
Worked example: E-commerce product page
Key: product:8812:page
Value: { name, price, images, inventory_status, ... }
TTL: 120 seconds
- Read-heavy: thousands of views per minute during sale
- Inventory changes: invalidate on purchase or use short TTL
- Stampede risk: use single-flight on popular SKUs during flash sales
Caching + replication together
- Reads: cache โ replica โ primary (fallback chain)
- Writes: primary + cache invalidation
- After write: read-your-writes may require skipping replica briefly
Common mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| Cache as source of truth | Data loss on eviction | DB commits first always |
| No TTL anywhere | Stale forever on invalidation bugs | Always set TTL |
| Caching everything | RAM full, low hit ratio | Cache hot paths only |
| Cache null permanently | New records invisible | Short TTL for negative cache |
| Ignoring stampede on hot keys | DB outage during expiry | Single-flight, early refresh |
| Same TTL for all data types | Wrong freshness/cost trade-off | Tune per data class |
| Not monitoring hit ratio | Silent performance regression | Dashboard: hits, misses, latency |
Monitoring what matters
| Metric | Healthy signal |
|---|---|
| Hit ratio | Stable or improving |
| Cache latency p99 | < 5 ms |
| Eviction rate | Not constantly at max memory |
| DB QPS after cache | Drops when cache added |
| Miss latency spike | Correlates with stampede? |
Interview phrases that sound solid
- "We use cache-aside with Redis: 5-minute TTL on profiles, delete-on-write invalidation."
- "URL redirects are 99%+ cache hits โ Postgres only on miss."
- "Flash sale SKU uses single-flight to prevent stampede when cache expires."
- "Sessions live in Redis with 24h TTL; DB stores only user account data."
Check your understanding
Questions
- Explain caching using the fridge vs grocery store analogy.
- What is the difference between a cache hit and a cache miss?
- Walk through cache-aside on both read and write paths.
- Why use TTL even when you invalidate cache on every write?
- What causes a cache stampede, and name two mitigations.
- Should you cache a user's bank balance? Why or why not?
- Compare write-through vs write-behind durability.
- For each pattern, who loads the cache on a read miss โ the app or the cache?
- A URL shortener gets 1M redirects/day for 10k unique URLs. Roughly how many DB reads/day if TTL is 24h and cache never evicts?
Answers
Click to reveal answers
-
Database = grocery store โ complete inventory, slow to access every time. Cache = fridge โ small, fast, holds frequently used items; may not have the absolute latest version of everything.
-
Hit: data found in cache โ fast return. Miss: not in cache โ must load from DB (slow), then usually populate cache for next time.
-
Read: check cache โ on miss, read DB โ set cache with TTL โ return. Write: update DB first โ delete (or update) cache key so next read gets fresh data.
-
TTL is a safety net against missed invalidations, bugs, race conditions, and manual errors. Data self-heals when TTL expires.
-
Stampede: many concurrent requests miss the same expired key and all query DB simultaneously. Mitigations: single-flight lock, probabilistic early refresh, serve stale while refreshing.
-
Generally no (without special design) โ financial data requires strong consistency; stale cache could show wrong balance. If cached, use very short TTL + invalidation + read-from-primary after transactions.
-
Write-through: write goes to cache and DB sync โ durable immediately. Write-behind: write to cache, async to DB โ faster but data can be lost if cache fails before flush.
-
Cache-aside & read-through (typical): cache-aside โ app loads DB on miss; read-through โ cache loads DB on miss. Write-through / write-behind don't change the miss-loader on reads โ write-through often pairs with read-through so cache serves reads.
-
Roughly 10,000 DB reads/day โ one miss per unique URL per 24h TTL (first request of the day per URL), then all subsequent requests hit cache. (Ignores evictions and new URLs.)
Quick reference card
Hit โ found in cache (fast)
Miss โ not in cache โ DB โ populate
CACHE-ASIDE โ App loads on miss; DB write + cache DELETE
READ-THROUGH โ Cache loads on miss; app never reads DB
WRITE-THROUGH โ Write cache โ sync DB; cache stays warm
WRITE-BEHIND โ Write cache โ async DB; fast, loss risk
TTL โ auto-expire; safety net for bugs
Invalidate โ delete/update cache on DB write
Stampede โ many misses at once โ lock / early refresh
Cache โ hot, read-heavy, tolerates slight staleness
Don't cache โ cold data, huge blobs, strong consistency needs
Next: 11. CAP & Consistency โ when "fast" and "correct everywhere" pull in opposite directions.