CDN Caching: Content Delivery Networks and Edge Caching
In this tutorial, you will learn about CDN Caching: Content Delivery Networks and Edge Caching. We cover key concepts, practical examples, and best practices to help you master this topic.
A Content Delivery Network (CDN) caches responses across geographically distributed edge servers. When a user requests content, the CDN serves it from the nearest edge location, dramatically reducing latency and offloading traffic from the origin server.
flowchart TB
User1[User - US East] --> CDN1[US East Edge]
User2[User - Europe] --> CDN2[Europe Edge]
User3[User - Asia] --> CDN3[Asia Edge]
CDN1 --> Origin[Origin Server]
CDN2 --> Origin
CDN3 --> Origin
CDN1 -.->|Cache Miss| Origin
CDN1 -.->|Cache Hit| Cache
What You'll Learn
- How CDNs cache and serve content from edge locations
- Cache key design: query parameters, cookies, headers, and Vary
- Purging and invalidating CDN caches
- Origin shielding and cache hierarchies
Why It Matters
A CDN can serve cached content in 10-50ms versus 100-500ms from a single origin. It also absorbs DDoS attacks by distributing traffic across thousands of edge nodes and reduces bandwidth costs at the origin.
Real-World Use
A global e-learning platform uses CloudFront to cache course thumbnails, video metadata, and API responses. Cache hit rate exceeds 95%, allowing a single small origin server to serve 10 million daily users across 6 continents.
CDN Cache Key Design
Normalizing Cache Keys in Express
const url = require('url');
app.use((req, res, next) => {
const parsed = url.parse(req.url, true);
const normalizedParams = Object.keys(parsed.query).sort().map(k => `${k}=${parsed.query[k]}`).join('&');
res.set('X-CDN-Key', `${req.method}:${parsed.pathname}?${normalizedParams}`);
res.set('Cache-Control', 'public, max-age=300');
next();
});
Expected output:
CDN uses the normalized URL as cache key, so ?a=1&b=2 and ?b=2&a=1 map to the same cache entry.
Vary Header for Multi-Version Caching
app.get('/api/content', (req, res) => {
const locale = req.headers['accept-language']?.split(',')[0]?.split('-')[0] || 'en';
const content = getLocalizedContent(locale);
res.set('Vary', 'Accept-Language');
res.set('Cache-Control', 'public, max-age=3600');
res.json(content);
});
Expected output:
CDN caches separate copies for each Accept-Language value. Spanish users get Spanish content, French users get French.
CDN Purge Request Handling
app.post('/api/purge', async (req, res) => {
const { url } = req.body;
const apiToken = req.headers['x-api-key'];
if (apiToken !== process.env.CDN_API_TOKEN) {
return res.status(403).json({ error: 'Unauthorized' });
}
try {
await cloudfront.createInvalidation({
DistributionId: process.env.CLOUDFRONT_DIST_ID,
InvalidationBatch: {
Paths: { Quantity: 1, Items: [url] },
CallerReference: Date.now().toString()
}
}).promise();
res.json({ success: true, invalidated: url });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
Expected output:
POST /api/purge with valid API key triggers CDN invalidation for that path. Subsequent requests miss cache and fetch from origin.
Common Mistakes
- Caching authenticated content at the CDN without varying by Authorization header, leaking user data between sessions.
- Using a single distribution for both static assets and dynamic API responses with different caching needs.
- Not purging CDN cache after content updates, serving stale data for hours or days.
- Ignoring query parameter order in cache keys — ?id=1&type=2 and ?type=2&id=1 should map to the same cache entry.
- Forgetting to enable origin shielding, causing every edge miss to hit the origin simultaneously (cache stampede at scale).
Practice Questions
- How does a CDN edge location reduce latency?
- What is the difference between a CDN cache hit and a cache miss?
- Why is cache key normalization important for CDNs?
- How does origin shielding prevent cache stampedes?
- What is the cost trade-off between purging individual URLs and wildcard /* purges?
Challenge
Design a CDN caching Strategy for an e-commerce site. Product pages should be cached for 1 hour, cart pages never cached, and API search results cached for 5 minutes. Implement origin shielding and a purge endpoint that accepts product IDs and invalidates related paths.
FAQ
Mini Project
Set up a local simulation: use Nginx as a reverse proxy cache to simulate CDN behavior. Create three origin endpoints with different cache policies. Implement a purge endpoint. Write a load test showing the difference in latency and origin load between cached and uncached responses.
What's Next
Continue with Redis Cache to master Redis-based caching with advanced data structures and cluster configurations.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro