Full answer
A CDN (content delivery network) is a set of servers close to users. A request goes to the nearest edge server. If it holds a fresh copy, it answers at once. If not, it asks the origin, stores the response if the rules allow, and answers. This cuts distance, protects the origin from load and can absorb traffic spikes.
The main ideas to explain:
- Cache key. The key normally includes the host and the URL path, and often the query string. If a response varies by header, the server lists the header in
Vary, for exampleVary: Accept-Encoding, and the CDN keeps one copy for each value.Vary: Cookieor a unique query parameter such as a tracking id can split the cache into thousands of entries and kill the hit rate. - Freshness.
max-ageapplies to every cache.s-maxageapplies only to shared caches such as a CDN and overridesmax-agethere. A common design is a short browser time with a longer CDN time:Cache-Control: public, max-age=60, s-maxage=3600. - Stale handling.
stale-while-revalidatelets a cache answer with an old copy while it fetches a new one in the background.stale-if-errorallows old copies when the origin fails. Check that your CDN supports these directives. - Purge. The origin can ask the CDN to delete an entry by URL or by tag after a content change. Purging is the escape hatch for content that changes at unknown times, but it is better to design URLs so that purging is rare, as hashed assets do.
- Private data. Responses with
privateor user-specific data must not be stored in a shared cache.
Check the real behaviour with response headers. Many CDNs add a header that tells whether the response was a hit or a miss. The names differ between providers.
A useful rule: cache by default what is the same for everybody, and be explicit about what is not.
http
HTTP/1.1 200 OK
Cache-Control: public, max-age=60, s-maxage=3600, stale-while-revalidate=30
Vary: Accept-Encoding
ETag: "a1b2c3d4"
Content-Type: text/html; charset=utf-8This is an example response header block. It was not run against a CDN, and the support for each directive depends on the provider.
Key points
- An edge server answers from its cache and goes to the origin only on a miss.
- The cache key is the URL plus headers listed in Vary.
- s-maxage sets the time for shared caches only.
- Purging removes content early. Hashed URLs avoid most purges.
- Never cache user-specific responses in a shared cache.
Common mistakes
- Using Vary: Cookie on a public page and destroying the hit rate.
- Caching a response that sets a session cookie.
- Relying on purge for every release instead of hashed asset names.
- Assuming all CDNs use the same header names and defaults.
Follow-ups
- How would you cache an API response that differs by language?
- What is an origin shield?
- How do you find out why a URL is a cache miss?
Tips
- Explain the cache key first. Most real problems come from it.
- Name the hit and miss headers as something to check for each provider.