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)
CapacityHuge โ€” everything existsSmall โ€” only what you use often
SpeedDrive there, walk aisles, checkoutWalk to kitchen, open door
FreshnessAlways the "official" inventoryMight be yesterday's milk
CostTrip time + effort every timeUpfront space; restock occasionally
DisasterStore 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 ratioMeaning
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 layerWhat it cachesTypical TTL
BrowserStatic assets, API responses (HTTP cache headers)Minutes to days
CDNImages, JS, CSS, videoHours to weeks
App cache (Redis)Sessions, profiles, computed resultsSeconds to hours
Database buffer poolDisk 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

PatternRemember asMnemonic
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
NeedPick
General purpose / interviewsCache-aside
Cache product owns readsRead-through
Cache must stay warm after every writeWrite-through
View counts, analytics buffersWrite-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}")
ProsCons
App controls exactly what is cachedMore app code than read-through
Cache can fail โ€” fallback to DB still worksEasy to forget invalidation on write
Works with any databaseTwo 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.

ProsCons
Cleaner app read codeCache provider must understand your schema
Consistent read entry pointLess flexible than hand-rolled cache-aside
Good fit for cache libraries / ORM pluginsVendor 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.

ProsCons
Cache always warm after writeWrite latency = cache + DB round trip
No stale cache after writeCaches rows that may never be read
Strong consistency between cache and DB on writeCache 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.

ProsCons
Very fast writes โ€” user doesn't wait for DBData loss if cache dies before flush
Batches DB writes โ€” fewer IOPSHarder to debug; DB lags cache
Great for high-volume counters / analyticsNot 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

PatternWho loads on miss?Write orderCache after writeDurabilityStart here?
Cache-asideAppDB โ†’ delete cacheCold until next readStrongโœ… Yes
Read-throughCacheDB โ†’ delete cacheCold until next readStrongIf cache product supports it
Write-throughCache or appCache โ†’ DB syncWarmStrongRead + write heavy
Write-behindN/A for writesCache โ†’ DB asyncWarmโš ๏ธ WeakerCounters / 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

ReasonExplanation
Bounds stalenessEven if invalidation bugs exist, data refreshes eventually
Memory managementOld keys disappear instead of filling RAM forever
Changing access patternsYesterday'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 typeTypical TTLWhy
User session24h โ€“ 7dSecurity vs convenience trade-off
Public user profile5 โ€“ 15 minChanges infrequently
URL shortener mapping1 โ€“ 24hStable, high read volume
Product catalog page1 โ€“ 5 minPrice/inventory changes
Leaderboard top 1030 โ€“ 60 secCompetitive freshness
Config / feature flags30 โ€“ 60 secFast 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

BugSymptomFix
Forgot to invalidate on writeUsers see old data until TTLAdd delete to write path; integration tests
Invalidated wrong keySome users still staleKey naming convention docs
Race: read during writeBrief inconsistencyTTL as safety net; or write-through
Cached null forever"User not found" stuck after user createdCache 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

TechniqueHow it works
Single-flight / lockOnly one request loads DB; others wait for result
Probabilistic early refreshRefresh cache before TTL expires (random jitter)
Soft TTL + hard TTLServe slightly stale data while one worker refreshes
Never expire hot keys synchronouslyBackground refresh job
Request coalescingMiddleware 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 โœ…

DataWhy
User sessionsRead every request; rarely changes mid-session
Public profilesSame data served to many users
URL shortener mappingsMassive read:write ratio
Hot product pagesCatalog browsing is repetitive
Feed first pageMost users only scroll top N
Config / feature flagsRead constantly; changes rarely
Computed aggregates"Top 10 posts today" โ€” expensive to compute
Auth permissionsRole checks on every API call

Poor cache candidates โŒ

DataWhy not
Bank balances (strong consistency)Stale = financial error unless carefully designed
Rarely read rowsWastes RAM; never pays back
Huge objects (10 MB JSON)Evicts useful small keys; serialization cost
Unique one-off queriesNo 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

MistakeConsequenceFix
Cache as source of truthData loss on evictionDB commits first always
No TTL anywhereStale forever on invalidation bugsAlways set TTL
Caching everythingRAM full, low hit ratioCache hot paths only
Cache null permanentlyNew records invisibleShort TTL for negative cache
Ignoring stampede on hot keysDB outage during expirySingle-flight, early refresh
Same TTL for all data typesWrong freshness/cost trade-offTune per data class
Not monitoring hit ratioSilent performance regressionDashboard: hits, misses, latency

Monitoring what matters

MetricHealthy signal
Hit ratioStable or improving
Cache latency p99< 5 ms
Eviction rateNot constantly at max memory
DB QPS after cacheDrops when cache added
Miss latency spikeCorrelates 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

  1. Explain caching using the fridge vs grocery store analogy.
  2. What is the difference between a cache hit and a cache miss?
  3. Walk through cache-aside on both read and write paths.
  4. Why use TTL even when you invalidate cache on every write?
  5. What causes a cache stampede, and name two mitigations.
  6. Should you cache a user's bank balance? Why or why not?
  7. Compare write-through vs write-behind durability.
  8. For each pattern, who loads the cache on a read miss โ€” the app or the cache?
  9. 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
  1. 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.

  2. Hit: data found in cache โ†’ fast return. Miss: not in cache โ†’ must load from DB (slow), then usually populate cache for next time.

  3. 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.

  4. TTL is a safety net against missed invalidations, bugs, race conditions, and manual errors. Data self-heals when TTL expires.

  5. 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.

  6. 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.

  7. 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.

  8. 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.

  9. 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.