CDN & Edge Computing Cheat Sheet
Key concepts, configuration patterns, and provider comparisons for content delivery networks and edge compute platforms.
AWS CloudFront Distribution (CLI)
Create a CDN distribution in front of an S3 origin.
aws cloudfront create-distribution \ --origin-domain-name my-bucket.s3.amazonaws.com \ --default-root-object index.html
Cache-Control Headers
HTTP headers controlling CDN and browser caching behavior.
# Cache aggressively, immutable assets (hashed filenames)Cache-Control: public, max-age=31536000, immutable# Never cache dynamic/personalized contentCache-Control: no-store# Cache but always revalidate with originCache-Control: no-cache# Cache for 1 hour, serve stale for another hour while revalidatingCache-Control: max-age=3600, stale-while-revalidate=3600
Edge Function (Cloudflare Workers)
Run JavaScript at the edge, close to the user.
export default { async fetch(request) { const url = new URL(request.url); if (url.pathname === '/hello') { return new Response('Hello from the edge!', { headers: { 'content-type': 'text/plain' } }); } return fetch(request); // pass through to origin }};
Core Concepts
Key core concepts to know.
- Origin- The source server (S3, load balancer, custom server) the CDN pulls content from
- Edge Location / PoP- Geographically distributed server caching content close to end users
- Cache Hit Ratio- Percentage of requests served from cache vs forwarded to origin
- TTL (Time to Live)- Duration a cached object remains valid before revalidation
- Cache Invalidation- Manually purging cached objects before their TTL expires
- Edge Compute- Running application logic (not just caching) at edge locations for lower latency
Provider Landscape
Key provider landscape to know.
- Amazon CloudFront- AWS-native CDN, integrates tightly with S3, Lambda@Edge, and ACM
- Cloudflare- Global CDN plus Workers (edge compute), DDoS protection, and DNS
- Azure CDN / Front Door- Microsoft's CDN with global load balancing and WAF integration
- Google Cloud CDN- Backed by Google's global network, integrates with Cloud Load Balancing
- Fastly- Real-time CDN with instant purge and VCL-based edge logic
CloudFront Signed URL (Python)
Restrict access to premium/private content with a time-limited, tamper-proof URL.
from datetime import datetime, timedeltafrom botocore.signers import CloudFrontSignerimport rsadef rsa_signer(message): with open('private_key.pem', 'rb') as f: return rsa.sign(message, rsa.PrivateKey.load_pkcs1(f.read()), 'SHA-1')key_id = 'K2JCJMDEHXQW5F'signer = CloudFrontSigner(key_id, rsa_signer)url = signer.generate_presigned_url( 'https://d123abcdef.cloudfront.net/videos/premium.mp4', date_less_than=datetime.utcnow() + timedelta(hours=1))print(url)
Custom Cache Keys with Vary
Prevent cache poisoning and fragmentation by controlling exactly which request attributes vary the cached object.
# Origin response tells the CDN which headers split the cacheVary: Accept-Encoding, Accept-Language# CloudFront cache policy (CLI) — cache by device type header only,# ignore all query strings and cookies to maximize hit ratioaws cloudfront create-cache-policy \ --cache-policy-config '{ "Name": "device-type-only", "MinTTL": 1, "ParametersInCacheKeyAndForwardedToOrigin": { "HeadersConfig": {"HeaderBehavior": "whitelist", "Headers": {"Items": ["CloudFront-Is-Mobile-Viewer"], "Quantity": 1}}, "CookiesConfig": {"CookieBehavior": "none"}, "QueryStringsConfig": {"QueryStringBehavior": "none"} } }'
Edge Middleware — Geo-Based Routing (Next.js)
Rewrite requests at the edge before they hit origin, based on the viewer's inferred region.
import { NextResponse } from 'next/server';export const config = { matcher: '/((?!_next/static|favicon.ico).*)' };export function middleware(req) { const country = req.geo?.country ?? 'US'; const url = req.nextUrl.clone(); if (country === 'DE' || country === 'FR') { url.pathname = `/eu${url.pathname}`; return NextResponse.rewrite(url); } return NextResponse.next();}
Origin Shield + Stale-If-Error
Reduce origin load with a shield layer and keep serving cached content when the origin is down.
# Origin Shield: adds one extra caching tier close to the origin so only# ONE request per object per region reaches origin, instead of one per PoP.aws cloudfront update-distribution --id EDFDVBD6EXAMPLE \ --distribution-config file://origin-shield-config.json# stale-if-error lets edge serve a stale copy for up to 1 day# if the origin returns 5xx or times outCache-Control: max-age=300, stale-while-revalidate=60, stale-if-error=86400
Advanced CDN & Edge Concepts
Terms that come up once you move past basic caching into production-grade edge architecture.
- Anycast Routing- Same IP announced from many PoPs; BGP routes the client to the topologically nearest one
- Cache Stampede / Dogpiling- Many concurrent requests miss cache simultaneously on expiry; mitigated with request coalescing at the edge
- Multi-CDN Strategy- DNS or client-side steering across two+ CDN vendors for resilience and cost arbitrage
- Edge KV Store- Low-latency key-value storage co-located with edge compute (Cloudflare KV, Vercel Edge Config) for config/feature flags
- Brotli Compression- ~15-20% smaller than gzip for text assets; CDNs negotiate it via Accept-Encoding automatically
- HTTP/3 (QUIC)- UDP-based transport eliminating head-of-line blocking, faster connection setup on lossy mobile networks
- Soft Purge / Instant Purge- Soft purge marks content stale (revalidate on next hit) instead of a hard delete, avoiding a thundering herd on origin
Version static assets with content-hashed filenames (e.g. app.a1b2c3.js) and set them to 'immutable, max-age=31536000' — this lets you cache forever while still guaranteeing instant updates, since a new deploy simply produces a new filename.