Skip to main content

CDN & Edge

Learning objectives
  • Explain how a request flows through edge PoPs, tiered caches and an origin shield, and what determines a hit
  • Design cache keys, Cache-Control headers and a purge strategy for product pages, static assets and semi-dynamic API responses
  • Protect private content with signed URLs and keep personalised responses out of shared caches
  • Decide when edge compute and dynamic acceleration are worth using for a flash sale or a banking app

TL;DR​

  • A CDN is a globally distributed shared HTTP cache plus a network: it cuts latency (content near users), offloads origin bandwidth, and absorbs attacks.
  • Pull CDNs fetch from origin on a miss (the default); push CDNs serve content you upload in advance (large files, releases).
  • Hit ratio is decided by the cache key: normalise URLs, strip tracking parameters, ignore cookies for static content, and avoid Vary on high-cardinality headers.
  • Prefer versioned, immutable asset URLs (content hash in filename, max-age=31536000, immutable) over purging. Use tag-based purge for content that changes (product pages).
  • An origin shield collapses misses from all edge PoPs into one request per object, protecting the origin during cold starts and purges.
  • Never cache authenticated or personalised responses in shared caches unless the cache key fully includes the identity — send Cache-Control: private, no-store for account data.
  • Dynamic acceleration (TLS termination at the edge, warm origin connections, backbone routing) helps even uncacheable APIs.

Why it matters​

  • Flash sales: a product page with images is ≈ 1–2 MB. One million users loading it in a minute is ≈ 200 Gbps — the origin cannot serve that, the CDN can (see Back-of-the-Envelope Estimation). Even the "sold out" JSON can be micro-cached at the edge for one or two seconds.
  • Catalog and SEO: category and product pages served from the edge render faster, which correlates with conversion.
  • Banking: app bundles, marketing pages and help content belong on a CDN; e-statements and KYC images need signed, short-lived URLs; and account pages must never be shared-cached. The CDN also terminates TLS and runs the WAF, which brings it into security and sometimes PCI DSS scope (see Compliance).
  • Availability: a CDN in front of the origin absorbs volumetric DDoS and can serve stale content when the origin is down (stale-if-error).

Core concepts​

How a request flows​

  1. The user is routed to a nearby PoP via anycast or DNS (see DNS).
  2. The PoP computes the cache key and looks it up. On a hit it serves directly.
  3. On a miss it asks the next tier — often a regional cache or a designated origin shield — and only that tier contacts the origin.
  4. Concurrent misses for the same key are collapsed into one origin fetch (request coalescing), the edge equivalent of single-flight.

Pull vs push​

Pull CDNPush CDN
How content arrivesEdge fetches from origin on first missYou upload content to CDN storage in advance
FreshnessControlled by TTL headers and purgeControlled by your upload/delete process
First requestSlow (miss) unless pre-warmedFast everywhere after upload
Operational effortLow: point CDN at originYou manage uploads and storage
Good forWebsites, APIs, catalogs, imagesLarge files (app installers, video), release artefacts, rarely changing content

Most production setups are pull CDNs with object storage as the origin; "push" today usually means uploading to object storage and pre-warming popular objects before an event.

Cache keys​

The cache key decides whether two requests share a cached response. A default key is roughly scheme + host + path + query string. Tune it deliberately:

  • Normalise the query string: sort parameters, drop marketing parameters (utm_source, fbclid), and ignore unknown ones. Otherwise every campaign link and every attacker's random ?x=123 is a miss that reaches origin.
  • Ignore cookies for static and public content. A session cookie in the key makes every user a separate cache entry (hit ratio ≈ 0).
  • Add only the dimensions that change the response: locale (vi/en), currency, device class if you serve different HTML, Accept-Encoding (handled automatically by most CDNs).
  • Beware Vary. Vary: Accept-Encoding is fine; Vary: User-Agent or Vary: Cookie fragments the cache into thousands of variants. If you return CORS headers that depend on Origin, you must send Vary: Origin or the wrong Access-Control-Allow-Origin gets cached.

TTLs and HTTP caching headers​

Header / directiveMeaning
Cache-Control: max-age=NFresh for N seconds in any cache (browser and CDN)
s-maxage=NOverrides max-age for shared caches (CDN) only
public / privateprivate forbids shared caches; only the user's browser may store it
no-storeDo not store anywhere — use for account and payment data
no-cacheMay store, but must revalidate with origin before each use
immutableContent at this URL never changes; browsers skip revalidation
stale-while-revalidate=NServe stale for up to N seconds while refreshing in the background
stale-if-error=NServe stale for up to N seconds if origin errors
ETag / Last-ModifiedEnable cheap revalidation (304 Not Modified)
CDN-Cache-Control / Surrogate-ControlCDN-targeted directives that browsers ignore (RFC 9213 for the former; the latter is vendor-specific)

Typical policies for an e-commerce site:

# Fingerprinted static asset: app.3f9c2a.js, product-42-800w.a91b.webp
Cache-Control: public, max-age=31536000, immutable

# Product detail HTML or JSON: short at the edge, revalidate in browsers
Cache-Control: public, max-age=0, s-maxage=60, stale-while-revalidate=30, stale-if-error=600
Surrogate-Key: product-42 category-phones

# Flash sale stock badge: micro-cache for one second at the edge
Cache-Control: public, max-age=0, s-maxage=1

# Account, cart, checkout, balance, statements list
Cache-Control: private, no-store

Standard HTTP caching rules also say a shared cache must not reuse a response to a request carrying an Authorization header unless the response explicitly allows it (public, s-maxage or must-revalidate) — another reason to be careful when adding those directives to authenticated APIs.

Purge and invalidation​

  • Versioned URLs (preferred for assets). Put a content hash in the filename at build time. Deploying new code changes the URL; nothing needs purging, old and new versions coexist during rollout, and you can use a one-year TTL.
  • Purge by URL. Simple, but you must know every URL variant (sizes, locales, query strings).
  • Purge by tag / surrogate key. Responses carry tags (product-42, category-phones); one API call purges everything tagged. Ideal when a price change affects the product page, category listing and search page at once. Availability and naming vary by vendor and plan.
  • Soft purge. Mark as stale instead of deleting, so the edge can still serve stale-while-revalidate or stale-if-error rather than sending a burst to origin.
  • Propagation time ranges from sub-second to minutes depending on vendor, and some vendors charge per invalidation. Do not design correctness around purge latency — design so that a few seconds or minutes of staleness is acceptable, and keep truly time-sensitive data (stock, price at checkout) out of long-TTL caches entirely. The checkout always re-prices server-side (see Pricing & Promotions).

Origin shield and tiered caching​

Without a shield, a purge or cold start means every PoP (dozens to hundreds) misses and fetches from origin. With a shield, edges miss to one regional tier, which fetches once. For a global catalog with millions of images, the shield is the difference between "purge is free" and "purge is an origin incident". Place the shield close to the origin's region, and treat it as a capacity tier when you estimate origin load.

Edge compute​

All major CDNs let you run code at the edge (Cloudflare Workers, CloudFront Functions and Lambda@Edge, Fastly Compute, Akamai EdgeWorkers). Useful patterns:

  • Request shaping: normalise cache keys, redirect, rewrite, A/B bucket assignment.
  • Auth at the edge: verify a JWT or signed token before the request ever reaches origin; reject garbage cheaply.
  • Waiting room for flash sales: issue queue tokens at the edge and admit users to origin at a controlled rate (see Flash Sale System).
  • Geo rules: block or route by country (data-residency or sanctions requirements), with the caveat that IP geolocation is approximate.
  • Image transformation: resize and convert formats on the fly with the result cached.

Constraints: tight CPU-time and memory limits, limited or eventually-consistent edge storage, harder debugging and testing, and vendor lock-in. Keep business logic that needs strong consistency (inventory, payments) at origin.

Signed URLs and cookies​

Private objects — e-statements, KYC document images, invoices, paid downloads — can still be served by the CDN or object storage if every URL is signed and short-lived:

  • The application authorises the request, writes an audit record, and returns a URL containing an expiry and a signature over path + expiry (sometimes the client IP). Some CDNs use HMAC tokens with a shared secret; others (for example CloudFront) use public/private key pairs.
  • Keep expiry short (minutes), never put personal data in the path, and serve the object with Cache-Control: private so browsers and intermediaries do not keep it longer than intended.
  • Signed cookies cover many objects at once (for example, all images of one KYC case for a back-office reviewer).

Static vs dynamic acceleration​

Even uncacheable traffic (login, checkout APIs) benefits from a CDN:

  • TLS terminates near the user. The TCP and TLS handshakes (one to three round trips) happen over a short path instead of across the region. For a user 50 ms from origin this can save 100 ms or more on a new connection.
  • Warm, multiplexed connections from edge to origin avoid repeated handshakes.
  • Backbone routing over the provider's network can avoid congested public internet paths.
  • Protocol upgrades: HTTP/2 and HTTP/3 to the client while the origin speaks HTTP/1.1 (see HTTP/1.1, HTTP/2, HTTP/3).
  • Micro-caching (1–5 s) for semi-dynamic, non-personalised responses: category listings, "items left" badges, homepage widgets.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Pull CDNZero upload process, automaticCold misses, origin load on purgeMost web content and APIs
Push / pre-warmedPredictable first-hit performanceUpload pipeline, storage managementLarge files, release day, known sale assets
Long TTL + versioned URLsHighest hit ratio, no purgeRequires build-time fingerprintingJS, CSS, images, fonts
Short TTL + tag purgeFresh content, still offloads originPurge infrastructure, vendor featuresProduct and category pages
Micro-caching (1–5 s)Huge offload for bursty endpointsSeconds of stalenessSale badges, listings, public counters
no-storeNo leakage riskZero offloadAccount, cart, checkout, payments
Edge computeLogic near users, cheap rejectionLimits, lock-in, debuggingAuth checks, waiting rooms, rewrites
Origin shieldProtects origin, raises hit ratioExtra hop on misses, costMany PoPs, large catalogs, frequent purges

In practice​

  • Lock down the origin. Accept traffic only from the CDN (provider IP ranges, mTLS, or a secret header verified at origin); otherwise attackers bypass caching and WAF by hitting the origin directly.
  • Watch the hit ratio by path, plus origin requests per second and bytes. A sudden drop usually means a cache-key change (a new cookie, a new query parameter) shipped by a frontend team.
  • Pre-warm before events. Request the sale product page and images from multiple regions shortly before go-live, and keep the origin shield warm.
  • Sign URLs in Go with an HMAC token scheme (the exact parameter names depend on your CDN's token-auth feature):
package edge

import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/url"
"strconv"
"time"
)

// SignPath returns path?exp=...&sig=... valid until now+ttl.
func SignPath(secret []byte, path string, ttl time.Duration, now time.Time) string {
exp := strconv.FormatInt(now.Add(ttl).Unix(), 10)
sig := mac(secret, path, exp)
return fmt.Sprintf("%s?exp=%s&sig=%s", path, exp, sig)
}

// Verify checks signature and expiry; run it at the edge or origin.
func Verify(secret []byte, path string, q url.Values, now time.Time) bool {
exp, sig := q.Get("exp"), q.Get("sig")
ts, err := strconv.ParseInt(exp, 10, 64)
if err != nil || now.Unix() > ts {
return false
}
want := mac(secret, path, exp)
return hmac.Equal([]byte(sig), []byte(want)) // constant-time compare
}

func mac(secret []byte, path, exp string) string {
h := hmac.New(sha256.New, secret)
h.Write([]byte(path + "\n" + exp))
return base64.RawURLEncoding.EncodeToString(h.Sum(nil))
}
  • Edge-cache incident lesson. Several public incidents have involved a CDN configuration change that caused personalised account pages to be cached and served to other users (Steam's December 2015 incident is a widely cited example). Make "authenticated responses are private, no-store" a default enforced in your API framework, not a per-endpoint choice.

Common pitfalls​

  • Personalised response cached publicly. Symptom: customers see each other's names, orders or balances — a reportable data breach.
  • Session cookie in the cache key. Symptom: hit ratio near zero, origin load unchanged after "adding a CDN".
  • Cache-busting attacks. Random query strings on each request bypass the cache. Symptom: origin overload while CDN shows mostly misses. Fix: ignore unknown parameters in the key, rate-limit at the edge.
  • Long TTL on HTML that references unversioned assets. Symptom: after a deploy, users get new HTML with old JS (or vice versa) and the page breaks.
  • Purge storm. Purging everything before a sale with no shield. Symptom: origin melts at the worst moment.
  • Missing Vary: Origin with dynamic CORS. Symptom: intermittent CORS failures depending on which site populated the cache.
  • Origin not locked down. Symptom: attackers hit origin directly, bypassing WAF and rate limits.
  • Signed URLs with long expiry, shared in chats. Symptom: statements accessible to anyone with the link for days.

Interview angle​

  • Where it appears: any read-heavy consumer system (catalog, media, news feed), flash-sale designs, and banking questions about statements and document delivery.
  • Strong answer covers: what is cached at the edge and with which TTL; how assets are versioned; how content is purged; how the origin is protected (shield, coalescing, lock-down); how private content is served (signed URLs); and an explicit rule that personalised data is no-store.
  • Follow-ups: "A price changed — how fast do users see it?", "How do you serve e-statements securely?", "What happens to origin when you purge?", "Can the CDN help checkout latency even though it is uncacheable?", "What goes in the cache key?"
  • Red flags: caching checkout or account pages, relying on purge for correctness of prices, no answer for origin protection, ignoring the cache key.

Self-check​

1. Why are versioned asset URLs better than purging for JS, CSS and images?

A content hash in the filename means a changed file has a new URL, so the old cached object is simply never requested again. You can use very long TTLs and immutable, there is no purge latency or cost, and old and new versions coexist safely during a rolling deploy. Purge remains for content whose URL must stay stable, such as product pages.

2. What should and should not be in the cache key for a public product page?

Include host, path, normalised and whitelisted query parameters that change the response (variant id, page number), locale and currency if they change content. Exclude session cookies, tracking parameters, and high-cardinality headers such as User-Agent. Personalised elements (cart count, "hello Linh") should be loaded separately from an uncached API.

3. Explain origin shield and request collapsing, and why they matter during a purge.

Request collapsing merges concurrent misses for the same key at one PoP into a single upstream request. An origin shield is a designated mid-tier cache that all edges miss through, so the origin sees at most one request per object regardless of how many PoPs miss. After a purge, every PoP misses at once; without these, origin load multiplies by the number of PoPs and concurrent users.

4. Scenario: design delivery of monthly e-statement PDFs for 5 M bank customers.

Generate PDFs in a batch job into private object storage, keyed by an opaque id. The statement API authenticates the customer, checks ownership, writes an audit record and returns a signed URL valid for a few minutes. The CDN or storage verifies the signature and serves the file with Cache-Control: private. No personal data in the URL, no public bucket, and download events logged for compliance.

5. How can a CDN reduce latency for an uncacheable checkout API?

TLS and TCP handshakes terminate at a nearby PoP instead of the distant origin, saving one to three long round trips on new connections. The edge reuses warm, multiplexed connections to the origin and may route over the provider's backbone. It also offers HTTP/2 or HTTP/3 to the client and absorbs attacks and bots before they reach checkout.

6. What does Cache-Control: public, max-age=0, s-maxage=60, stale-while-revalidate=30 do?

Browsers treat the response as immediately stale and revalidate each time. Shared caches (the CDN) consider it fresh for 60 seconds, and for a further 30 seconds may serve the stale copy while fetching a fresh one in the background. Origin sees roughly one request per key per minute per shield, and users never wait on a refresh within that window.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

Design the edge configuration for an e-commerce flash sale.

  1. List every URL class involved (HTML shell, product JSON, images, stock badge, add-to-cart API, checkout API, account pages) and write the exact Cache-Control header for each.
  2. Define the cache key for the product JSON and the purge mechanism when the price changes 10 minutes before the sale.
  3. Estimate origin requests per second for 1 M users with and without origin shield and 1-second micro-caching of the stock badge, assuming 60 PoPs.
  4. Implement SignPath/Verify above, write a table-driven test for valid, expired and tampered URLs, and run it with go test.

Done looks like: a one-page table of URL class → header → key → purge method, the origin-load estimate, and passing tests.

Further reading​

  • RFC 9111, "HTTP Caching" and RFC 5861, "HTTP Cache-Control Extensions for Stale Content" (rfc-editor.org).
  • RFC 9213, "Targeted HTTP Cache Control" (CDN-Cache-Control).
  • Ilya Grigorik, High Performance Browser Networking (O'Reilly) — latency, TLS and CDN chapters.
  • Official documentation for your CDN: cache keys, tiered caching / origin shield, purge, token authentication (Cloudflare, Fastly, Akamai, Amazon CloudFront).
  • MDN Web Docs, "HTTP caching" guide.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).