StackPractices
advanced By Mathias Paulenko

Complete Guide to CDN Caching Strategy

CDN caching for web apps and APIs: edge caching, cache keys, headers, invalidation, surrogate keys, stale strategies and multi-CDN setups.

Introduction

A Content Delivery Network caches your content at edge locations close to users. A user in Tokyo requesting a page hosted in Virginia gets it from a Tokyo edge node in 20ms instead of waiting 200ms for an ocean round-trip. That speed is the easy part — the hard part is telling the CDN what to cache and when to let it go. Get cache keys wrong and every request misses; get invalidation wrong and users see week-old prices.

This guide covers the full stack of decisions: how edge caching actually works, which HTTP headers drive it, how to design cache keys that hit, the invalidation toolbox from TTL to surrogate keys, stale-content fallbacks, per-content-type policies, multi-CDN routing, and the metrics that tell you it’s working. For what happens on the application side after the edge, the cache invalidation guide covers the patterns in depth, and the CDN cache invalidation recipe has provider-specific purge walkthroughs.

How CDN Caching Works

User (Tokyo) → CDN Edge (Tokyo) → Origin (Virginia)
                    ↓
              Cache HIT → Return cached response (20ms)
              Cache MISS → Fetch from origin, cache, return (200ms)
  1. User requests a URL (e.g., https://example.com/image.jpg)
  2. CDN checks if the response is cached at the nearest edge node
  3. If cached (HIT): return the cached response immediately
  4. If not cached (MISS): fetch from origin, store at edge, return to user
  5. Subsequent requests for the same URL are served from cache until TTL expires

Most production CDNs add one more hop worth knowing about:

CDN request flow with origin shield: user requests hit the nearest edge node; on a cache miss the edge asks the origin shield, which fans out only one request to the origin, then the response flows back and gets cached at both layers.

The origin shield is a mid-tier cache between edges and your origin. Without it, a cold key means every edge node fetches independently — a hundred regions, a hundred origin requests. With it, the shield collapses them into one.

When a CDN Is the Wrong Tool

Before tuning anything, check whether CDN caching applies to your problem at all. The edge pays off when content is shared and repeated: assets many users fetch, pages that change less often than they get read. It stops paying off when every response is personalized (your hit ratio is ~0% by design), when freshness is measured in milliseconds (a CDN cannot outrun a TTL of zero), or when the origin is already geographically close to all users. Internal APIs inside one VPC and dashboards used by twenty employees get nothing from a global edge network — spend the effort on application-layer caching there instead, the application-level caching guide covers that territory.

When the fit is right — a public site, a global audience, origin capacity worth protecting — the rest of this guide is the playbook for making every cacheable byte count.

Cache Headers

CDNs take their marching orders from HTTP cache headers. Get these right and most of the strategy falls into place — the MDN Cache-Control reference is the canonical spec.

Cache-Control

The Cache-Control header is the primary directive for CDN caching.

Cache-Control: public, max-age=3600
  • public: Any cache (CDN, browser) can store the response
  • private: Only the browser can store the response (not the CDN)
  • max-age=N: Cache for N seconds
  • s-maxage=N: Cache for N seconds in shared caches (CDN) only
  • no-cache: Must revalidate with origin before using cached copy
  • no-store: Do not cache at all
  • must-revalidate: Do not serve stale response after expiry
  • stale-while-revalidate=N: Serve stale while revalidating in background

Two subtleties bite people: s-maxage overrides max-age only for shared caches — it’s how you give the CDN a different lifetime than the browser. And private doesn’t mean “secret”, it means “don’t put this in a shared cache” — user-specific HTML should always carry it.

Setting Headers by Content Type

# nginx configuration

# Static assets: long cache, immutable
location ~* \.(css|js|png|jpg|jpeg|gif|svg|woff2?)$ {
    add_header Cache-Control "public, max-age=31536000, immutable";
}

# HTML pages: short cache, must revalidate
location ~* \.html$ {
    add_header Cache-Control "public, max-age=60, must-revalidate";
}

# API responses: no cache by default
location /api/ {
    add_header Cache-Control "no-store";
}

# Public API responses: short cache
location /api/public/ {
    add_header Cache-Control "public, max-age=60";
}

ETag and Last-Modified

ETag and Last-Modified enable conditional requests. When the CDN’s cached copy expires, it sends a conditional request to the origin with If-None-Match or If-Modified-Since. If nothing changed, the origin returns 304 Not Modified with no body, and the CDN refreshes the TTL for free — a validation round-trip costs bytes, not a full response.

# First request
HTTP/1.1 200 OK
ETag: "abc123"
Last-Modified: Wed, 04 Jul 2026 12:00:00 GMT
Cache-Control: public, max-age=3600
Content: <html>...</html>

# Subsequent request (after TTL expires)
GET /page
If-None-Match: "abc123"
If-Modified-Since: Wed, 04 Jul 2026 12:00:00 GMT

# Origin response
HTTP/1.1 304 Not Modified
Cache-Control: public, max-age=3600
# No body — CDN keeps cached copy

Cache Keys

The cache key decides whether two requests share a cached response. Default is the full URL including query string — which is exactly what you don’t want.

Default Cache Key

Cache key: https://example.com/page?utm_source=email&utm_campaign=summer

Two requests with different utm_source values produce different keys for identical content. Marketing campaigns effectively DDoS your hit ratio — every new parameter value creates a fresh cache copy that only that one URL uses.

Normalizing Cache Keys

Strip parameters that don’t change the response:

// Cloudflare Worker: normalize cache key
addEventListener("fetch", (event) => {
  const url = new URL(event.request.url);

  // Remove tracking parameters
  const trackingParams = ["utm_source", "utm_medium", "utm_campaign",
    "utm_term", "utm_content", "fbclid", "gclid"];
  for (const param of trackingParams) {
    url.searchParams.delete(param);
  }

  // Use normalized URL as cache key
  event.respondWith(fetch(url.toString()));
});

Vary Header

Vary tells the CDN to fold extra request headers into the cache key — necessary whenever the response differs by request headers:

Vary: Accept-Encoding, Accept-Language

This creates separate entries per encoding (gzip, br) and language (en, es). Without it, a Spanish request can get the cached English response — or worse, a gzip-encoded page served to a client that can’t decode it. Vary is powerful and expensive: each dimension multiplies your cache space, so list only headers that actually change the body.

Cache Key Composition

Full cache key = URL + Vary headers + Custom keys

Design the key to include everything that affects the response and nothing that doesn’t. Tracking params out, content-affecting headers in.

Invalidation Strategies

TTL is the floor — everything below targets faster freshness. For the application-side counterpart, the cache invalidation guide goes deep on races and consistency.

TTL-Based Expiration

Set a TTL on cached content. After expiry, the CDN revalidates with the origin. Simple, self-healing, stale-tolerant:

Cache-Control: public, max-age=300

Purge by URL

Explicitly evict a URL when content changes before the TTL:

# Cloudflare purge by URL
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache" \
  -H "Authorization: Bearer {api_token}" \
  -H "Content-Type: application/json" \
  -d '{"files": ["https://example.com/page1", "https://example.com/page2"]}'
# Fastly purge by URL
curl -X POST "https://api.fastly.com/purge/{service_id}" \
  -H "Fastly-Key: {api_key}" \
  -d "https://example.com/page1"

Works for a handful of URLs; falls apart when one entity lives behind fifty of them.

Purge by Surrogate Key

Tag responses with surrogate keys, then purge by key — the provider’s equivalent of the tag-based pattern in Redis. See Fastly’s surrogate key docs:

# Response headers
Surrogate-Key: product-42 products category-5
Cache-Control: public, max-age=3600
# Fastly purge by surrogate key
curl -X POST "https://api.fastly.com/purge/{service_id}" \
  -H "Fastly-Key: {api_key}" \
  -H "Surrogate-Key: product-42"

This purges every response tagged product-42 across the entire network in one call — the only sane way to invalidate “everything that renders this product”.

Purge All

Nuke the whole cache. Sometimes necessary (a bad deploy), always expensive:

# Cloudflare purge everything
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache" \
  -H "Authorization: Bearer {api_token}" \
  -H "Content-Type: application/json" \
  -d '{"purge_everything": true}'

Every request becomes a miss at the same moment — your origin eats the full traffic load cold. Keep it for emergencies, and prefer surrogate keys everywhere else.

Event-Driven Invalidation

Hook the purge into your write path so cache follows data:

import os
import requests

API_KEY = os.environ["FASTLY_API_KEY"]

def update_product(product_id: int, data: dict):
    product = db.products.update(product_id, data)  # db is app-provided

    # Purge CDN cache for this product — after the write
    requests.post(
        "https://api.fastly.com/purge/{service_id}",
        headers={"Fastly-Key": API_KEY},
        data={"surrogate_keys": [f"product-{product_id}", "products"]},
        timeout=5,
    )

    return product

Same rule as application-layer invalidation: purge after the write, not before, or a concurrent request repopulates the edge with pre-update content.

Stale Content Strategies

Between “fresh” and “missing” there’s a third state worth designing for: deliberately serving stale content when it’s better than the alternatives.

stale-while-revalidate

Serve stale while a background fetch updates the cache — users see instant responses and the next request gets fresh data:

Cache-Control: public, max-age=300, stale-while-revalidate=60

For 300s, serve from cache. From 300–360s, serve stale while revalidating. After 360s, fetch synchronously. This flattens the thundering-herd cliff at expiry: only one unlucky request triggers the origin fetch; everyone else rides the stale copy.

stale-if-error

Serve stale when the origin is down — resilience for free:

Cache-Control: public, max-age=300, stale-if-error=86400

If the origin returns 5xx after expiry, the CDN serves the stale copy for up to a day. Your origin can be on fire and the site keeps working on cached content.

Caching Different Content Types

One header policy for everything is the most common CDN mistake. Each content type wants its own balance of freshness and hit ratio.

Static Assets (CSS, JS, Images)

Long TTL plus fingerprinted filenames — new deploy, new URL, no invalidation needed:

Cache-Control: public, max-age=31536000, immutable
<!-- Versioned URLs -->
<link rel="stylesheet" href="/css/main.a1b2c3d4.css">
<script src="/js/app.e5f6g7h8.js"></script>

HTML Pages

Short TTL with revalidation — changes frequently, expensive to generate:

Cache-Control: public, max-age=60, must-revalidate
ETag: "abc123"

API Responses

Cache public APIs briefly; never cache authenticated ones:

# Public product list
Cache-Control: public, max-age=60

# User-specific data
Cache-Control: private, no-cache

# Real-time data
Cache-Control: no-store

Authentication and CDN Caching

The single most dangerous CDN bug: a personalized response cached at the edge and served to someone else. Anything authenticated, user-specific, or carrying Set-Cookie gets private or no-store:

# User profile (private)
Cache-Control: private, no-cache
Set-Cookie: session=abc123; HttpOnly; Secure

# Public product (cacheable)
Cache-Control: public, max-age=3600

For mixed pages — public shell, private fragments — use Edge Side Includes or render the personalized parts client-side, and cache only the public shell.

Multi-CDN Strategy

Multiple CDNs buy you better regional performance, cost leverage, and survivability — at the price of doubled operational complexity. Worth it when a CDN outage is unacceptable or global performance is uneven.

CDN Selection by Geography

Route users to the CDN that performs best in their region:

// DNS-based CDN routing (using a DNS provider like NS1 or Route 53)
const cdnRoutes = {
  "asia": "cdn-asia.example.com",      // strong PoPs in Asia
  "europe": "cdn-europe.example.com",  // strong in Europe
  "default": "cdn-global.example.com", // global fallback
};

CDN Selection by Content Type

Split by workload, not geography:

Static assets (CSS, JS, images) → CDN A (cheaper, longer TTL)
Dynamic content (API, HTML) → CDN B (faster origin, shorter TTL)

Failover

If a CDN goes down, shift traffic to the backup:

# Health check script
if ! curl -s --max-time 5 https://cdn-a.example.com/health; then
  # Update DNS to route to CDN B
  aws route53 change-resource-record-sets \
    --hosted-zone-id Z123 \
    --change-batch '{"Changes":[{"Action":"UPSERT","ResourceRecordSet":{"Name":"cdn.example.com","Type":"CNAME","TTL":60,"ResourceRecords":[{"Value":"cdn-b.example.com"}]}}]}'
fi

DNS failover is slow (TTL-bound, minutes at best) — for faster cutover, run active-active behind a load balancer or Anycast instead of swapping records during an incident.

Monitoring CDN Performance

Key Metrics

  • Cache hit ratio: hits / (hits + misses) — above 90% for static content
  • Origin shield ratio: requests served from shield without hitting origin
  • Edge response time: p50, p95, p99 for edge-served responses
  • Origin response time: p50, p95, p99 for origin fetches
  • Purge latency: time from purge request to effective invalidation
  • Bandwidth: CDN-served vs origin-served — the direct cost signal

Cache Hit Ratio Calculation

Cache Hit Ratio = Cache Hits / (Cache Hits + Cache Misses) * 100

A 95% ratio means 5 out of 100 requests reach the origin. Track it per content type — a global 80% can hide “static assets at 60%” behind “APIs at 95%“:

Content TypeTarget Hit RatioTypical TTL
Static assets99%+1 year
HTML pages80-90%1-5 minutes
Public API60-80%30-60 seconds
Private API0% (no cache)N/A

When hit ratio drops without a deploy, the usual suspects are: a new tracking parameter polluting cache keys, someone adding Vary on a noisy header, or an origin that started emitting no-cache by accident.

The second dashboard worth keeping is per-region latency, not just aggregate. A CDN strategy that looks perfect in a single-region average can still be serving 800ms responses in South America if your DNS or origin shield pools are uneven. If you ship to a global audience, graph edge time p95 by region — the tails live in the regions nobody demos from.

Best Practices

  1. Normalize cache keys at the edge. Strip tracking params in the CDN layer — doing it at the origin means the misses already happened.
  2. Fingerprint static assets, don’t purge them. main.a1b2.css needs zero invalidation infrastructure; main.css needs forever-TTL plus purges on every deploy.
  3. private on anything user-shaped. Cookies, auth headers, user-specific data — when in doubt, private, no-cache. A leaked personalized response is worse than a slow one.
  4. Surrogate keys over URL lists. Tag responses at emit-time so invalidation stays a single call regardless of how many URLs render the entity.
  5. Always-on origin shield. It’s usually a config toggle, and it cuts origin load by an order of magnitude on cold keys.
  6. Budget for stale-if-error before you need it. It’s a one-line directive that turns origin outages into cache hits.

Common Mistakes

  • Cache-Control: public on personalized pages. The classic auth bug — the edge caches your “Hi, Mathias” and serves it to the next visitor.
  • Vary on too many headers. Each dimension multiplies cache space; Vary: User-Agent alone can split your cache into hundreds of useless copies.
  • Purging all on every deploy. Full purges create origin stampede; fingerprinted assets make them unnecessary for static content.
  • Assuming query params don’t matter. They do — by default they’re in the key. ?utm_source=twitter misses ?utm_source=email even for identical pages.
  • no-store on the whole API “just in case”. You lose cacheable public endpoints along with the private ones; mark the private ones private instead.
  • Multi-CDN without a shared invalidation plan. Two CDNs means two purge APIs and twice the staleness surface — agree on surrogate-key conventions first.

Production Checklist

  • Cache-Control headers set for all content types
  • ETag or Last-Modified headers for conditional requests
  • Cache keys normalized (tracking parameters removed)
  • Vary header set for content negotiation (encoding, language)
  • Surrogate keys for targeted purging
  • Event-driven purge on data changes
  • stale-while-revalidate for graceful staleness
  • stale-if-error for origin outage resilience
  • Static assets use fingerprinted filenames
  • Authenticated responses marked private or no-store
  • Cache hit ratio monitored per content type
  • Purge latency monitored
  • Origin shield configured to reduce origin load
  • Failover plan for CDN outage

See Also

Frequently Asked Questions

What is the difference between browser cache and CDN cache?

Browser cache lives on the user's device and cuts requests to the CDN; CDN cache lives on edge servers and cuts requests to the origin. They layer: browser cache serves repeat visits by one user, CDN cache serves first visits by anyone in the region.

Should I cache HTML pages on the CDN?

Yes, with a short TTL (1–5 min). HTML is expensive to generate; even a one-minute edge cache collapses most of the origin load during traffic spikes. Pair must-revalidate with ETags so revalidation stays cheap.

How do I handle user-specific content with a CDN?

Don't cache it — private or no-store. For mixed pages, use Edge Side Includes or client-side rendering for the personalized fragments and cache only the public shell.

What is an origin shield?

A mid-tier cache between edge nodes and your origin. All edges fetch from the shield; only the shield fetches from you. A hundred edge misses become one origin request instead of a hundred.

How long should I cache static assets?

A year (max-age=31536000) — but only with fingerprinted filenames. main.a1b2c3.css can live forever because the next deploy ships main.d4e5f6.css; an unfingerprinted main.css with a yearly TTL is a purging nightmare.

What is the best CDN for my use case?

Depends on priorities: Cloudflare for network breadth and a generous free tier, Fastly for instant purging and surrogate keys, CloudFront for AWS integration, Akamai for enterprise scale. If the choice really matters, benchmark with your real traffic pattern — marketing pages lie.