CDN & Edge Caching
📖 Concept
A CDN is a globally distributed network of servers that caches content close to users, reducing latency from 200-500ms to 10-50ms.
How CDNs Work
- User requests
cdn.example.com/image.jpg - DNS routes to nearest edge server
- Cache HIT: Serve from edge (~10ms)
- Cache MISS: Fetch from origin → cache → serve
What to Cache on CDN
| Content Type | Cache? | TTL |
|---|---|---|
| Static assets (JS, CSS) | Always | 1 year (versioned) |
| Images/Videos | Always | 1 month+ |
| HTML pages (static) | Usually | 5 min - 1 hour |
| API responses | Sometimes | 10s - 5 min |
| Personalized content | Never | N/A |
CDN Invalidation
- TTL expiration: Automatic
- Cache purge: Immediate (API call)
- Versioned URLs:
bundle.abc123.js— new hash = new URL = instant update - stale-while-revalidate: Serve stale, refresh in background
Edge Computing
Modern CDNs run code at the edge (Cloudflare Workers, Lambda@Edge): A/B testing, auth, image optimization, geo-routing — all without hitting origin.
Interview tip: Mention CDN whenever the system serves static content or has global users. Easiest latency win.
💻 Code Example
1// ============================================2// CDN & Edge Caching — Implementation3// ============================================45const express = require('express');6const app = express();78// Static assets: immutable, cache forever9app.get('/static/:hash/:file', (req, res) => {10 res.set('Cache-Control', 'public, max-age=31536000, immutable');11 res.sendFile(`/static/\${req.params.hash}/\${req.params.file}`);12});1314// API: CDN caches 60s, browser always revalidates15app.get('/api/products', (req, res) => {16 res.set({17 'Cache-Control': 'public, s-maxage=60, max-age=0, stale-while-revalidate=30',18 'Vary': 'Accept-Encoding',19 });20 res.json({ products: [] });21});2223// Private: Never cache on CDN24app.get('/api/me/profile', (req, res) => {25 res.set('Cache-Control', 'private, no-store');26 res.json({ user: req.user });27});2829// ---------- CDN Purge API ----------30class CDNManager {31 async purgeUrls(urls) {32 console.log(`Purging \${urls.length} URLs from CDN`);33 // Call CDN provider API (Cloudflare, CloudFront, etc.)34 }3536 async purgeByTag(tags) {37 console.log(`Purging tags: \${tags.join(', ')}`);38 }39}4041// ---------- Versioned Static Assets ----------42const crypto = require('crypto');43const fs = require('fs');4445function getAssetUrl(filePath) {46 const content = fs.readFileSync(filePath);47 const hash = crypto.createHash('md5').update(content).digest('hex').slice(0, 8);48 const ext = filePath.split('.').pop();49 const basename = filePath.split('/').pop().replace(`.\${ext}`, '');50 return `/static/\${basename}.\${hash}.\${ext}`;51}5253console.log("CDN patterns configured.");
🏋️ Practice Exercise
CDN Architecture: Design CDN strategy for Netflix — video chunks, thumbnails, API responses, static assets. What gets cached? Cache policies?
Cache-Control Headers: Write exact headers for: (a) Webpack bundle with hash, (b) User avatar, (c) Blog post HTML, (d) Real-time stock API.
Global Latency: Users in India get 3s load time, US users get 500ms. Design multi-CDN strategy to bring India < 1s.
CDN Invalidation at Scale: Breaking news changes homepage. Design invalidation for browser + CDN (200+ edges) + API caches.
⚠️ Common Mistakes
Not using versioned filenames — without content hashes, CDN purging is the only way to update assets. Slow and error-prone.
Setting s-maxage too high for dynamic content — 24h CDN cache means 24h to propagate updates.
Caching personalized content on CDN — all users might see one user's personal info. Use 'private' for personalized data.
Not using Vary headers — CDN might serve gzipped response to client that doesn't support it.
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for CDN & Edge Caching