How CDNs Work
How CDNs Work
Content Delivery Networks distribute content globally for faster access.
CDN Architecture
User → Edge Server (nearest) → Origin Server
↓
Cache Hit → Return cached content
Cache Miss → Fetch from origin, cache, return
Benefits
- Reduced Latency: Content served from nearest edge
- Reduced Origin Load: Edge servers handle most requests
- High Availability: Redundancy across multiple locations
- DDoS Protection: Edge servers absorb attacks
Popular CDNs
- Cloudflare: Free tier, easy setup
- AWS CloudFront: Deep AWS integration
- Fastly: Real-time purge, edge computing
- Akamai: Enterprise-grade
- Vercel/Netlify: Built-in for static sites
DNS Resolution
1. User requests example.com
2. DNS resolves to CDN edge server IP
3. Edge server checks cache
4. If miss, fetches from origin
5. Caches response for future requests
CDN Configuration
CDN Configuration
Cloudflare Setup
// wrangler.toml (Cloudflare Workers)
name = "my-site"
routes = [
{ pattern = "example.com/*", zone_name = "example.com" }
]
// Worker for custom caching
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
// Custom cache key
const cacheKey = new Request(url.toString(), request)
const cache = caches.default
// Check cache
let response = await cache.match(cacheKey)
if (response) {
return response
}
// Fetch from origin
response = await fetch(request)
// Cache response
if (response.ok) {
const clonedResponse = response.clone()
clonedResponse.headers.set('Cache-Control', 'public, max-age=3600')
event.waitUntil(cache.put(cacheKey, clonedResponse))
}
return response
}
AWS CloudFront
// CloudFront distribution config
const distributionConfig = {
Origins: {
Items: [
{
DomainName: 'origin.example.com',
Id: 'origin-1',
CustomOriginConfig: {
HTTPPort: 80,
HTTPSPort: 443,
OriginProtocolPolicy: 'https-only',
},
},
],
},
DefaultCacheBehavior: {
TargetOriginId: 'origin-1',
ViewerProtocolPolicy: 'redirect-to-https',
CachePolicyId: '658327ea-f89d-4fab-a63d-7e88639e58f6', // CachingOptimized
Compress: true,
},
CacheBehaviors: {
Items: [
{
PathPattern: '/api/*',
TargetOriginId: 'origin-1',
ViewerProtocolPolicy: 'redirect-to-https',
CachePolicyId: '4135ea2d-6df8-44a3-9df3-4b5a84be39ad', // CachingDisabled
},
],
},
};
Caching Rules
// Static assets (immutable)
const staticAssets = {
pattern: '\\\.(js|css|png|jpg|jpeg|gif|ico|svg|woff2)$',
cacheControl: 'public, max-age=31536000, immutable',
};
// HTML pages
const htmlPages = {
pattern: '\\\.html$|^/$',
cacheControl: 'public, max-age=3600, must-revalidate',
};
// API responses
const apiResponses = {
pattern: '/api/*',
cacheControl: 'private, no-cache',
};
Purging Cache
// Cloudflare API
async function purgeCache(zoneId, apiToken, urls) {
await fetch(
`https://api.cloudflare.com/client/v4/zones/${zoneId}/purge_cache`,
{
method: 'DELETE',
headers: {
Authorization: `Bearer ${apiToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ files: urls }),
}
);
}
Edge Caching
Edge Caching
Cache content at edge locations closest to users.
Edge Caching Strategies
// Cache by device type
const cacheKey = new Request(url, {
headers: {
'User-Agent': request.headers.get('User-Agent'),
'Accept': request.headers.get('Accept'),
},
});
// Cache by locale
const locale = request.headers.get('Accept-Language')?.split(',')[0] || 'en';
const cacheKey = `${url}?locale=${locale}`;
Cache Invalidation at Edge
// Versioned assets
const version = 'v1.2.3';
const assetUrl = `/static/${version}/app.js`;
// Purge specific paths
await purgeCache(zoneId, apiToken, [
'/index.html',
'/static/v1.2.3/*',
]);
Edge Computing
// Cloudflare Worker for edge logic
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
// A/B testing at edge
const bucket = Math.random() < 0.5 ? 'A' : 'B';
const cookie = `ab-test=${bucket}; path=/`
// Rewrite URL based on bucket
if (bucket === 'B' && url.pathname === '/') {
url.pathname = '/new-homepage';
}
const response = await fetch(url.toString(), request)
const newResponse = new Response(response.body, response)
newResponse.headers.set('Set-Cookie', cookie)
return newResponse
}
CDN Best Practices
- Use immutable caching for versioned assets
- Set appropriate TTLs for different content types
- Implement cache invalidation for dynamic content
- Use edge computing for personalization
- Monitor cache hit ratios
- Configure proper cache keys
- Use compression at the edge
Practice Problems
Create a reusable React component implementing CDN. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for CDN using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize CDN for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. How does a CDN reduce latency?
2. What is a cache hit?
3. How should you cache static assets on a CDN?
4. What is edge computing?
5. How do you invalidate CDN cache?
Flashcards
Question
What is a CDN?
Click to reveal answer
Answer
A Content Delivery Network distributes content globally to edge servers for faster access.
Question
What is a cache hit?
Click to reveal answer
Answer
When requested content is found in the CDN cache and served directly to the user.
Question
What is edge computing?
Click to reveal answer
Answer
Running code on CDN servers close to users for lower latency and personalization.
Question
How do you invalidate CDN cache?
Click to reveal answer
Answer
Purge via CDN API or use versioned filenames for instant cache invalidation.
Question
What is CDN?
Click to reveal answer
Answer
CDN is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.CDNs reduce latency by serving from nearest edge
- 2.Static assets should use immutable caching for 1 year
- 3.Use versioned URLs for instant cache invalidation
- 4.Edge computing enables personalization at the edge
- 5.Monitor cache hit ratios for optimization
Interview Tips
- •Explain how a CDN reduces latency
- •Discuss cache invalidation strategies
- •Know the benefits of edge computing
Cheat Sheet
CDN Cheat Sheet
How CDNs Work
- Edge servers cache content globally
- Users get content from nearest edge
- Reduces latency and origin load
Caching Rules
- Static assets: immutable, 1 year
- HTML: short TTL, must-revalidate
- API: private, no-cache
Invalidation
- Versioned URLs: instant invalidation
- API purge: Cloudflare, CloudFront
Edge Computing
- A/B testing at edge
- Personalization
- Authentication