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:
| Layer | Caches | Example |
|---|---|---|
| Browser | Static files, API responses | Cache-Control, ETags (Lesson 198) |
| CDN | Static files, images, video, even whole pages and API responses | Cloudflare, CloudFront, Fastly |
| Reverse proxy | Responses | nginx, Varnish |
| Application in-memory | Hot small data per server | A Map with TTL, an LRU cache |
| Distributed cache | Shared data for all servers | Redis, Memcached (Lesson 205) |
| Database | Its own pages in memory, query plans | PostgreSQL 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:
| Policy | Removes |
|---|---|
| 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 expiry | Entries older than their time-to-live |
| FIFO | The 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.
- The user's request goes to the nearest edge (through DNS or anycast routing).
- Hit: the edge returns its cached copy in milliseconds.
- 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
| Problem | Description | Mitigation |
|---|---|---|
| Stale data | The cache serves an old value after the database changed | Short TTLs, delete on write, accept bounded staleness |
| Race between update and cache fill | A reader caches an old value just after a writer deleted the key | Short TTLs; delete again after a delay ("delayed double delete"); versioned keys |
| Stampede | A hot key expires and many requests hit the database (Lesson 205) | Single-flight loading, jitter, early refresh |
| Hot key | One key gets enormous traffic (a celebrity profile) | Local in-memory copies on each server, key replicas |
| Cold start | After a restart the cache is empty and the database is flooded | Warm 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
| Word | Meaning |
|---|---|
| Hit ratio | Share of reads served by the cache |
| Eviction | Removing entries when the cache is full |
| LRU | Least recently used eviction |
| CDN | A worldwide network of caching servers near users |
| Edge location | A CDN server close to users |
| Origin | The server a CDN fetches content from |
| Hot key | A key receiving a huge share of traffic |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.