Skip to the content

Lesson 234 of 296

Caching layers and CDNs

What you will learn

  • Every place a system can cache
  • What to cache, and for how long
  • Cache hit ratio and eviction policies
  • CDNs and how they work
  • Cache consistency problems
  • Caching mistakes
On this page

Caching layers

From the user to the database, each layer can cache:

LayerCachesExample
BrowserStatic files, API responsesCache-Control, ETags (Lesson 198)
CDNStatic files, images, video, even whole pages and API responsesCloudflare, CloudFront, Fastly
Reverse proxyResponsesnginx, Varnish
Application in-memoryHot small data per serverA Map with TTL, an LRU cache
Distributed cacheShared data for all serversRedis, Memcached (Lesson 205)
DatabaseIts own pages in memory, query plansPostgreSQL shared buffers

The closer to the user, the faster, and the harder to invalidate.

What to cache

  • Data read often, changed rarely: product catalogues, configuration, user profiles, rendered pages.
  • Expensive results: aggregates, recommendations, third-party API responses.
  • Not highly personal or rapidly changing data without care, and never in shared caches without user-specific keys.

Hit ratio and eviction

  • Hit ratio = hits ÷ (hits + misses). A cache with a 95% hit ratio sends only 5% of reads to the database. Monitor it.
  • Memory is limited, so caches evict entries:
PolicyRemoves
LRU (least recently used)The entry not used for the longest time. The most common default
LFU (least frequently used)The entry used least often
TTL expiryEntries older than their time-to-live
FIFOThe oldest inserted

Implementing an LRU cache is a classic coding question (Lesson 140 built one with a Map).

CDNs

A Content Delivery Network is a worldwide network of servers (edge locations, "points of presence") that cache content close to users. A user in Manchester gets your images from a server in the UK instead of your origin server in Virginia.

  1. The user's request goes to the nearest edge (through DNS or anycast routing).
  2. Hit: the edge returns its cached copy in milliseconds.
  3. Miss: the edge fetches from your origin (S3, your load balancer), caches it according to Cache-Control, and returns it.

Benefits: much lower latency, far less load and bandwidth on your origin, protection against traffic spikes and DDoS attacks, TLS close to users. CDNs can also run code at the edge (Cloudflare Workers, Lambda@Edge) for redirects, authentication checks or A/B tests.

Invalidation: prefer versioned file names (app.3f9c2a.js, Lesson 198) over purging; use purge APIs for content that must change at the same URL.

Consistency problems

ProblemDescriptionMitigation
Stale dataThe cache serves an old value after the database changedShort TTLs, delete on write, accept bounded staleness
Race between update and cache fillA reader caches an old value just after a writer deleted the keyShort TTLs; delete again after a delay ("delayed double delete"); versioned keys
StampedeA hot key expires and many requests hit the database (Lesson 205)Single-flight loading, jitter, early refresh
Hot keyOne key gets enormous traffic (a celebrity profile)Local in-memory copies on each server, key replicas
Cold startAfter a restart the cache is empty and the database is floodedWarm important keys; scale the database for misses

Mistakes

  • Caching without TTLs.
  • Caching errors or empty results for too long ("negative caching" is useful but needs short TTLs).
  • Forgetting tenant or user IDs in keys, leaking data between users.
  • Treating the cache as the only copy of data (caches can lose data at any time).

How to say it in an interview

"I cache at several layers: browser caching with Cache-Control, a CDN at the edge for static assets and public content, and Redis as a shared cache for hot data, usually with cache-aside and TTLs. I watch the hit ratio, rely on LRU eviction, and design keys with tenant and version. A CDN serves content from edge locations near users and only goes to the origin on a miss, which cuts latency and origin load; I use versioned file names instead of purging. I plan for stale data, stampedes, hot keys and cold starts, and never treat the cache as the source of truth."

Key words

WordMeaning
Hit ratioShare of reads served by the cache
EvictionRemoving entries when the cache is full
LRULeast recently used eviction
CDNA worldwide network of caching servers near users
Edge locationA CDN server close to users
OriginThe server a CDN fetches content from
Hot keyA key receiving a huge share of traffic

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.