Learning outcomes
- Configure HTTP Cache-Control headers for CDN edge nodes
- Execute instant purge API calls on content updates
Mental model
Content Delivery Networks (CDNs) cache static assets and SSG HTML pages on geographically distributed edge servers near users, offloading origin servers and reducing global latency.
Theory
max-agevss-maxage:max-agedictates browser cache duration;s-maxagedictates public CDN edge cache duration.stale-while-revalidate: Instructs the CDN edge node to serve a stale cached response immediately while asynchronously fetching an updated version from the origin server in the background.- Edge Invalidation: Programmatically purging cached URLs at CDN edge nodes via API when underlying content changes.
from fastapi import FastAPI, Response
app = FastAPI()
@app.get("/api/v1/catalog")
async def get_catalog(response: Response):
# Instruct CDN Edge to cache for 1 hour, serve stale for 1 day while revalidating
response.headers["Cache-Control"] = "public, max-age=300, s-maxage=3600, stale-while-revalidate=86400"
response.headers["Vary"] = "Accept-Encoding"
return {"status": "success", "catalog": [...]}
Alternatives and trade-offs
- Direct Origin Serving: Simple; expensive bandwidth costs, high latency for distant global users, origin crashes under traffic spikes.
- CDN Edge Caching: Sub-20ms global response times; requires managing cache invalidation hooks on content updates.
Failure modes and misconceptions
- Caching Authenticated API Responses: Sending
s-maxageon endpoints returning user PII causes CDN edge nodes to serve private user data to other users. Always setCache-Control: private, no-storeon authenticated routes. - Missing
VaryHeaders: Failing to setVary: Accept-Encodingcauses CDNs to serve uncompressed Gzip responses to clients requesting Brotli compression.
Decision scenario
Use Cache-Control: public, s-maxage=3600, stale-while-revalidate=86400 on public catalog and static content routes to achieve sub-20ms CDN edge responses globally.
Learning outcomes
- Structure HTTP
Cache-Controldirectives (max-age,s-maxage,stale-while-revalidate). - Programmatically trigger CDN edge cache purges on content updates.
- Prevent security vulnerabilities caused by caching private authenticated endpoints.
Trade-offs
CDN edge caching eliminates origin traffic load and delivers ultra-low latency, but requires strict handling of private endpoint header restrictions and purge APIs.
Evidence assessment
Theory and decision mastery
Decision scenario
You are designing a high-concurrency production system requiring reliable execution of cdn edge caching invalidation under heavy traffic load.
Which architectural decision ensures maximum resilience, scalability, and system stability?
Primary sources
- FastAPI Framework Architecture & Dependency Injection Specification — Tiangolo, verified 2026-07-22