CDN & Edge Caching

0/4 in this phase0/45 across the roadmap

📖 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

  1. User requests cdn.example.com/image.jpg
  2. DNS routes to nearest edge server
  3. Cache HIT: Serve from edge (~10ms)
  4. 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

codeTap to expand ⛶
1// ============================================
2// CDN & Edge Caching — Implementation
3// ============================================
4
5const express = require('express');
6const app = express();
7
8// Static assets: immutable, cache forever
9app.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});
13
14// API: CDN caches 60s, browser always revalidates
15app.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});
22
23// Private: Never cache on CDN
24app.get('/api/me/profile', (req, res) => {
25 res.set('Cache-Control', 'private, no-store');
26 res.json({ user: req.user });
27});
28
29// ---------- 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 }
35
36 async purgeByTag(tags) {
37 console.log(`Purging tags: \${tags.join(', ')}`);
38 }
39}
40
41// ---------- Versioned Static Assets ----------
42const crypto = require('crypto');
43const fs = require('fs');
44
45function 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}
52
53console.log("CDN patterns configured.");

🏋️ Practice Exercise

  1. CDN Architecture: Design CDN strategy for Netflix — video chunks, thumbnails, API responses, static assets. What gets cached? Cache policies?

  2. Cache-Control Headers: Write exact headers for: (a) Webpack bundle with hash, (b) User avatar, (c) Blog post HTML, (d) Real-time stock API.

  3. Global Latency: Users in India get 3s load time, US users get 500ms. Design multi-CDN strategy to bring India < 1s.

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