CDNs & Edge Delivery
Moving bytes closer to users, and the invalidation cost of doing so.
Questions
Easy / Med / Hard
Your accuracy
A CDN is a globally distributed cache in front of your origin. The win is physics: a user in Sydney fetching from a Sydney edge saves hundreds of milliseconds of round-trip time versus reaching a server in Virginia.
What controls it. Cache-Control is the contract. max-age tells browsers how long to cache; s-maxage overrides it for shared caches like the CDN, which lets you cache aggressively at the edge while keeping browsers on a short leash. stale-while-revalidate serves the stale copy instantly and refreshes in the background, and is the single highest-leverage header for perceived performance. private keeps a response out of shared caches entirely, which is what you want for anything user-specific.
Invalidation. Purging is slow and globally eventually-consistent, so the robust pattern is content-addressed URLs: put a hash in the filename (app.9f2c1b.js) and cache it forever. New deploy, new filename, no purge needed. Reserve purging for the HTML entry point, which you keep on a short TTL.
When the origin is unwell. stale-if-error lets the edge keep serving the last good response when the origin returns a 5xx or times out, which turns a short origin outage into something most users never notice. Error responses need a decision of their own: cache a 404 briefly and a mistaken deploy propagates to every edge, cache it not at all and a crawler walking missing paths reaches your origin on every request.
Knowing whether it works. The number to watch is offload — the share of bytes served without touching the origin — rather than raw hit rate, because a single large uncached asset can dominate origin traffic while barely moving a request-counted percentage. Hit rate falls for a small set of reasons, and they are worth checking in order: a cache key that varies more than it needs to, TTLs shorter than the gap between requests for the same object, and responses the origin marked private or no-store without meaning to.
Beyond static. Modern CDNs cache dynamic responses too, keyed on whatever varies. But the Vary header fragments your cache once per distinct value, so Vary: User-Agent can shred a hit rate. An origin shield adds a mid-tier cache so a miss at fifty edges becomes one origin request instead of fifty.