CDN — Serve Content From the Edge
Distribute static and cacheable content from edge nodes near users — offload your origin and reduce latency globally.
When to use
- Static assets (images, JS, CSS) and public API responses with low mutation rate
- Global user base with latency-sensitive delivery
Tradeoffs
- Cache invalidation at edge nodes is eventual — purge propagation takes time
- Personalized or auth-gated content needs careful
Cache-Controlor bypass rules
- Go
- Python
// Cache-Control headers for CDN edge caching
func ServeAsset(w http.ResponseWriter, r *http.Request) {
// Versioned asset: immutable, cache forever
if isVersioned(r.URL.Path) {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
} else {
// Serve stale while revalidating in background
w.Header().Set("Cache-Control", "public, max-age=60, stale-while-revalidate=60")
}
http.ServeFile(w, r, assetPath(r.URL.Path))
}
func PurgeEdgeCache(path string) error {
_, err := cdnClient.Purge(ctx, &cdn.PurgeRequest{Paths: []string{path}})
return err
}
from flask import Flask, send_file, request
app = Flask(__name__)
@app.route("/assets/<path:filename>")
def serve_asset(filename):
resp = send_file(f"static/{filename}")
if is_versioned(filename):
resp.headers["Cache-Control"] = "public, max-age=31536000, immutable"
else:
resp.headers["Cache-Control"] = "public, max-age=60, stale-while-revalidate=60"
return resp
def purge_edge_cache(path: str):
cdn_client.purge(paths=[path])
Gotcha: Set
Cache-Control: stale-while-revalidate=60for content that can be briefly stale. It serves cached content immediately while revalidating in the background — zero latency spike on expiry.