CDN & Edge Caching

9 min read

Reading Progress0%
System Design Index
Start Here
Tier 1 -- Building Blocks
Tier 2 -- Core Systems
URL Shortener — System Design InterviewFree
Pastebin — System Design InterviewFree
News Feed System — System Design InterviewFree
Chat System (WhatsApp/Messenger) — System Design InterviewFree
Tier 3 -- Location & Real-Time
Tier 4 -- Infrastructure & Data
Tier 5 -- Finance & Commerce
Tier 6 -- Advanced & Collaborative
System Design Index
Start Here
Tier 1 -- Building Blocks
Tier 2 -- Core Systems
URL Shortener — System Design InterviewFree
Pastebin — System Design InterviewFree
News Feed System — System Design InterviewFree
Chat System (WhatsApp/Messenger) — System Design InterviewFree
Tier 3 -- Location & Real-Time
Tier 4 -- Infrastructure & Data
Tier 5 -- Finance & Commerce
Tier 6 -- Advanced & Collaborative

CDN & Edge Caching

Tier 1 — Building Block


1. What Is It?

A Content Delivery Network () is a globally distributed network of servers — called Points of Presence (PoPs) or edge nodes — that cache content geographically close to end users. When a user requests content (an image, video, JS bundle, or API response), the serves it from the nearest edge node instead of routing all the way back to your origin server.

Without a CDN, a user in Tokyo requesting content from a US-East origin server suffers ~140ms round-trip — just for the network hop. With a CDN edge node in Tokyo, that same request is served from ~5ms away. More importantly, CDNs absorb the majority of traffic at the edge, protecting your origin from massive read load. A well-configured CDN can handle 95%+ of static asset requests without ever touching the origin.

is the underlying mechanism: CDN nodes store cached copies of responses and serve them directly to users during the (Time-To-Live) window — the period a cached copy is considered fresh — only fetching from origin on a cache miss.


QUICK CHECK

Your company's origin server is hosted in US-East. Analytics show that 40% of your users are in Southeast Asia and are reporting slow load times for static assets like images and JS bundles. Which outcome would you most expect after deploying a CDN with edge nodes in Southeast Asia?

Choose one answer

2. How It Works

Cache Hit (Edge Serves Directly)

Cache Miss (Origin Pull)

CDN Architecture

Cache Control Headers

The respects HTTP Cache-Control and Expires headers from the origin:

HeaderExampleEffect
Cache-Control: max-age=86400Static assetsCache for 24 hours at edge
Cache-Control: public, max-age=3600Semi-static contentCache for 1 hour, shared caches allowed
Cache-Control: privateUser-specific pagesDo NOT cache at CDN (user data)
Cache-Control: no-cacheMust revalidateCDN checks origin freshness before serving
Cache-Control: no-storeSensitive dataNever cache anywhere

3. Variants & Comparisons

Push CDN vs. Pull CDN

ModelHow It WorksProsConsBest For
Pull CDNCDN pulls from origin on first miss; caches result at edgeZero setup; origin is source of truth; easy cache invalidationCold-start miss penalty; origin still handles first request per edge per TTL cycleDynamic content, unpredictable access patterns, frequent updates
Push CDNYou proactively upload assets to CDN nodes before requests arriveZero miss latency; guaranteed freshness at deploymentMust upload all assets on every deploy; storage costs; complex invalidationLarge static files (video, installers), assets known to be high-traffic

Static vs. Dynamic Content Caching

Content TypeCacheabilityTTL StrategyExamples
Static assetsExcellentLong TTL (days/weeks) + cache-busting hash in filename (app.a3b4c5.js)JS, CSS, images, fonts
Semi-staticGoodMedium TTL (minutes/hours)Product listings, blog posts, public profiles
PersonalizedPoorPrivate or no-cacheShopping carts, dashboards, notifications
Real-timeNoneno-storeStock prices, live chat, user-specific feeds

Major CDN Providers

ProviderStrengthsPoP CountNotable Features
CloudflareDDoS protection + CDN combo, Workers (edge compute), free tier~330 citiesWorkers for edge logic, Argo for smart routing, very aggressive anycast network
AWS CloudFrontNative AWS integration, Lambda@Edge, very low latency for S3/EC2 origins~450+ PoPs (including regional edge caches)Signed URLs, OAI for S3, streaming support
FastlyReal-time purge (~150ms global invalidation), VCL programmability, instant config deploys~80 PoPs, high-capacityShielding, surrogate keys for mass invalidation
AkamaiOldest/largest CDN, deep enterprise features, IoT/media specialization~4,100 PoPsIon for web performance, media delivery, security add-ons

QUICK CHECK

A video streaming platform is preparing to launch a major movie release. They know exactly which video files will be requested heavily the moment the launch goes live, and they cannot afford any cache-miss latency during that spike. Which CDN caching model is most appropriate for this scenario, and why?

Choose one answer

4. When to Use It (and When NOT To)

Use a CDN When:

  • Globally distributed users — users in multiple geographies experiencing high to your origin
  • Static asset heavy — JS, CSS, images, fonts: perfect for caching
  • High read traffic — offload repeated GET requests from your origin servers
  • Video/large media — byte-range requests, streaming protocols (HLS, DASH) — is essentially mandatory
  • DDoS protection neededCDN absorbs volumetric attacks at the edge before they reach origin

Decision triggers:

  • "If your for static assets is >200ms for overseas users → add CDN"
  • "If static assets account for >50% of your request volume → CDN will dramatically reduce origin load"
  • "If you're serving video → CDN is non-negotiable (origin cannot serve concurrent streams at scale)"

Do NOT Use CDN For:

  • Personalized responsesCDN would cache User A's data and serve it to User B. Always set Cache-Control: private or no-cache for user-specific content.
  • Highly dynamic APIs — if cache hit rate < 5%, CDN adds (a miss is always slower than going directly to origin due to the extra hop)
  • Sensitive/PII data in URLs — some CDN logs request URLs; avoid putting tokens or IDs in query params

Anti-patterns:

  • Caching authenticated responses — forgetting to set Cache-Control: private on user-specific API responses. CDN will serve cached user A data to user B.
  • No cache-busting for static assets — deploying new CSS with the same filename. Users get stale CDN cache. Fix: content hash in filename (app.[hash].css) + immutable .
  • Not using on deploys — new deploy requires immediate -independent purge of old assets. Have a deploy step that calls CDN purge API.
  • Forgetting the Vary header — if your origin returns different content for Accept-Encoding: gzip, CDN must cache gzipped and non-gzipped versions separately. Vary: Accept-Encoding tells CDN to key cache by encoding.

QUICK CHECK

Your team deploys a new version of your web app but forgets to purge the CDN cache. Users continue seeing the old CSS styles even though the origin is serving the updated file. Which strategy, applied before the next deploy, would have prevented this problem entirely?

Choose one answer

5. Real-World Usage

Netflix: Netflix uses a custom called Open Connect — dedicated appliances (servers with large SSD/HDD storage) placed inside ISPs worldwide. Netflix pre-positions popular content to Open Connect appliances at night during off-peak hours (push model). During peak evening streaming hours, ~95% of Netflix traffic is served directly from Open Connect within the ISP, never touching Netflix's origin. This is why Netflix can serve 15% of global internet traffic during peak hours.

GitHub (Fastly): GitHub uses Fastly for CDN. Fastly's key feature for GitHub is instant purge (~150ms global invalidation). When a user pushes code, GitHub must immediately invalidate cached pages for that repository. With traditional CDN TTLs, a 1-hour would show stale README pages for up to 1 hour. Fastly's surrogate keys allow GitHub to invalidate all pages related to a repo with a single API call.

Cloudflare Workers (edge compute): Cloudflare Workers allow running JavaScript at edge PoPs, not just caching. Companies like Discord use Workers to authenticate requests, transform responses, and implement A/B testing at the edge — eliminating an entire round-trip to origin for logic that used to live in the app server. This represents the evolution of CDN from "cache static assets" to "run compute at the edge."


QUICK CHECK

A developer pushes an update to a public repository's README file. The CDN serving the repository pages has a 1-hour TTL configured. Users who visit the repository page immediately after the push still see the old README. Which CDN capability would eliminate this problem, allowing the updated content to be visible globally within milliseconds of the push?

Choose one answer

6. Interview Cheat Sheet

Key sentences to demonstrate depth:

  1. "A reduces by serving content from geographically close edge nodes and reduces origin load by absorbing cache hits — a well-tuned handles 95%+ of static traffic without touching origin."
  2. "The key CDN decision is what to cache: static assets with long TTLs and filename-based cache busting are a perfect fit; personalized API responses must never be cached at a shared edge node."
  3. "CDN invalidation is the hard part — for static assets I use content-addressed filenames (hash in URL) with immutable TTLs, eliminating the invalidation problem. For semi-static content I use the CDN's purge API on deploy."
  4. "A 'shield' or 'mid-tier' PoP collapses cache misses from many edge nodes into a single origin request — without it, a burst of misses from 100 edge nodes all simultaneously hit origin."
  5. "CDNs are also DDoS mitigation — they absorb volumetric attacks at the edge's massive bandwidth capacity before packets reach your origin."

Common follow-up questions:

QuestionConcise Answer
"How do you invalidate CDN cache?"Option 1: Content-addressed URLs (hash in filename) — just change the filename, no invalidation needed. Option 2: CDN purge API on deploy (Fastly ~150ms global purge, CloudFront ~seconds–minutes). Option 3: Short TTLs for content that changes frequently.
"What is a cache hit ratio and how do you improve it?"Cache hit ratio = hits / (hits + misses). Improve by: increasing TTLs, reducing query string variability, normalizing request paths, using surrogate/cache tags to group related objects.
"What is edge compute?"Running application logic (JS/Wasm) at CDN PoPs instead of just caching. Eliminates origin round-trip for auth, routing, A/B testing. Examples: Cloudflare Workers, Lambda@Edge, Fastly Compute.
"How does CDN handle HTTPS?"CDN terminates TLS at the edge PoP (uses its own TLS cert). Saves the user the ~100ms TLS handshake to a distant origin. The CDN-to-origin connection can be TLS (full end-to-end) or plain HTTP (flexible mode).
"What is the 'thundering herd' problem with CDNs?"A popular object's TTL expires at the same moment; thousands of edge nodes miss simultaneously and all hit origin. Fix: request coalescing (CDN holds all simultaneous misses while one upstream request to origin is in flight).

Connections to other building blocks:

  • Caching Strategies: CDN implements semantics (miss → origin pull → cache at edge). HTTP Cache-Control headers are the CDN's mechanism.
  • Load Balancing: CDN typically sits in front of your . distributes among origin app servers; CDN distributes globally across PoPs.
  • Read Replicas: CDN handles static/semi-static content; read replicas handle dynamic database reads. Together they cover most read traffic.
  • : CDNs often provide rate limiting at the edge — block abusive IPs before traffic hits your origin. Cloudflare, Fastly both support edge rate limiting rules.
  • : Large CDN networks use internally to route requests to the same edge node for a given URL (maximizing cache hit rates across CDN nodes).
Glossary History

Click dotted jargon to save explanations here.

Glossary History

Click dotted jargon to save explanations here.