Mental model
A Content Delivery Network (CDN) terminates TLS and stores cacheable HTTP representations inside hundreds of geographically distributed Point-of-Presence (PoP) edge nodes close to end users (5–25 ms RTT instead of 150–300 ms back to a single origin VPS). Mastering CDN architecture requires separating browser cache lifetime (max-age) from shared proxy cache lifetime (s-maxage), serving instant background-refreshed responses via stale-while-revalidate / stale-if-error, cleaning cache keys with Vary and Surrogate-Key tag purges, and enforcing bulletproof boundaries so authenticated PII (Set-Cookie, Authorization) can never leak across shared edge nodes.
Theory
Confusing client-private caching with public CDN edge caching causes either 0% edge offload (every request hitting your VPS) or critical security disclosures (caching Tenant A's dashboard response globally).
| HTTP Header Directive | Controlled Target | Production Usage Pattern | Security & Ops Caution |
|---|---|---|---|
public, max-age=60, s-maxage=3600 | Browser caches 60 s; shared CDN edge caches 3600 s | Public docs, landing catalogs, read-only public REST APIs | Allows instant CDN tag purge without leaving stale 1-hour copies stuck in user browsers! |
stale-while-revalidate=86400 | Edge & browsers after TTL expiry | Serve stale copy instantly (< 15 ms) while 1 background fetch refreshes edge asynchronously | Prevents origin p99 spikes on popular key expiry (check CDN support for stale-if-error on 5xx outages too!) |
private, no-store | User-specific authenticated APIs/SSR pages | Any route inspecting cookies, Authorization, or PII (Set-Cookie!) | Never combine public / s-maxage with Set-Cookie or personalized HTML |
immutable (max-age=31536000) | Content-hashed static assets (/static/app.8f91c2.js) | JS/CSS bundles, fonts, hashed images whose URL changes every build | Eliminates unnecessary 304 If-None-Match revalidation requests forever |
Request Collapsing, Vary Cardinality Hygiene, and Tag-Based Surrogate Purges
Under a traffic spike when a popular un-cached catalog page expires, Origin Shielding / Request Collapsing coalesces 500 simultaneous PoP cache misses into one single origin request, forwarding that single fresh origin response out to all 500 waiting clients. Meanwhile, avoid Cache-Control Vary fragmentation: adding Vary: User-Agent splits cache keys into tens of thousands of fragmented permutations (Chrome 130.0.1, Chrome 130.0.2), collapsing cache hit ratio toward zero! Keep Vary minimal (Vary: Accept-Encoding or explicit Vary: Accept-Encoding, Origin when CORS dynamically sets origins). For instant invalidations upon CMS publishes without flushing the entire CDN cache (which hammers origin servers cleanly right after purge!), attach response tags like Cache-Tag: concept-42,catalog-list (Surrogate-Key on Fastly) and purge solely affected tags (POST /purge_by_tag) via webhooks—and strip internal Surrogate-Control headers cleanly at the edge so browsers only obey downstream Cache-Control.
pythonfrom fastapi import FastAPI, Responseapp = FastAPI()@app.get("/api/v1/public/concepts/{slug}")async def get_public_concept(slug: str, response: Response) -> dict[str, str]:# Browser validates every 60s; CDN caches 1 hour and refreshes asynchronously for 24h on stale hitresponse.headers["Cache-Control"] = ("public, max-age=60, s-maxage=3600, stale-while-revalidate=86400, stale-if-error=86400")response.headers["Cache-Tag"] = f"concept:{slug},public-catalog"response.headers["Vary"] = "Accept-Encoding"return {"slug": slug, "status": "ok"}@app.get("/api/v1/me/profile")async def get_private_profile(response: Response) -> dict[str, str]:# Strict guardrail preventing shared CDN caching of user PII or cookiesresponse.headers["Cache-Control"] = "private, no-store, max-age=0"return {"user": "authenticated-session"}
Alternatives and trade-offs
- Global Push/Pull Edge CDN (
Cloudflare/Fastly/CloudFront): Offloads80%–98%of read bandwidth, absorbs L3/L4/L7 DDoS floods upstream of origin VPS instances, cuts global TTFB under25 ms, and sustains read availability during brief origin restarts viastale-if-error; introduces cache-key debugging complexity,Varyfragmentation pitfalls, and purge automation requirements. - Origin-Only In-Memory Cache (
Nginx microcache/Redis): Simpler invalidation logic directly co-located with writes (zero distributed PoP eventual lag), yet still routes transoceanic packets across the internet back to one region and exposes origin compute to bandwidth spikes. - Static Immutable Builds + Content-Addressed URLs (
app.<hash>.js,/media/<sha256>.webp): Achieves zero invalidation bugs completely because every edited file receives a fresh unique URL while old versions remain cached safely for1 year(immutable) during rolling deployments!
Failure modes and misconceptions
- Cross-Tenant Cache Poisoning (
public, s-maxage+Set-Cookieor Personalized Auth): If an origin accidentally marks an authenticated routepublic, s-maxage=300without ignoring cookies—or renders user email inside an edge-cached SSR page—the CDN happily serves User A's private profile to User B worldwide (Web Cache Deception / PII leak)! Configure CDN rules never to cache any request containingAuthorization/sessioncookies, and emit explicitprivate, no-storeon personalized routes. - Flushing the Entire Site Cache ("Purge Everything") on Single CMS Edits: Purging
*globally drops Edge Hit Ratio to0%simultaneously, causing millions of users to stampede the origin VPS directly (self-inflicted origin collapse). Purge specifically by URL orCache-Tag/Surrogate-Keybatches! - Cache Key Fragmentation via Untracked Marketing Query Params (
?fbclid=...&utm_source=...): Default CDNs treat/concepts/rag?utm_source=xand/concepts/rag?utm_source=twitteras completely distinct cache misses—destroying edge hit rates whenever social links circulate! Configure CDN query-string ignore lists (utm_*,fbclid,gclid). - Setting High
max-age=86400Without Separatings-maxage: Settingmax-age=86400locks stale API/HTML responses inside millions of customer Chrome caches for 24 hours where your CDN purge API cannot reach them! Always keep browsermax-ageshort (0–60 sfor dynamic HTML/APIs) while giving the controllable CDN edge longers-maxage+stale-while-revalidate.
Decision scenario
Your educational SaaS (fullstackaihub.com) serves 400 public SSR curriculum pages and immutable Next.js static bundles worldwide from a single European Contabo VPS while simultaneously running authenticated /admin, /oauth, and /api/user endpoints. Set /_next/static/* hashed assets to public, max-age=31536000, immutable, configure public concept/catalog pages with public, max-age=60, s-maxage=3600, stale-while-revalidate=86400, stale-if-error=86400 plus Cache-Tag headers triggered automatically via your CMS publish hook (purge_by_tag ignoring utm_*/fbclid query strings), enforce Cache-Control: private, no-store plus cookie/auth cache-bypass rules across /admin, /oauth, and user APIs, and pair Origin Shielding so origin CPU handles only coalesced refreshes cleanly.
Learning outcomes
- Distinguish browser-locked
max-agefrom CDN-purgeables-maxageand design non-blockingstale-while-revalidate/stale-if-errorpolicies. - Eliminate cache-miss origin storms using Request Collapsing, Origin Shielding, and granular
Cache-Tagpurges instead of wildcard flushes. - Protect edge hit rates from query-string (
utm_*) andVary(User-Agent) fragmentation. - Prevent severe Web Cache Deception / PII leaks via strict
private, no-storeand cookie-aware bypass boundaries.
Trade-offs
CDN edge caching slashes global latency and origin compute load dramatically across read-heavy workloads, balanced against strict URL/tag purge orchestration, query-string normalization, and unforgiving separation between public cacheable content and private user state.