system-design · intermediate
Content Delivery Networks (CDN) — Edge Acceleration and Caching
The Central Question
Consider a global web application running on the CacheLab platform (cachelab.com) hosted in a primary cloud data center located in Frankfurt, Germany (eu-central-1):
- A mobile application user in Sydney, Australia opens the application (
assets.cachelab.com). - The network packet travels across undersea fiber cables over a physical distance of 16,000 kilometers, requiring a round-trip time (RTT) of 280 milliseconds.
- Establishing an encrypted TLS 1.3 connection requires 2 TCP round-trips ($280\text{ms} \times 2 = 560\text{ms}$).
- Downloading 15 separate JavaScript bundles, CSS stylesheets, images, and font files over a single origin connection causes page render times to explode past 4.5 seconds.
Furthermore, when 100,000 global users simultaneously download a 5 MB promotional video file, the origin data center's network bandwidth saturates, driving server CPU utilization to 100% and crashing the application.
To overcome speed-of-light physical distance limits and offload origin network traffic, systems deploy edge caching networks.
A Content Delivery Network (CDN) is a globally distributed network of edge proxy servers (Points of Presence) that caches static and public responses geographically close to end users, terminating TLS handshakes at the edge and serving cached content without hitting origin servers.
This lesson answers one central question: How do Content Delivery Networks leverage Anycast DNS, edge Points of Presence (PoPs), HTTP Cache-Control directives, and Cache Invalidation strategies to deliver sub-50ms user latency while protecting origin data centers from traffic saturation?
The Origin vs. Edge Topology
A CDN alters the network route between public clients and application backend data centers by establishing an intermediate Edge Tier:
flowchart TB
subgraph Public Users Worldwide
UserUS[User in New York]
UserEU[User in London]
UserAPAC[User in Sydney]
end
subgraph CDN Edge Tier Points of Presence
PoPUS[New York Edge PoP 203.0.113.5]
PoPEU[London Edge PoP 198.51.100.12]
PoPAPAC[Sydney Edge PoP 192.0.2.88]
end
subgraph Origin Data Center Tier
Shield[CDN Origin Shield Proxy]
Origin[(Primary Application Storage - Frankfurt)]
end
UserUS -->|Sub-10ms RTT| PoPUS
UserEU -->|Sub-10ms RTT| PoPEU
UserAPAC -->|Sub-10ms RTT| PoPAPAC
PoPUS -.->|Cache Miss: Long-Haul WAN| Shield
PoPEU -.->|Cache Miss: Long-Haul WAN| Shield
PoPAPAC -.->|Cache Miss: Long-Haul WAN| Shield
Shield -->|Fetch Asset| Origin
Figure 1: Network topology comparing regional edge Points of Presence (PoPs) against a central origin data center.
How CDNs Route Users: Anycast DNS and Latency Steering
When a user requests https://assets.cachelab.com/app.js, CDNs route traffic using Anycast or Latency DNS:
flowchart TD
subgraph Anycast BGP Steering
User[User in Sydney] --> BGP[Local ISP Router]
BGP -->|Shortest BGP Path| EdgeSydney[Sydney Edge PoP: 198.51.100.1]
Note["Identical IP 198.51.100.1 advertised by 200 PoPs globally!"]
end
Figure 2: Anycast BGP routing directing users to the closest geographical PoP.
HTTP Caching Directives: Mastering Cache-Control Headers
The interaction between browsers, CDN edge PoPs, and origin servers is controlled by HTTP standards-compliant Cache-Control headers:
HTTP/1.1 200 OK
Content-Type: application/javascript
Cache-Control: public, max-age=3600, s-maxage=86400, stale-while-revalidate=300
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
Deconstructing Caching Headers
| Header Directive | Plain-English Purpose | Target Recipient |
|---|---|---|
public | Permits both browser caches and intermediate CDN edge proxies to store the response. | Browsers & CDNs |
private | Forbids shared CDN proxies from caching; permits browser local cache only (e.g. user profiles). | Browsers Only |
max-age=3600 | Instructs browser caches that the asset remains fresh for 1 hour ($3,600\text{ seconds}$). | Browser Cache |
s-maxage=86400 | Overrides max-age specifically for shared CDN proxies, caching the asset for 24 hours. | Shared CDN Edge |
stale-while-revalidate=300 | Serves stale cached content for up to 5 minutes while asynchronously fetching a fresh copy from origin. | CDN Edge |
no-store | Strictly forbids caching anywhere; forces full origin fetch every time (e.g. credit card checkout). | All Caches |
CDN Invalidation Strategies: Purge by URL, Tag, and Versioning
Updating content before CDN s-maxage expires requires explicit Cache Invalidation:
flowchart TD
Invalidation[CDN Cache Invalidation Methods] --> CacheBusting[1. Cache-Busting Filename Versioning]
Invalidation --> URLPurge[2. Direct URL Instant Purge]
Invalidation --> SurrogateKey[3. Surrogate-Key / Tagged Purge]
CacheBusting --> CBDesc["app.v2.js or main.a8f92.js.<br/>Guarantees 100% cache safety.<br/>Zero CDN purge cost."]
URLPurge --> UPDesc["PURGE /images/banner.jpg.<br/>Invalidates single URL globally across 200 PoPs in < 2s."]
SurrogateKey --> SKDesc["Surrogate-Key: product-10492.<br/>Purges 500 related pages simultaneously via 1 API call."]
Figure 3: Taxonomy of CDN cache invalidation techniques.
Edge Compute & Serverless Workers (Cloudflare Workers / Fastly VCL)
Modern CDNs evolved from static file proxies into programmable Edge Compute Platforms. Developers deploy lightweight JavaScript/Wasm functions directly to CDN edge PoPs globally (such as Cloudflare Workers or AWS Lambda@Edge). Edge workers execute custom application logic in sub-milliseconds right at the geographical edge:
- A/B Testing & Feature Flags: Route users to experimental UI versions based on edge cookie evaluation without contacting origin servers.
- Geo-IP Personalization: Modify HTTP response headers or currency formats based on the client's physical country detected at the edge PoP.
- Edge Authentication: Validate JWT signatures and authorization claims at the edge, short-circuiting invalid requests before they reach core backend databases.
Dynamic Content Acceleration (DCA) & TCP Optimizations
CDNs accelerate un-cacheable dynamic requests (such as personalized user dashboards or checkout transactions) using Dynamic Content Acceleration (DCA):
- Persistent Pre-Warmed Connections: CDN edge PoPs maintain persistent, pre-established TLS and TCP connections back to origin data centers over optimized private fiber routes.
- TCP Window & Congestion Tuning: Edge proxies tune TCP BBR congestion control and window sizes over high-quality backhaul links, bypassing congested public Internet ISP routing.
- TLS Termination at Edge: Clients establish TLS handshakes with the local PoP ($10\text{ms}$ RTT), eliminating the multi-roundtrip delay of establishing TLS directly across oceans to distant origin servers.
CDN Edge Web Application Firewalls (WAF) & Rate Limiting
Because CDNs sit directly at the public ingress boundary of global networks, they serve as primary security shields. Edge Web Application Firewalls (WAF) inspect incoming HTTP headers, request bodies, and SQL injection patterns right at the edge PoP before packets reach origin data centers:
- SQLi & XSS Shielding: Block malicious payloads (
' OR 1=1 --) at the edge, returning HTTP 403 Forbidden without invoking origin servers. - Volumetric DDoS Mitigation: Scrub layer 3/4 SYN floods and layer 7 HTTP GET floods across 200 distributed PoPs, absorbing terabits-per-second attacks through Anycast capacity.
- Bot Management: Analyze TLS fingerprinting and HTTP request timing to identify automated scrapers and block credential stuffing bots at the edge.
TLS Session Resumption at Edge
By offloading TLS session negotiation to local edge PoPs, CDNs utilize TLS 1.3 Session Resumption (Session Tickets). Returning client browsers resume encrypted sessions in a single 0-RTT roundtrip, completely eliminating TLS handshake overhead for recurring global users.
Complete Worked Example: Production Go CDN Edge Caching Middleware
Let's inspect a complete Go implementation of a CDN Edge Caching Middleware for the CacheLab platform (cachelab.com).
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"net/http"
"sync"
"time"
)
type CDNEdgePoP struct {
mu sync.RWMutex
cache map[string]cachedResponse
originURL string
originShield bool
}
type cachedResponse struct {
body []byte
contentType string
eTag string
expiresAt time.Time
}
func NewCDNEdgePoP(originURL string) *CDNEdgePoP {
return &CDNEdgePoP{
cache: make(map[string]cachedResponse),
originURL: originURL,
}
}
func (pop CDNEdgePoP) ServeHTTP(w http.ResponseWriter, r http.Request) {
cacheKey := r.URL.Path
// 1. Check If Client Sent Matching ETag
if clientETag := r.Header.Get("If-None-Match"); clientETag != "" {
pop.mu.RLock()
item, exists := pop.cache[cacheKey]
pop.mu.RUnlock()
if exists && item.eTag == clientETag && time.Now().Before(item.expiresAt) {
w.WriteHeader(http.StatusNotModified) // HTTP 304 Not Modified
return
}
}
// 2. Check Edge PoP Cache Hit
pop.mu.RLock()
item, hit := pop.cache[cacheKey]
pop.mu.RUnlock()
if hit && time.Now().Before(item.expiresAt) {
w.Header().Set("X-Cache", "HIT-EDGE-POP")
w.Header().Set("Cache-Control", "public, max-age=3600, s-maxage=86400")
w.Header().Set("ETag", item.eTag)
w.Header().Set("Content-Type", item.contentType)
w.Write(item.body)
return
}
// 3. Cache Miss: Fetch from Origin Server
pop.fetchFromOriginAndCache(w, r, cacheKey)
}
func (pop CDNEdgePoP) fetchFromOriginAndCache(w http.ResponseWriter, r http.Request, cacheKey string) {
// Simulate Origin Server Fetch
body := []byte(fmt.Sprintf({"asset":"%s","status":"OK","time":"%s"}, cacheKey, time.Now()))
// Generate ETag Hash
hash := sha256.Sum256(body)
eTag := fmt.Sprintf("%s", hex.EncodeToString(hash[:8]))
item := cachedResponse{
body: body,
contentType: "application/json",
eTag: eTag,
expiresAt: time.Now().Add(24 * time.Hour), // s-maxage 24 Hours
}
pop.mu.Lock()
pop.cache[cacheKey] = item
pop.mu.Unlock()
w.Header().Set("X-Cache", "MISS-ORIGIN-FETCH")
w.Header().Set("Cache-Control", "public, max-age=3600, s-maxage=86400")
w.Header().Set("ETag", eTag)
w.Header().Set("Content-Type", item.contentType)
w.Write(body)
}
Failure Modes and Engineering Mitigations
| Failure Scenario | Root Cause | System Symptom | Detection Signal | Mitigation Strategy |
|---|---|---|---|---|
| 1. Origin Stampede Overload | Hot asset expires on CDN PoPs simultaneously; 100,000 global requests hit origin concurrently. | Origin database CPU hits 100%; origin network bandwidth exhausts. | Sharp QPS spike on origin server logs corresponding to CDN TTL expiration. | Deploy an Origin Shield Proxy tier to collapse duplicate cache misses into 1 origin fetch. |
| 2. Private Data Caching Leaks | Developer sets Cache-Control: public on user profile or credit card API endpoints. | User A in London sees User B's private account dashboard served from shared CDN PoP. | Security incidents reporting cross-account data leaks. | Enforce Cache-Control: private, no-store on all authenticated API endpoints. |
| 3. Stale Asset Invalidation Failure | Origin deploys new code, but CDN edge PoPs continue serving cached old JS bundles for 24 hours. | Web app breaks with JavaScript runtime syntax errors across client browsers. | High volume of client-side error telemetry following deployment. | Use Cache-Busting Filename Hashes (bundle.a8f92.js) for all static assets. |
| 4. Volumetric DDoS Origin Crash | Attacker bypasses CDN by appending random query parameters (?random=12345) to URLs. | Every request forces a CDN cache miss, slamming the origin server directly. | Massive surge in origin request rates with randomized query parameters. | Configure CDN Query String Normalization to ignore un-necessary URL parameters. |
What You Should Remember
- CDNs collapse latency by terminating TLS at the edge: Move caching proxies close to end users to reduce RTT from $280\text{ms}$ down to $< 10\text{ms}$.
- Master
Cache-Controlheaders: Uses-maxagefor CDN proxy retention,max-agefor browsers, andno-storefor private authenticated API routes. - Use Cache-Busting filenames for deployment safety: Append content hashes (
app.a8f92.js) to guarantee 100% immediate cache safety without waiting for CDN purges. - Deploy Origin Shielding against Thundering Herds: Interpose an Origin Shield layer between edge PoPs and origin servers to aggregate cache misses.
- Normalize Query Parameters against DDoS Attacks: Strip random query parameters at edge PoPs to prevent attackers from forcing 100% origin cache misses.
Glossary of Terms
| Term | Definition |
|---|---|
| Content Delivery Network (CDN) | A globally distributed network of proxy servers that caches assets close to users. |
| Point of Presence (PoP) | A local datacenter containing caching proxy servers located in major cities near end users. |
| Origin Server | The primary application database or object store that holds authoritative master files. |
| Origin Shield | An intermediate caching proxy tier positioned between edge PoPs and origin servers to reduce origin load. |
| Cache-Control | An HTTP response header specifying caching rules for browsers and shared CDN proxies. |
| Cache Invalidation | The process of removing or purging stale cached assets from edge PoPs before their TTL expires. |
Practice Scenario and Self-Assessment
Architecture Scenario
You are designing the CDN edge caching layer for a global video streaming platform (`video.cachelab.com`):- Video segment files (
.ts2 MB chunks) are served to 10,000,000 global users. - User account authentication routes (
POST /v1/auth/login) handle sensitive credit card transactions.
- Formulate the exact
Cache-Controlheader policy for video segment chunks vs authentication routes. - Design the Origin Shielding architecture to protect origin storage buckets during viral live streaming events.
Interactive Self-Assessment
A new filename creates a distinct cache key, forcing immediate edge and browser fetches with 100% reliability on deploy.
Cache-busting automatically rewrites relational database primary key indexes.
Cache-busting replaces public DNS nameservers with local hosts file entries.
Cache-busting doubles the physical hardware clock speed of origin server CPUs.
The shared CDN edge PoP will cache User A's private profile and serve it to User B, causing a catastrophic security data breach.
The CDN automatically formats the origin server NVMe SSD disk drives.
The CDN converts TCP socket connections into un-encrypted UDP packets.
The CDN converts SQL database tables into un-indexed CSV files.
What to Learn Next
- Distributed Caching & Redis Cluster: Master consistent hashing and Redis cluster partitioning.
- Cache Eviction Policies — LRU, LFU, FIFO, ARC: Learn $O(1)$ LRU eviction and scan pollution prevention.
- Caching Strategies — Read-Through, Write-Through, Write-Back: Revisit read and write caching workflows.
Track: Data, Storage and Messaging
Previous: Caching Strategies — Aside, Through, Behind, and Refresh-Ahead
Next: Distributed Cache Design
Series: Caching
- Caching 101 — Memory Offloading and Latency Reduction
- Caching Strategies — Aside, Through, Behind, and Refresh-Ahead
- Cache Eviction Policies — LRU, LFU, TTL, and Friends
- Distributed Caching — Sharding and High-Availability Clusters
- Cache Stampede — When Expiry Melts the Database
- Stale Cache After Write — When Your Own Update Disappears
- Content Delivery Networks (CDN) — Edge Acceleration and Caching (this guide)
- Bloom Filters — Probabilistic Set Membership at Scale
By Shubham Jain