Skip to main content

Module 4: Caching & CDN

Cache Invalidation

TTL, explicit purge, versioned keys, and stampede control — strategies for keeping caches fresh without melting the database.

Stale cache entries create subtle bugs. Invalidation policy is part of the design, not an afterthought — especially when Redis, local caches, and a CDN all hold copies of the truth.

What you will learn

  • Compare TTL, explicit invalidation, and versioned keys
  • Walk a correct write → invalidate path for cache-aside
  • Explain stampede / thundering-herd mitigations
  • Handle multi-layer and CDN purge realities
  • Pick a strategy by data type (feeds vs profile vs static assets)
Three steps: write the database, delete the cache key, then the next read refills the cache.
Delete on write. The next read misses and copies the new row back into cache.

Why invalidation is hard

  • Reads are easy to speed up. Making every copy forget the old value — correctly, quickly, under failure — is the hard part.
  • Multiple layers may store the same logical object
  • Writes race with reads that repopulate a key you just deleted
  • Partial failures: DB write succeeds, purge fails (or the reverse)
  • CDN and browser caches add global delay and extra purge APIs
  • Wrong purge ⇒ silent stale UX; aggressive purge ⇒ stampede on origin

Strategy 1 — TTL expiry

  • Every entry dies by the clock. Simple ops, bounded staleness, no perfect freshness.
  • Set TTL when you populate; miss after expiry reloads from source
  • Pros: easy, self-healing if you forget a purge path
  • Cons: users can see old data until TTL ends; hot keys stampede on expiry
  • Best for: feeds, counters, recommendations, soft-state metadata
  • Tune TTL from the product staleness budget, not a random round number

Strategy 2 — Explicit invalidate on write

  • On write, update the system of record, then delete (or update) every cached copy.
  • Cache-aside classic: write DB → DEL key (prefer delete over set to avoid races)
  • Must list every key derived from that write (profile, permissions, rendered cards)
  • Pros: fresher reads after the next miss
  • Cons: missed key = stale forever until TTL; more code paths to keep correct
  • Make purge idempotent — deleting a missing key should be fine

Strategy 3 — Versioned keys

  • Readers look up a version; writers bump the version so old keys become unreachable.
  • Example: store ver=5; readers use user:42:profile:v5
  • Bump version on write; old v4 entries expire naturally or via TTL
  • Pros: avoids some delete races; great for fingerprinted static assets (content hash in URL)
  • Cons: need a place to store/read the current version; orphaned versions use memory until TTL
  • CDN-friendly: new URL ⇒ cache miss without an urgent purge of the old object

Delete vs update on write

  • After a DB write, you can SET the new value in cache or DEL and let the next read refill.
  • DEL + refill — simpler consistency story; next read pays a miss
  • SET new value — warm cache, but concurrent writers can overwrite with stale compute
  • Race: read loads old DB row while write commits, then write’s DEL happens before/after badly ordered SET
  • Common advice: invalidate (delete) rather than write-through from every code path unless carefully locked
  • Document the chosen rule so every service follows it

Stampede after invalidation/expiry

  • Freshness events (TTL end or mass DEL) can turn into a thundering herd on the DB.
  • Many requests miss the same hot key at once and rebuild together
  • Mitigations: single-flight / mutex per key, only one rebuild wins
  • Soft TTL: serve stale while a background refresh runs
  • Probabilistic early expiration to jitter herd timing
  • Request coalescing at the edge or app tier

Multi-layer invalidation

  • If Redis, local JVM caches, and CDN all hold copies, one DEL is not enough.
  • Map every layer that can answer the read
  • Invalidate inward-out or publish an event each layer listens to
  • Local in-process caches need short TTL or pub/sub busting across instances
  • Forgotten layer = “I purged Redis but users still see old HTML”
  • Prefer fewer layers for strongly consistent objects

CDN and browser purge realities

  • Edge caches are powerful and slower to herd-control than a single Redis cluster.
  • Purge APIs may be eventually consistent across PoPs
  • Fingerprinted filenames (app.abc123.js) beat emergency purge for static assets
  • Cache-Control / Surrogate-Control define who may store responses
  • Authenticated or personalized responses often must be private/no-store at CDN
  • Plan a staleness window if purge is async

Picking a policy by data type

  • One product should use more than one invalidation style.
  • Static assets — versioned URLs + long TTL
  • User profile / settings — explicit invalidate on write (+ modest TTL safety net)
  • Feeds / counters — TTL with stampede protection
  • Permissions — short TTL or explicit bust on role change; never serve forever-stale authz
  • Money / inventory — often skip cache or use strongly coordinated reads

Common failure modes

  • Name these before the interviewer asks what goes wrong.
  • Forgot a derived key → users see old data indefinitely
  • Purge fails after DB commit → stale until TTL; need retry/outbox
  • Stampede after expiry → DB overload
  • CDN purge delay → regional inconsistency
  • Invalidating too broadly → unnecessary origin load

Interview framing

  • Use this order when the write path touches cached reads.
  • List layers that hold the object
  • Pick TTL vs explicit vs versioned (or a mix) per data type
  • Narrate write → commit → invalidate → next read miss
  • Add stampede defense for hot keys
  • State the maximum staleness you accept

Quick revision checklist

  • Write the write-path invalidation steps aloud.
  • Mention idempotent purge APIs.
  • Prefer DEL over blind SET after writes unless races are handled.
  • Pair short TTLs with stampede protection.
  • Account for every cache layer, including CDN.
  • Match strategy to data: TTL vs explicit vs versioned.

FAQs

Why is invalidation hard?

Because multiple layers, race conditions, and partial failures make “delete the old value everywhere” surprisingly tricky.

Should I delete or update the cache on write?

Deleting is usually safer with cache-aside: the next read refills from the DB. Updating can leave subtle races if a concurrent reader writes back stale data.

Is TTL enough by itself?

For soft-state data, yes. For user-edited profiles or permissions, pair TTL with explicit invalidation so changes show up before the clock runs out.

How do versioned keys help?

Readers use a key that includes a version or content hash. After a bump, they naturally miss old entries without needing a perfect broadcast delete.

What if invalidate fails after the DB write?

Retry the purge, use an outbox/event to bust caches asynchronously, and keep a TTL safety net so staleness cannot last forever.

How is CDN invalidation different from Redis DEL?

Redis delete in your cluster is typically immediate. CDN purge can take time across PoPs; versioned asset URLs often beat relying on purge alone.

Practice

Learner’s Task

  • Practice out loud for 8–10 minutes. Design invalidation for one write that feeds several reads.
  1. Pick an update (edit profile name) and list every cache key/layer that might store it (Redis, local, CDN).
  2. Choose policies: explicit vs TTL vs versioned for each layer — justify staleness budgets.
  3. Narrate the write path: DB commit → purges → what the next GET does on miss.
  4. Add one stampede defense if a hot key is deleted at peak traffic.
  5. Write a 4-sentence closing: policy mix, race you avoided, multi-layer note, and max staleness.