Skip to main content

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-Control or bypass rules
// 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
}

Gotcha: Set Cache-Control: stale-while-revalidate=60 for content that can be briefly stale. It serves cached content immediately while revalidating in the background — zero latency spike on expiry.