FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

CDN Edge Caching & Invalidation

Edge Caching, Cache-Control headers (s-maxage, stale-while-revalidate), and instant purge invalidation.

Freshness: current•15 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Configure HTTP Cache-Control headers for CDN edge nodes
  • ✓Execute instant purge API calls on content updates
Isometric Diagram LabSystem Design · 11 steps · 12 min

Caching Strategies & Write Policies

Compare cache-aside, write-through, write-behind, and stampede mitigation under live cache hit-rate sliders.

Open Isometric Walkthrough
Full Technical Reference Document

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.

Client HTTPS Request Hits Nearest Edge PoP
Verify Cache Key (Host + Path + Normalized Vary)
Edge HIT -> Instant Response (<20ms)
Edge MISS / Stale -> Coalesced Origin Fetch
Store Copy with s-maxage, SWR & Surrogate Tags
Conceptual teaching model synthesized from:cloudflare-cache-docs,mdn-http-headers

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 DirectiveControlled TargetProduction Usage PatternSecurity & Ops Caution
public, max-age=60, s-maxage=3600Browser caches 60 s; shared CDN edge caches 3600 sPublic docs, landing catalogs, read-only public REST APIsAllows instant CDN tag purge without leaving stale 1-hour copies stuck in user browsers!
stale-while-revalidate=86400Edge & browsers after TTL expiryServe stale copy instantly (< 15 ms) while 1 background fetch refreshes edge asynchronouslyPrevents origin p99 spikes on popular key expiry (check CDN support for stale-if-error on 5xx outages too!)
private, no-storeUser-specific authenticated APIs/SSR pagesAny 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 buildEliminates 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.

python
from fastapi import FastAPI, Response
​
app = 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 hit
response.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 cookies
response.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): Offloads 80%–98% of read bandwidth, absorbs L3/L4/L7 DDoS floods upstream of origin VPS instances, cuts global TTFB under 25 ms, and sustains read availability during brief origin restarts via stale-if-error; introduces cache-key debugging complexity, Vary fragmentation 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 for 1 year (immutable) during rolling deployments!

Failure modes and misconceptions

  1. Cross-Tenant Cache Poisoning (public, s-maxage + Set-Cookie or Personalized Auth): If an origin accidentally marks an authenticated route public, s-maxage=300 without 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 containing Authorization/session cookies, and emit explicit private, no-store on personalized routes.
  2. Flushing the Entire Site Cache ("Purge Everything") on Single CMS Edits: Purging * globally drops Edge Hit Ratio to 0% simultaneously, causing millions of users to stampede the origin VPS directly (self-inflicted origin collapse). Purge specifically by URL or Cache-Tag / Surrogate-Key batches!
  3. Cache Key Fragmentation via Untracked Marketing Query Params (?fbclid=...&utm_source=...): Default CDNs treat /concepts/rag?utm_source=x and /concepts/rag?utm_source=twitter as completely distinct cache misses—destroying edge hit rates whenever social links circulate! Configure CDN query-string ignore lists (utm_*, fbclid, gclid).
  4. Setting High max-age=86400 Without Separating s-maxage: Setting max-age=86400 locks stale API/HTML responses inside millions of customer Chrome caches for 24 hours where your CDN purge API cannot reach them! Always keep browser max-age short (0–60 s for dynamic HTML/APIs) while giving the controllable CDN edge longer s-maxage + stale-while-revalidate.
Reflect before revealing the guide

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-age from CDN-purgeable s-maxage and design non-blocking stale-while-revalidate / stale-if-error policies.
  • Eliminate cache-miss origin storms using Request Collapsing, Origin Shielding, and granular Cache-Tag purges instead of wildcard flushes.
  • Protect edge hit rates from query-string (utm_*) and Vary (User-Agent) fragmentation.
  • Prevent severe Web Cache Deception / PII leaks via strict private, no-store and 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.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next