Skip to content

CDNs: Push vs Pull, Static vs Dynamic, Video Streaming, Cache Hierarchy ​

"The goal of HTTP caching is significantly improving performance by reusing a prior response message to satisfy a current request." — RFC 9111, HTTP Caching, section 1

Summary: A content delivery network (CDN) is a fleet of shared HTTP caches and proxies placed close to users (edge PoPs), arranged in tiers in front of your origin. It answers most requests without touching the origin, and the rest it collapses into as few origin fetches as possible. Whether it helps or hurts depends almost entirely on headers you send: the cache key, the freshness lifetime for browsers and for the CDN, the validators, the purge tags, and what must never be stored. Focus: Edge, PoP, origin, anycast and GeoDNS steering; pull vs push CDN; cache keys and Vary; Cache-Control, max-age, s-maxage, CDN-Cache-Control and Surrogate-Control; revalidation with ETag, If-None-Match and 304; stale-while-revalidate and stale-if-error; request coalescing (collapsed forwarding); tiered caching and origin shield; cache hit ratio vs byte hit ratio; purge by URL, cache tag and surrogate key, soft purge, fingerprinted immutable assets; edge compute (Cloudflare Workers, Lambda@Edge, CloudFront Functions, Fastly Compute) and ESI; WAF, DDoS absorption, signed URLs and cookies, token authentication, hotlink protection, origin pull TLS; HLS, DASH, CMAF, adaptive bitrate, low-latency HLS, live vs VOD; range requests and 206; egress cost; multi-CDN; observability; Cloudflare, Fastly, Akamai, CloudFront, Bunny; Go and Laravel 13 code with tests. Learning goal: For any URL of a system, say which tier answers it, under which cache key, for how long in the browser and at the edge, how it is revalidated, how it is purged and how much origin traffic and egress it costs; then write the headers (Go and Laravel), the purge path and the video packaging rules that make that answer true.

This chapter sits in the Traffic & Scale group of system design and owns the CDN as a system component: the decision to put one in front of a system, the numbers, the headers, the trade-off tables and the worked designs. Siblings hold the mechanics around it: IP, DNS & GeoDNS owns how a user is steered to a PoP (anycast and GeoDNS), Forward vs Reverse Proxies owns the proxy itself, Caching owns application caches (cache-aside, stampedes, Redis), Object Storage & Presigned URLs owns the bucket behind a push CDN, DDoS Protection owns attack mitigation, HTTP evolution owns HTTP/2 and HTTP/3, and Load Balancing owns global load balancing. The Go upload path is in File Uploads, S3 & CDN; token signing primitives are in Password Hashing & Signed Tokens; compression codecs are in Compression. Persian version: /fa/system-design/cdn.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why CDNs exist and what they tradeWhy it exists
RFCs, ESI, HLS and DASH historyWhere it comes from
PoPs, anycast, GeoDNS, originEdge, PoP and origin
Fetch on miss vs upload aheadPull CDN, Push CDN
What makes two requests "the same"Cache key
max-age, s-maxage, CDN-Cache-Control, Surrogate-ControlFreshness headers
ETag, If-None-Match, 304Revalidation
Serving stale on purposestale-while-revalidate and stale-if-error
One origin fetch for a thousand missesRequest coalescing
Browser, edge, shield, originCache hierarchy and origin shield
The two ratios on every dashboardHit ratio and byte hit ratio
Cookies, query strings, devices, encodingsVary and cache key pitfalls
Purge by URL, tag, surrogate key, soft purgeInvalidation
Hashed file names and one-year TTLsStatic assets
Workers, Lambda@Edge, Compute, ESIDynamic content at the edge
WAF, DDoS, signed URLs, tokens, TLS to originSecurity at the edge
HLS, DASH, CMAF, ABR, live vs VODVideo streaming, Low-latency HLS
Range requests, 206, big downloadsLarge files
Two CDNs at once, failoverMulti-CDN
Egress pricing and cache economicsCost
Cloudflare, Fastly, Akamai, CloudFront, BunnyProducts
Header precedence, status words, 52x errorsMechanics
CodeGo, Laravel
Classic production failuresSolving the classic problems
Which setup for which contentChoosing
Monolith to distributed systemIn architecture
A lab you can runLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

What a request meets. Each tier is a cache with its own rules; the first one that has a fresh copy answers.

TierCache type (RFC 9111)Who controls itTypical lifetimeAnswers
BrowserPrivate cacheCache-Control (max-age)0 for HTML, one year for hashed assetsRepeat views by the same user
Edge PoPShared cacheCDN-Cache-Control, Surrogate-Control, s-maxage, CDN rulesSeconds to daysEveryone near that PoP
Shield / upper tierShared cacheSame headers; CDN tiering settingSame as edge, larger storageEvery edge PoP's misses
OriginThe source of truthYour codeNot a cacheOnly what no tier could answer

Pull vs push. How content gets into the CDN.

Pull CDNPush CDN
How content arrivesThe edge fetches from the origin on the first missYou upload to the CDN's storage (or a bucket it reads) ahead of time
OriginAny HTTP serverObject storage (S3, R2, Bunny Storage) or the CDN's own store
First requestA miss per PoP (or per shield)Already a hit at the storage tier
You manageHeaders and purgeUploads, deletes, replication, naming
Best forWebsites, APIs, images, most contentLarge video libraries, software releases, game patches

The header set that decides everything.

HeaderAudienceExampleEffect
Cache-Control: max-age=NBrowser and shared cachespublic, max-age=31536000, immutableFresh for N seconds
Cache-Control: s-maxage=NShared caches onlypublic, max-age=0, s-maxage=300CDN keeps 300 s, browser revalidates
CDN-Cache-Control (RFC 9213)CDNs onlymax-age=300, stale-while-revalidate=60Targeted lifetime; Cloudflare reads it
Surrogate-ControlFastly (removed before the browser)max-age=300Targeted lifetime on Fastly
ETag / Last-ModifiedEvery cache"8bb0a6a4931615f1"Enables 304 revalidation
VaryEvery cacheAccept-EncodingAdds request headers to the cache key
Surrogate-Key / Cache-TagFastly / Cloudflareproduct-42 productsPurge a group with one call
private, no-storeEvery cacheprivate, no-storeNever in a shared cache

Content type to setup.

ContentBrowserEdgeInvalidation
Hashed JS/CSS/fontsOne year, immutableOne yearNone needed: new name per build
ImagesHours to daysDaysVersioned URL or purge by URL
Product/article HTMLmax-age=0, must-revalidateMinutes, SWR + SIEPurge by tag on change
Public JSON API (catalogue)0 to a few secondsSeconds to minutesTag purge or short TTL
Personal pages, carts, accountprivate, no-storeNever storedNot applicable
Video segmentsLongLong, immutableNew URL per rendition
Live manifest0 to a secondHalf the segment durationNatural expiry

Why it exists ​

Without a CDN, every byte of every response crosses the distance between the user and your data centre, and every request costs your origin CPU, connections and egress bandwidth. Three physical facts make that expensive.

  1. Distance is latency. Light in fibre needs tens of milliseconds to cross a continent, and a TLS connection needs at least one round trip before the first byte (see Latency Budgets). A PoP 10 ms away instead of 150 ms away turns the handshake and the first byte from noticeable into invisible.
  2. Popularity is skewed. A small share of URLs gets most of the traffic. Serving the popular part from memory near the user removes most of the origin load at a fraction of the cost.
  3. Peaks are not average. A product launch, a breaking story or a live match produces a burst that the origin was never sized for. A layer of shared caches with request coalescing turns a million simultaneous viewers into a handful of origin fetches.

The CDN also became the natural place for work that every site needs and nobody wants to run: TLS termination close to the user, HTTP/2 and HTTP/3 to the browser, compression, image resizing, a WAF, DDoS absorption, bot management and, more recently, code (edge compute).

Without a CDNWith a CDN
Every request reaches the originMost requests end at the edge; origin sees misses and revalidations
Latency = distance to one regionLatency = distance to the nearest PoP for hits; misses pay both legs
Origin sized for the peakOrigin sized for the miss rate plus collapsed peaks
Egress paid at cloud prices for all bytesOrigin egress for misses only; CDN delivery priced separately
One place to attackAttack traffic absorbed across the CDN network
Content always currentContent can be stale: you must design freshness and invalidation
One copy of the truthMany copies; a wrong header leaks a personal page to strangers

An everyday picture. A CDN is a newspaper distribution network. The printing press (origin) prints once; regional depots (shields) hold bundles; corner kiosks (edge PoPs) hand copies to readers. The kiosk does not phone the press for each reader; it asks the depot when it runs out, and the depot asks the press only once for all kiosks. The front-page date is the freshness lifetime: yesterday's paper may still be sold during a printing strike (stale-if-error) but not forever. A personal letter (your account page) must never go through the kiosk at all. And a recall (purge) is cheap only if every bundle is labelled with what it contains (surrogate keys).

Cache hierarchy: every tier answers what it can and collapses what it cannotBrowser (Tehran)private cacheBrowser (Frankfurt)private cacheBrowser (Singapore)private cacheEdge PoP IKAshared cache, TLS, WAFEdge PoP FRAshared cache, TLS, WAFEdge PoP SINshared cache, TLS, WAFanycast / GeoDNS picks the PoPShield / upper tierone PoP near originrequest collapsingOriginapp + object storagesees shield missesedge miss -> ask shield1 fetch304 on matchCache-Control: max-age (browser)CDN-Cache-Control / s-maxage (CDN)Surrogate-Key / Cache-Tag (purge)Cloudflare Tiered Cache, Fastly shielding,CloudFront Origin Shield, Akamai Tiered Distribution

Three common misunderstandings, up front ​

  1. "Put a CDN in front and the site is fast." A CDN caches only what your headers and rules allow. Cloudflare's documentation says it plainly: "The Cloudflare CDN does not cache HTML or JSON by default." Without the right headers your HTML still travels to the origin for every request; it just takes a detour through a PoP.
  2. "Purge is how you deploy." Purging is a recovery tool, and Akamai's purge documentation warns that "the purge mechanisms shouldn't substitute the time-to-live (TTL) settings". Static assets are deployed by changing their names (fingerprinting); HTML is kept short-lived and purged by tag when the data behind it changes.
  3. "A high cache hit ratio means a low bill." The hit ratio counts requests; the bill counts bytes. A site can hit 95% on small HTML and thumbnails and still miss on the large files that cost money. Watch the byte hit ratio and origin egress, not only the request ratio.

Where it comes from ​

The vocabulary comes from HTTP itself. RFC 9111 (June 2022, which obsoletes RFC 7234) defines the two kinds of cache this page is about: a "shared cache" is "a cache that stores responses for reuse by more than one user", while a private cache is dedicated to one user and usually lives in the browser. Everything else (TTLs, revalidation, stale serving, tags) is built on that spec plus extensions and vendor headers.

DateMilestoneSource
August 2001ESI 1.0 (Edge Side Includes) submitted as a W3C Note: an XML language that "allows content assembly by HTTP surrogates"W3C ESI Language Specification
May 2010RFC 5861 defines stale-while-revalidate and stale-if-errorRFC 5861
August 2017RFC 8216 documents HTTP Live Streaming (HLS) version 7, "a protocol for transferring unbounded streams of multimedia data"RFC 8216
September 2017RFC 8246 defines immutableRFC 8246
ISO/IEC 23009MPEG-DASH: streaming "using existing available HTTP infrastructure (particularly servers and CDNs, but also proxies, caches, etc.)"MPEG DASH page
ISO/IEC 23000-19CMAF, the common segment format; DASH-IF IOP v5 is constrained to itDASH-IF guidelines
June 2022RFC 9110 (semantics: ETag, conditional requests, 206 and 304) and RFC 9111 (caching) replace the 7230-seriesRFC 9110, RFC 9111
June 2022RFC 9213 standardises targeted cache control: CDN-Cache-ControlRFC 9213
May 2026The HLS second-edition draft (draft-pantos-hls-rfc8216bis) carries Partial Segments, Blocking Playlist Reload and preload hints (low-latency HLS)IETF datatracker

RFC 9213 explains why the targeted header exists: "Modern deployments of HTTP often use multiple layers of caching." The browser, a corporate proxy and a CDN should not always share one lifetime, and before 2022 every CDN had its own header for that (Surrogate-Control on Fastly, cache rules on Cloudflare and CloudFront).

The concept catalogue ​

Edge, PoP and origin Must-know ​

In plain words: The origin is your server, the one place where the content is made. A PoP (point of presence) is one CDN site in a city, full of caching proxies. "The edge" is the set of PoPs closest to users. A request goes to a nearby PoP first, and only travels to the origin when the PoP cannot answer.

Common misunderstanding: "The CDN copies my whole site to every PoP." A pull CDN stores only what was requested there recently, bounded by that PoP's cache size and eviction; unpopular files get evicted and are refetched. Each PoP is an independent cache unless tiering ties them together.

Definition: A CDN is a distributed set of shared HTTP caches (reverse proxies operated by a third party) with a request-steering mechanism that maps each client to a PoP. Steering is done by anycast (the same IP prefix announced from every PoP; BGP routing delivers packets to a nearby one, as on Cloudflare) or by DNS (the CDN's authoritative DNS answers with the address of a PoP chosen by the resolver's or client's location, as on Akamai and CloudFront). The mechanics of both are in IP, DNS & GeoDNS.

 1  browser  -> DNS        shop.example CNAME -> shop.example.cdn.net -> 203.0.113.10 (anycast or GeoDNS answer)
 2  browser  -> PoP FRA    TCP + TLS handshake terminates at the edge (10 ms away, not 150 ms)
 3  PoP FRA                compute cache key: https://shop.example/products/42 | ae=br
 4  PoP FRA                lookup: HIT (age 40 s, fresh for 300 s) -> respond, origin untouched
 5  PoP FRA  -> browser    200, Age: 40, CF-Cache-Status: HIT
 6  (miss path)            PoP FRA -> shield -> origin over a pooled, warm TLS connection

Real scenario: a shop in one AWS region serving Europe and Asia; a news site whose traffic spikes 50x on a story; an API with a public catalogue read by mobile apps worldwide; a game studio shipping a 40 GB patch on release day; a SaaS whose origin must not be reachable except through the CDN.

ProductSteeringNetwork namingOrigin types
CloudflareAnycastData centers, lower and upper tiersAny HTTP origin, R2 object storage, Workers
FastlyAnycast and DNSPOPs, shield POPBackends (any HTTP), Fastly Object Storage, Compute
AkamaiDNS based mappingEdge servers, tiered distribution parentsCustom origin, NetStorage
Amazon CloudFrontDNSEdge locations, regional edge caches, Origin ShieldS3, ALB, EC2, MediaPackage, any HTTP
BunnyNot stated in the pages readPoPs, Pull Zones, Storage ZonesAny HTTP, Bunny Storage

The Bunny row summarises Bunny's product and token-authentication pages; its steering method was not stated in them.

Fix / how to use it: point the public hostname at the CDN (CNAME, or the CDN as authoritative DNS), lock the origin so only the CDN can reach it (see Security at the edge), and make every response carry an explicit caching decision. The Go origin below does that per route.

Pull CDN Must-know ​

In plain words: The CDN starts empty. The first time someone near a PoP asks for a URL, the PoP fetches it from your origin, stores it for as long as the headers allow, and serves everyone else from that copy.

Common misunderstanding: "The first user pays the miss, then everyone is fast." The first user per PoP, per cache key, per eviction pays it. With 300 PoPs, 3 encodings and a long tail of URLs, a cold object can be fetched hundreds of times. Tiered caching and an origin shield turn that into one fetch per object.

Definition: A pull (origin-pull) CDN fills its caches lazily: on a miss it forwards the request to the configured origin, applies the response's freshness rules (or overriding CDN rules), stores it under the cache key, and serves it. TTL comes from CDN-Cache-Control, Surrogate-Control, s-maxage, max-age or Expires, in a product-specific order, or from a CDN default when the origin says nothing (Cloudflare: 200, 206 and 301 for 120 minutes; 302 and 303 for 20 minutes; 404 and 410 for 3 minutes; "All other status codes are not cached by default"; Fastly: 2 minutes for a 200 without freshness headers).

Pull: the edge fetches on a missPush: you upload before anyone asksViewerEdge PoPOrigin1 GET2 miss3 200 +headers4 store+ zero upload step, origin decides TTL+ storage follows popularity (LRU)- first viewer per PoP pays the miss- origin must be up and fastHTML, APIs, images, most sitesCI / encoderBucket orstorage zoneEdge PoP1 PUT2 readViewer+ first request is already a hit+ origin can be plain object storage- you manage upload, replication, deletes- storage paid for files nobody readsvideo libraries, releases, game patches
 1  t=0     viewer A (FRA) -> edge FRA   GET /img/hero.webp        MISS
 2  t=0     edge FRA -> origin           GET /img/hero.webp
 3  t=0.12  origin -> edge FRA           200, Cache-Control: public, max-age=86400, ETag "a1"
 4  t=0.12  edge FRA                     store key https://shop.example/img/hero.webp for 86400 s
 5  t=5     viewer B (FRA) -> edge FRA   HIT, Age: 5
 6  t=5     viewer C (SIN) -> edge SIN   MISS (another PoP, another cache) -> origin again unless tiered

Real scenario: a WordPress or Laravel site behind Cloudflare; product images behind CloudFront with an S3 origin; an API gateway's public GET endpoints behind Fastly; a documentation site where all pages are pulled and purged on publish.

Pull detailCloudflareFastlyCloudFrontAkamai
Default TTL without headers120 min for 200/206/301; HTML and JSON not cached by default (extension based)2 min for 200Default TTL of the cache policyProperty caching rule
OverrideCache Rules (Edge TTL)VCL or Compute code, Surrogate-ControlCache policy min/default/max TTLCaching behavior in Property Manager
Respects Set-CookieDoes not cache when Set-Cookie existsConfigurable in VCLForwards cookies only if in policyConfigurable

Fix / how to use it: send explicit headers per route (never rely on defaults), and turn on tiering so a miss in one PoP is usually a hit in the upper tier.

Push CDN Important ​

In plain words: You copy the files into the CDN (or into storage the CDN serves) before anyone asks. The CDN never needs to call your application for them.

Common misunderstanding: "Push means the file is in every PoP." On most products a push uploads into a storage tier (a bucket, a storage zone, NetStorage); the edges still pull from that storage on their own misses. The difference is that the origin is a dumb, durable object store, not your application.

Definition: In a push model the publisher writes objects into CDN-managed or CDN-attached storage (S3 behind CloudFront, Cloudflare R2, Bunny Storage Zones, Akamai NetStorage) as part of a build or ingest pipeline. Object names are usually content-addressed or versioned; deletes and overwrites are the publisher's job. The bucket mechanics (presigned uploads, multipart, consistency) are in Object Storage.

 1  CI       build -> app-3f9a1c2b.js, app-3f9a1c2b.css (hashed names)
 2  CI       PUT s3://assets-bucket/build/assets/app-3f9a1c2b.js  Cache-Control: public, max-age=31536000, immutable
 3  CI       deploy HTML that references the new names
 4  viewer   GET https://cdn.example/build/assets/app-3f9a1c2b.js -> edge MISS -> bucket (not the app) -> HIT afterwards
 5  CI       old files kept for N days so cached HTML that still references them keeps working

Real scenario: a video library where the packager writes segments to object storage; a mobile app release; Laravel's Vite build uploaded to S3 and served through CloudFront with ASSET_URL; a game patch pre-warmed in storage before launch day.

Push targetEdge in frontNotes
Amazon S3CloudFront with Origin Access Control (OAC)Bucket stays private; CloudFront signs its requests
Cloudflare R2Cloudflare cacheSame network as the edge
Bunny Storage ZoneBunny Pull ZoneStorage replicated to regions by configuration
Akamai NetStorageAkamai edgeOrigin type in Property Manager
Fastly Object StorageFastlyS3-compatible

Fix / how to use it: push immutable, content-addressed objects; keep a retention window for old versions; never push mutable names (overwriting app.js in a bucket gives you the pull model's staleness without its purge tooling).

Cache key Must-know ​

In plain words: The cache key is the name under which a response is stored. Two requests with the same key get the same bytes. Everything that changes the bytes must be in the key; everything that does not change the bytes must be out of it.

Common misunderstanding: "The key is the URL." By default it is roughly scheme + host + path + full query string, plus whatever Vary names. That means ?utm_source=mail creates a separate copy, and a key that ignores the cookie your page depends on serves one user's page to another.

Definition: The primary cache key in RFC 9111 is the request method and target URI; Vary adds secondary keys from request headers. CDNs let you shape it: CloudFront cache policies list the headers, cookies and query strings in the key ("The cache key is the unique identifier for every object in the cache, and it determines whether a viewer's HTTP request results in a cache hit"); Cloudflare custom cache keys and Workers cacheKey; Fastly req.hash in VCL or the Compute cache API; Akamai cache ID modification.

 1  GET /p/42?color=red&size=m&utm_source=mail     Accept-Encoding: gzip, deflate, br
 2  GET /p/42?size=m&color=red                       Accept-Encoding: br;q=1, gzip;q=0.8
 3  naive key  1: /p/42?color=red&size=m&utm_source=mail | gzip, deflate, br
 4  naive key  2: /p/42?size=m&color=red | br;q=1, gzip;q=0.8      -> two copies, two misses
 5  normalised  : shop.example/p/42?color=red&size=m | ae=br     -> one copy for both

Real scenario: marketing links multiply the cache footprint by every campaign id; a mobile app adds ?ts=<now> and gets 0% hit ratio; a site varies on User-Agent and stores thousands of copies per URL; a page reads Accept-Language without putting it in the key and serves French to Germans.

Key controlCloudflareFastlyCloudFrontAkamai
Query stringsCache key settings; sort, include or excludeVCL req.url rewrite, querystring functionsCache policy: none, whitelist, allExcept, allCache ID modification
HeadersCustom cache key (header list)Vary plus VCLCache policy header listCache ID by header
CookiesCustom cache key (cookie list)VCLCache policy cookie listCache ID by cookie
Device classDevice type in cache keyVCL logicCloudFront-Is-Mobile-Viewer style headers in the policyDevice characterisation

Fix / how to use it: include only what changes the bytes; normalise the rest (drop marketing parameters, sort parameters, collapse Accept-Encoding to br/gzip/identity). The Go edgecache.DefaultKey and AllowListKey show both strategies, and the CloudFront cache policy below uses an allow-list of two parameters.

json
{
  "Name": "product-pages",
  "Comment": "Only what changes the bytes goes into the cache key",
  "MinTTL": 0,
  "DefaultTTL": 300,
  "MaxTTL": 86400,
  "ParametersInCacheKeyAndForwardedToOrigin": {
    "EnableAcceptEncodingGzip": true,
    "EnableAcceptEncodingBrotli": true,
    "HeadersConfig": { "HeaderBehavior": "none" },
    "CookiesConfig": { "CookieBehavior": "none" },
    "QueryStringsConfig": {
      "QueryStringBehavior": "whitelist",
      "QueryStrings": { "Quantity": 2, "Items": ["page", "sort"] }
    }
  }
}

Freshness headers: Cache-Control, max-age, s-maxage, CDN-Cache-Control, Surrogate-Control Must-know ​

In plain words: The origin tells each cache how long it may reuse a response without asking again. Browsers and CDNs can be told different things.

Common misunderstanding: "no-cache means do not cache." It means "store it, but revalidate before every reuse". The directive that forbids storing is no-store. And private means "browsers only, never a shared cache".

Definition: max-age=N gives a freshness lifetime to every cache; s-maxage=N applies to shared caches only: per RFC 9111, "for a shared cache, the maximum age specified by this directive overrides the maximum age specified by either the max-age directive or the Expires header field". CDN-Cache-Control (RFC 9213) uses the same directives but targets CDN caches, and Cloudflare documents it as "a response header field set on the origin to separately control the behavior of CDN caches from other intermediaries". Fastly reads Surrogate-Control first, then s-maxage, then max-age, then Expires, and strips Surrogate-Control before the response leaves. public allows shared caching even where it would otherwise be refused (for example with Authorization); must-revalidate forbids serving stale once expired.

 1  origin -> CDN    Cache-Control: public, max-age=0, must-revalidate
                     CDN-Cache-Control: max-age=300, stale-while-revalidate=60, stale-if-error=86400
                     Surrogate-Control: max-age=300, stale-while-revalidate=60, stale-if-error=86400
 2  Cloudflare       uses CDN-Cache-Control: fresh 300 s at the edge
 3  Fastly           uses Surrogate-Control, removes it from the response
 4  CDN -> browser   Cache-Control: public, max-age=0, must-revalidate
 5  browser          stores, revalidates on every navigation (cheap 304 thanks to ETag)

Real scenario: HTML that must update within five minutes at the edge but never be stale in the browser; a public API that may be 10 s old at the CDN; a 404 that should be cached for one minute to protect the origin from broken links; an image transform service whose results never change.

DirectiveBrowserShared cache (CDN)Typical use
max-age=NFresh N sFresh N s (unless s-maxage)Static assets
s-maxage=NIgnoredFresh N s, overrides max-ageHTML with short browser life
no-cacheStore, revalidate each timeStore, revalidate each timeAlways-correct pages with cheap 304
no-storeDo not storeDo not storeSecrets, personal data
privateStoreMust not storeAccount pages
publicStoreStore (even with Authorization)Explicitly shareable
must-revalidateNo stale after expiryNo stale after expiryPrices, stock
immutableSkip revalidation while fresh(mostly a browser hint)Fingerprinted assets

Fix / how to use it: split the audiences: short or zero max-age for the browser on HTML, a targeted header for the CDN, and both CDN-Cache-Control and Surrogate-Control when you use more than one CDN. The Go origin's BrowserHTML and EdgeHTML constants are exactly this.

Revalidation: ETag, If-None-Match and 304 Must-know ​

In plain words: When a stored copy expires, the cache does not have to download it again. It asks "I have version X, is it still current?" and the origin answers "yes, keep it" with a tiny response.

Common misunderstanding: "Revalidation is free, so TTL does not matter." A 304 saves bytes, not round trips: the request still travels to the origin, still costs a connection and still runs your handler (unless the handler can check the validator without rendering). On a hot page with a 0 s edge TTL, every request becomes an origin request.

Definition: An ETag is "an opaque validator for differentiating between multiple representations of the same resource" (RFC 9110). The cache sends If-None-Match: "<etag>" (or If-Modified-Since with Last-Modified); the origin answers 304 Not Modified, which per RFC 9110 means the request "would have resulted in a 200 (OK) response if it were not for the fact that the condition evaluated to false". The 304 carries updated headers and no body; the cache refreshes its stored entry from them (RFC 9111 section 4.3.4). If-None-Match uses weak comparison, so W/"x" matches "x".

 1  edge  -> origin   GET /products/42  If-None-Match: "8bb0a6a4931615f1"
 2  origin            render or look up version, compute ETag, compare
 3  origin -> edge    304 Not Modified, CDN-Cache-Control: max-age=300 ..., no body
 4  edge              entry is fresh again for 300 s, Age reset; CF-Cache-Status: REVALIDATED
 5  browser -> edge   GET /products/42  If-None-Match: "8bb0a6a4931615f1"
 6  edge -> browser   304 from cache, origin untouched

Real scenario: a CMS page that changes twice a day but is checked every five minutes; Laravel's cache.headers middleware with etag (Laravel computes an xxh128 hash); S3 objects whose ETag is the stored object's hash; a load balancer that strips ETag when it compresses (a common reason revalidation silently stops working).

ProductRevalidates withStatus word
CloudflareIf-Modified-Since and ETag; revalidation is asynchronous when stale-while-revalidate appliesREVALIDATED, EXPIRED
FastlyConditional fetch on expiry when the object has validatorsX-Cache: HIT after 304
CloudFrontConditional request to origin when the object expiredRefreshHit from cloudfront in X-Cache
AkamaiIf-Modified-Since / If-None-Match to originLogged as revalidation

Fix / how to use it: compute strong ETags from content (or from a version column, cheaper than rendering), answer If-None-Match before doing expensive work, and send the same caching headers on 304 as on 200. Go: origin.NoneMatch; Laravel: $response->setEtag() plus isNotModified($request).

stale-while-revalidate and stale-if-error Must-know ​

In plain words: After the fresh time runs out, a cache may keep serving the old copy for a little while (a) while it fetches the new one in the background, or (b) for a long while if the origin is broken.

Common misunderstanding: "Serving stale is a bug." It is a contract you write: you state how stale is acceptable. A product page that is 60 seconds stale during a refresh is far better than every visitor waiting for the origin, and a page that is a few hours stale is far better than a 502 during an outage.

Definition: RFC 5861: stale-while-revalidate=N "indicates that caches MAY serve the response in which it appears after it becomes stale, up to the indicated number of seconds", and the cache should revalidate in the background. stale-if-error=N "indicates that when an error is encountered, a cached stale response MAY be used to satisfy the request, regardless of other freshness information". Cloudflare, Fastly and CloudFront honour both (CloudFront caps stale serving at the cache policy's maximum TTL).

One object at the edge: CDN-Cache-Control: max-age=300, stale-while-revalidate=60, stale-if-error=86400fresh: HIT, origin untouchedSTALE servedrefresh in backgroundstale only if origin fails(5xx, timeout): STALE-IF-ERROR0 s stored300 s360 s86 700 sRevalidation: the edge sends If-None-Match: "etag"; origin answers 304 Not Modified (headers only) or 200 with a new body.Soft purge moves the object to the stale side at once; hard purge deletes it, so the next request is a MISS.Browsers get Cache-Control: max-age=0, must-revalidate and revalidate every time with the same ETag.
 1  t=0      MISS, stored; CDN-Cache-Control: max-age=300, stale-while-revalidate=60, stale-if-error=86400
 2  t=299    HIT
 3  t=330    STALE: old copy served at once; one background refresh starts (collapsed)
 4  t=331    HIT: refresh came back (200 or 304), entry fresh again
 5  t=4000   origin down; request: STALE-IF-ERROR, old copy served, error hidden from users
 6  t=90000  origin still down, beyond 86400 s: the error reaches users (502/504 or 52x)

Real scenario: a newspaper front page during a database failover; an e-commerce category page during a deploy; Fastly's documentation calls these directives a way for an application to "act like a local backup system"; a price page where stale is not acceptable (then use must-revalidate and a short TTL instead).

BehaviourCloudflareFastlyCloudFront
stale-while-revalidateYes; first request after expiry gets stale, background revalidationYes; Surrogate-Control or Cache-ControlYes; limited by maximum TTL
stale-if-errorYesYes; required alongside soft purge for its best effectYes
Status wordSTALE, UPDATINGX-Cache: HIT with stale state in logsHit while revalidating

Fix / how to use it: always send stale-if-error on content that may be shown slightly old; use stale-while-revalidate on hot HTML and APIs; omit both on prices, stock and anything legally binding. The Go simulator returns STALE and STALE-IF-ERROR outcomes and is tested for both.

Request coalescing (collapsed forwarding) Must-know ​

In plain words: When a thousand people ask for the same missing object at the same moment, the cache sends one request to the origin and makes the other 999 wait for that answer.

Common misunderstanding: "A cache with a TTL protects the origin." At the instant a hot object expires, every concurrent request is a miss. Without coalescing they all go to the origin together: the thundering herd (cache stampede). The TTL created the herd; coalescing removes it.

Definition: Fastly: "Request collapsing is the practice of combining multiple requests for the same object into a single request to origin, and then potentially using the resulting response to satisfy all pending requests." CloudFront Origin Shield consolidates requests for the same object "resulting in as few as one request going to your origin". The same idea inside a program is Go's singleflight: Do makes "sure that only one execution is in-flight for a given key at a time". Coalescing must be disabled for responses that turn out to be uncacheable (Fastly's hit-for-pass), otherwise every queued user waits behind one personal response and then fetches anyway.

 1  t=0.000  1000 requests for /live/score.json arrive at edge FRA; object expired
 2  t=0.000  request #1 becomes the leader: one GET to the shield
 3  t=0.000  requests #2..#1000 wait on the same key (no origin traffic)
 4  t=0.080  shield answers 200 (itself coalescing other PoPs' leaders)
 5  t=0.080  edge stores it and answers all 1000 from the one response
 6  result   origin saw 1 request instead of 1000 x number_of_PoPs

Real scenario: a live score endpoint with a 1 s TTL; a breaking-news page; a release-day download; an application cache in front of a slow query (the same pattern, see Caching and Write Buffering & Coalescing).

ProductCoalescingCaveat
FastlyOn by default for cache misses (VCL and Compute readthrough/simple cache)Uncacheable results must create hit-for-pass
CloudFrontRequests consolidated at edge, regional cache and Origin ShieldPer location; shield makes it near-global
CloudflareTiered Cache funnels misses to one upper tierLower tiers still each ask the upper tier
AkamaiTiered Distribution parents absorb child missesConfigured per property
NGINX (self-run)proxy_cache_lock onPer server

Fix / how to use it: rely on the CDN's coalescing plus a shield; in your own Go caches use singleflight with a detached, bounded context so the first caller's cancellation does not fail everyone (the edgecache.fetchAndStore function does exactly that).

Cache hierarchy: tiered caching and origin shield Must-know ​

In plain words: Instead of every PoP asking your origin, PoPs ask a bigger cache in the middle first, and only that middle cache talks to the origin.

Common misunderstanding: "A shield adds a hop, so it makes things slower." It adds a hop only on edge misses, and that hop runs over the CDN's backbone with warm connections. In exchange, a miss at one of hundreds of edges usually becomes a hit at the shield, and the origin sees one fetch per object instead of one per PoP.

Definition: A cache hierarchy is browser (private) → edge (lower tier) → mid-tier or shield (upper tier) → origin. Cloudflare Tiered Cache "works by dividing Cloudflare's data centers into a hierarchy of lower-tiers and upper-tiers" where "only the upper-tier can ask the origin for content" (topologies: Smart Tiered Cache, which picks the single closest upper tier per origin; Generic Global; Regional Tiered Cache; Custom). Fastly shielding: "visitor requests from across the global network funnel through a single, designated shield POP instead". CloudFront has regional edge caches as a mid-tier by default and Origin Shield as an extra layer in one AWS Region. Akamai Tiered Distribution lets edges "retrieve your cached content from another tier of servers that are closer to your origin server".

 1  viewer SIN -> edge SIN          MISS
 2  edge SIN   -> upper tier FRA    HIT (filled 3 min ago by edge LHR's miss)
 3  edge SIN                         stores, serves: X-Cache: shield HIT, edge-sin MISS
 4  viewer SIN2 -> edge SIN          HIT
 5  origin                           saw one request (from the shield) for all PoPs

Real scenario: an origin in one region with a global audience; a video library where each segment would otherwise be fetched by every PoP; an origin with a strict request budget (a legacy CMS, a paid API); during an incident, a shield is also the single place that can serve stale for everyone.

ProductMid-tier nameHow to enableChoose location
CloudflareTiered Cache (upper tiers)Smart Tiered Cache toggle; Regional and Custom on higher plansAutomatic, region hint, or custom
FastlyShield POPChoose a shield per backendClosest POP to the origin
CloudFrontRegional edge caches (always), Origin Shield (opt-in)Origin settingAWS Region near the origin
AkamaiTiered DistributionProperty Manager behaviorTiered Distribution map
BunnyOrigin ShieldPull Zone settingShield region

Fix / how to use it: enable a shield near the origin for every pull origin; then measure origin requests, not only edge hit ratio. The Go test TestShieldCollapsesTwoEdgesToOneOriginFetch shows two cold edges and one origin fetch; the lab simulation shows the shield cutting origin fetches from 133,357 to 72,222 for the same workload.

Cache hit ratio and byte hit ratio Must-know ​

In plain words: Hit ratio is the share of requests the CDN answered from cache. Byte hit ratio is the share of bytes it answered from cache. They can be very different numbers.

Common misunderstanding: "95% hit ratio, the origin is fine." If the 5% misses are the large files, they may be most of your bytes, your origin egress and your bill. Also, a hit ratio measured at the edge says nothing about how many of the misses the shield absorbed: measure origin offload too.

Definition: Cache hit ratio (CHR) = cached responses / all cacheable responses (product definitions differ on whether REVALIDATED, STALE or uncacheable DYNAMIC responses count). Byte hit ratio = bytes served from cache / all bytes served. Origin offload = 1 − origin requests / edge requests (or the byte version). CloudFront defines a higher cache hit ratio as "a higher proportion of viewer requests that result in a cache hit".

 1  day: 10,000,000 requests, 40 TB served
 2  HTML and thumbnails: 9,500,000 requests, 4 TB, 98% hits
 3  originals and downloads: 500,000 requests, 36 TB, 40% hits
 4  hit ratio      = (9,310,000 + 200,000) / 10,000,000 = 95.1%
 5  byte hit ratio = (3.92 TB + 14.4 TB) / 40 TB        = 45.8%
 6  origin egress  = 0.08 + 21.6 = 21.7 TB/day           <- this is the bill

Real scenario: an image site whose request hit ratio looks great while originals are evicted from small PoPs; a software download whose Range requests miss because the CDN does not cache partial content; a site that counts DYNAMIC (never cacheable) as misses and chases a number it cannot change.

MetricCloudflareFastlyCloudFront
Request statusCF-Cache-Status: HIT, MISS, EXPIRED, STALE, BYPASS, REVALIDATED, UPDATING, DYNAMIC, NONE/UNKNOWNX-Cache, X-Cache-Hits, real-time statsX-Cache: Hit, RefreshHit, Miss, Error from cloudfront
Hit ratioCache analyticsStats API (hit ratio)Cache statistics report
Byte offloadBandwidth savedStats (bandwidth)Bytes from origin vs total

The CloudFront X-Cache value list is widely observed but was not in the CloudFront pages fetched for this chapter; treat it as practice, not citation.

Fix / how to use it: report three numbers per content class: request hit ratio, byte hit ratio, origin requests per second. The SQL below computes the first two from CDN logs loaded into PostgreSQL; the Go edgecache.Stats exposes the same numbers.

sql
-- CDN logs (Cloudflare Logpush, Fastly real-time logging, CloudFront standard logs) loaded into one table.
CREATE TABLE cdn_requests (
    ts            timestamptz NOT NULL,
    pop           text        NOT NULL,
    host          text        NOT NULL,
    path          text        NOT NULL,
    status        smallint    NOT NULL,
    cache_status  text        NOT NULL,   -- HIT, MISS, EXPIRED, STALE, REVALIDATED, UPDATING, BYPASS, DYNAMIC
    bytes_sent    bigint      NOT NULL,
    origin_ms     integer                 -- null when the origin was not contacted
);
CREATE INDEX ON cdn_requests (ts);

-- Hourly request hit ratio, byte hit ratio, origin load and edge 5xx for cacheable traffic.
SELECT date_trunc('hour', ts)                                                   AS hour,
       round(avg((cache_status IN ('HIT','STALE','REVALIDATED','UPDATING'))::int), 3) AS hit_ratio,
       round(sum(bytes_sent) FILTER (WHERE cache_status IN ('HIT','STALE','REVALIDATED','UPDATING'))::numeric
             / nullif(sum(bytes_sent), 0), 3)                                    AS byte_hit_ratio,
       count(*) FILTER (WHERE origin_ms IS NOT NULL)                             AS origin_requests,
       count(*) FILTER (WHERE status >= 500)                                     AS edge_5xx
FROM cdn_requests
WHERE ts > now() - interval '24 hours'
  AND cache_status <> 'DYNAMIC'
GROUP BY 1
ORDER BY 1;

-- The keys that cost the most origin bytes: candidates for longer TTLs, a shield or fingerprinting.
SELECT host, path, count(*) AS misses, sum(bytes_sent) AS bytes
FROM cdn_requests
WHERE ts > now() - interval '24 hours' AND cache_status IN ('MISS','EXPIRED')
GROUP BY host, path
ORDER BY bytes DESC
LIMIT 20;

Vary and cache key pitfalls Important ​

In plain words: Vary tells caches "this response depends on these request headers too". Used carefully it keeps the right version per client; used carelessly it shatters the cache into thousands of copies or, missing, serves the wrong version.

Common misunderstanding: "Vary: User-Agent is the safe way to serve mobile pages." There are tens of thousands of distinct User-Agent strings; the cache stores one copy per string, so the hit ratio collapses. Normalise to a device class at the edge and vary on that (or use responsive pages).

Definition: RFC 9111: when a stored response has Vary, "the cache MUST NOT use that stored response without revalidation unless all the presented request header fields nominated by that Vary field value match those fields in the original request", and Vary: * always fails to match. Cookies are a special case: most CDNs do not cache responses with Set-Cookie and, by default, do not put request cookies in the key, so a page that reads a cookie must either vary on a normalised value or not be cached.

 1  origin    Vary: Accept-Encoding, User-Agent
 2  edge      key = url + "gzip, deflate, br" + "Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 ...)"
 3  edge      next iPhone with a minor version bump -> new key -> MISS
 4  result    one URL, 4,000 stored copies, 3% hit ratio
 5  fix       edge computes device=mobile|desktop, key = url + ae=br + device=mobile; Vary: Accept-Encoding only

Real scenario: compression: an origin that returns gzip to one client and identity to another without Vary: Accept-Encoding poisons the cache for clients that cannot decompress; a language switch read from Accept-Language; an A/B test cookie read by the HTML; a CDN that caches a page with Set-Cookie because a "cache everything" rule overrides the default.

Request inputSafe approachDangerous approach
Accept-EncodingVary: Accept-Encoding, CDN normalises to br/gzip/identityNo Vary while serving different encodings
Query stringsAllow-list or sorted, marketing params droppedFull raw query in the key
CookiesKey on one normalised cookie, or bypass when a session cookie existsIgnore cookies while the page depends on them
DeviceDevice class header in the keyVary: User-Agent
LanguagePath prefix /de/, /fr/Vary: Accept-Language on raw values
AuthorizationNot shared; privatepublic on personal responses

Fix / how to use it: prefer URLs that carry the variation (/de/, ?page=2) over headers; keep Vary to Accept-Encoding; strip cookies from cacheable routes (the Laravel routes remove the session middleware for exactly this reason). Web cache poisoning (an unkeyed header that changes the response) and web cache deception (a personal page cached because its URL looks static, such as /account/x.css) are both cache-key bugs; see OWASP Top 10.

Invalidation: purge by URL, cache tag, surrogate key and soft purge Must-know ​

In plain words: Purging tells the CDN to stop serving a stored copy before its TTL ends. You can purge one URL, everything carrying a tag, a prefix, a hostname or everything.

Common misunderstanding: "Purge is instant and global, so long TTLs are free." Purges propagate in seconds on modern CDNs, but they also turn the next request everywhere into a miss: purge everything on a busy site and the origin receives the whole working set at once. A soft purge, a shield and coalescing make that survivable.

Definition: Purge by URL removes one cache key (all its variants). Purge by tag removes every object whose response carried that tag: Fastly Surrogate-Key (space separated), Cloudflare Cache-Tag (comma separated, the aggregate header "cannot exceed 16 KB"), Akamai cache tags (each up to 128 characters), CloudFront invalidation by cache tags. A soft purge marks objects stale instead of deleting them: per Fastly, "Stale objects remain available to use in some circumstances while Fastly fetches a new version from origin, unlike objects invalidated by a hard purge". Akamai calls the two methods invalidate and delete.

 1  t=0    product 42 price changes; DB COMMIT
 2  t=0    app enqueues PurgeCdnTags(["product-42", "category-kitchen"]) after commit
 3  t=0.2  worker: POST https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache {"tags": [...]}
 4  t=0.2  worker (Fastly): POST https://api.fastly.com/service/{SID}/purge/product-42  Fastly-Soft-Purge: 1
 5  t=1    all PoPs: objects tagged product-42 are stale (soft) or gone (hard)
 6  t=1.1  next request per PoP: STALE + background refresh (soft) or MISS (hard), coalesced at the shield

Real scenario: a price change purges the product page, its category pages and the search results that list it; an editor fixes a typo in an article; a legal takedown that must be gone now (hard purge); a deploy that changed HTML (do not purge assets: they have new names).

Purge typeCloudflareFastlyCloudFrontAkamai
Single URLYes (recommended method)PURGE request or APIInvalidation pathFast Purge by URL/ARL
TagCache-TagSurrogate-KeyInvalidation by cache tagsCache tags
Prefix / wildcardPurge by prefixVia tagsPath with *By CP code or directory (ECCU)
Hostname / everythingHostname, purge everythingPurge all (never soft)/*CP code
Soft purgeNot named so; stale serving via SWRFastly-Soft-Purge: 1NoInvalidate method

Fix / how to use it: tag every response with the ids of the entities it shows; purge after the transaction commits, from a queue with retries (purges are idempotent); prefer soft purge; never use purge-everything as a deploy step. Laravel: PurgeCdnTags + CdnPurger; Go: edgecache.PurgeTag and SoftPurgeTag.

Static assets: fingerprinting, versioned assets and immutable Must-know ​

In plain words: Put a hash of the file's content in its name. When the file changes, its name changes, so you can tell every cache to keep each name forever.

Common misunderstanding: "?v=2 is the same as fingerprinting." A query-string version works only if every cache keeps the query in the key, and you must remember to bump it. A content hash in the path is automatic, works with every cache, and lets old and new versions coexist during a rolling deploy.

Definition: A versioned (fingerprinted) asset name is derived from the content (app-3f9a1c2b.js). The response carries Cache-Control: public, max-age=31536000, immutable; RFC 8246 says immutable means "a client never needs to revalidate a cached fresh resource to be certain it has not been modified". The HTML that references the names stays short-lived. CloudFront's invalidation guide recommends the same: "If you want to update your files frequently, we recommend that you primarily use file versioning". Laravel's Vite integration builds hashed names and a manifest; @vite reads public/build/manifest.json to print them, and ASSET_URL makes the printed URLs point at the CDN.

 1  build    resources/js/app.js -> public/build/assets/app-3f9a1c2b.js; manifest.json maps the two
 2  deploy   upload assets first, then switch HTML (old HTML still finds old files)
 3  browser  GET /build/assets/app-3f9a1c2b.js -> 200, max-age=31536000, immutable
 4  reload   browser does not even send If-None-Match while fresh (immutable)
 5  release  app-7c01e9aa.js: new URL, new cache entry; the old one ages out by LRU

Real scenario: a React or Vue bundle; web fonts (which also need CORS headers); images processed by Vite (Vite::asset); a Go server embedding assets and naming them by hash (the origin.AddAsset function).

Asset strategyCache-ControlPurge neededRisk
Hash in file namemax-age=31536000, immutableNoMust keep old files during rollout
?v= query versionLongNo, if the key includes the queryBreaks when a cache drops queries
Same name, short TTLmax-age=300SometimesUsers run mixed versions for 5 minutes
Same name, long TTLmax-age=86400Yes, every deployStale JavaScript for a day if purge fails

Fix / how to use it: fingerprint everything the HTML references; set immutable on those paths only (the NGINX snippet and the Go origin do it per route); keep the manifest itself out of public serving.

conf
# NGINX on the origin: hashed build output is immutable, the manifest is not served.
location /build/assets/ {
    add_header Cache-Control "public, max-age=31536000, immutable" always;
    try_files $uri =404;
}
location = /build/manifest.json {
    deny all;
}

Dynamic content at the edge: edge compute and ESI Important ​

In plain words: Some pages are mostly the same for everyone with a small personal part. You can run a little code in the PoP to assemble or tweak the page, or cache the shared parts and fill in the rest.

Common misunderstanding: "Edge compute makes the database close to the user." The code runs in the PoP; your data usually does not. An edge function that calls a database in one region on every request adds a hop rather than removing one. Edge compute wins when the decision can be made from the request (country, cookie, header, A/B bucket), from a cache, or from edge storage.

Definition: Edge compute products run customer code inside the CDN: Cloudflare Workers (JavaScript, TypeScript, Python, Rust and WebAssembly), Fastly Compute ("Fastly's edge computing platform"), CloudFront Functions (lightweight viewer request/response code with "submillisecond startup times") and Lambda@Edge (Node.js or Python functions authored "in one AWS Region, US East (N. Virginia)" and replicated to AWS locations), Akamai EdgeWorkers. ESI (Edge Side Includes) is the older approach: the cached page contains <esi:include src="/fragment"/> tags and the surrogate fetches and caches each fragment separately; Akamai enables it per property (also only for content carrying Edge-control: dca=esi). Even without code, a CDN accelerates uncacheable API traffic: TLS and TCP terminate near the user, and the PoP reuses warm, long-lived connections to the origin over the CDN backbone.

 1  viewer (DE)  -> edge        GET /products/42?utm_source=mail  Cookie: ab=B
 2  Worker                      strip utm_*, region = eu (from request.cf.country), bucket = B
 3  Worker                      cache key = https://shop.example/products/42#region=eu (3 regions, not per user)
 4  edge cache                  HIT for region eu -> HTML with EU prices
 5  Worker                      no session cookie -> cacheable; with session -> pass to origin uncached
 6  (ESI variant)               page HIT + <esi:include src="/fragments/cart-count"/> fetched per user, uncached

Real scenario: country-based price or legal banners; A/B tests with a handful of buckets; redirects and URL rewrites; bot detection; header normalisation before the cache key; image format negotiation; an authenticated API where only the JWT check moves to the edge.

NeedCloudflareFastlyAWSAkamai
Rewrite, redirect, header at viewer requestWorkers, RulesVCL, ComputeCloudFront FunctionsProperty rules, EdgeWorkers
Full request handling with network callsWorkersComputeLambda@EdgeEdgeWorkers
Fragment assemblyWorkersVCL or Compute codeLambda@EdgeESI
Edge stateKV, Durable Objects, R2KV Store, Config StoreDynamoDB (regional)EdgeKV

Fix / how to use it: personalise on few buckets (region, device class, experiment arm), never per user; bypass the cache entirely when a session cookie exists; keep edge code free of origin calls on the hot path. The Worker below normalises the key and buckets by region; cacheKey is an Enterprise feature on Cloudflare (other plans use the Cache API). Event-driven serverless beyond the CDN is in Serverless & Event-Driven Compute.

js
// Cloudflare Worker: normalise the cache key and personalise by region
// without fragmenting the cache per user.
const DROP = /^(utm_|fbclid$|gclid$)/;
const EU = new Set(["DE", "FR", "NL", "IT", "ES"]); // pricing regions, not the full EU list

export default {
  async fetch(request) {
    const url = new URL(request.url);

    // 1. Remove marketing parameters and sort the rest: one object, not thousands.
    const kept = [...url.searchParams].filter(([k]) => !DROP.test(k)).sort();
    url.search = new URLSearchParams(kept).toString();

    // 2. Coarse personalisation: three price regions -> three cache entries.
    const country = request.cf?.country ?? "XX";
    const region = country === "US" ? "us" : EU.has(country) ? "eu" : "row";

    // Never cache for signed-in users.
    if ((request.headers.get("Cookie") ?? "").includes("session=")) {
      return fetch(request);
    }

    const originReq = new Request(url, request);
    originReq.headers.set("X-Price-Region", region);
    const response = await fetch(originReq, {
      cf: {
        // cacheKey is an Enterprise feature; on other plans use the Cache API.
        cacheKey: `${url.toString()}#region=${region}`,
        cacheTtlByStatus: { "200-299": 300, 404: 60, "500-599": 0 },
      },
    });
    const out = new Response(response.body, response);
    out.headers.set("Cache-Control", "public, max-age=0, must-revalidate");
    return out;
  },
};

Security at the edge Must-know ​

In plain words: Because every request passes through the CDN, it is the cheapest place to block bad traffic, check who may download a file, and encrypt traffic. It only works if attackers cannot bypass it and reach the origin directly.

Common misunderstanding: "The CDN protects my origin." Only if the origin accepts traffic from the CDN alone. If the origin's address leaks (old DNS records, mail headers, a subdomain not behind the CDN), attackers go straight to it. Lock the origin with mTLS from the CDN, private bucket access or IP allow-lists, and use full TLS to the origin.

Definition: Edge security covers: a WAF (rules on requests before the cache; Cloudflare WAF, Fastly Next-Gen WAF, AWS WAF on CloudFront, Akamai App & API Protector); DDoS absorption (the anycast network spreads volumetric attacks; mechanics in DDoS Protection); signed URLs and signed cookies (CloudFront: a signed URL "includes additional information, for example, an expiration date and time" in a canned or custom policy; signed cookies cover many files, which suits HLS); token authentication (Bunny: Basic with MD5 expiry and optional IP, Advanced with SHA256, geo restrictions and directory tokens); hotlink protection (Cloudflare: it "prevents your images from being used by other sites"); TLS at the edge (the CDN's certificate for your hostname) and origin pull TLS (encryption and authentication on the CDN-to-origin leg: Cloudflare Full (strict) plus Authenticated Origin Pulls, which "helps ensure requests to your origin server come from the Cloudflare network"; CloudFront origin protocol policy HTTPS only and Origin Access Control for S3).

 1  viewer   -> edge     GET /video/abc/720p/seg_42.m4s?exp=1800003600&prefix=%2Fvideo%2Fabc%2F&sig=...
 2  edge WAF             rules pass; rate limit per IP ok
 3  edge                 verify HMAC over prefix + exp, check exp > now -> valid (403 if not)
 4  edge cache           key ignores exp/sig (all viewers share the segment) -> HIT
 5  edge     -> origin   (on miss) TLS with client certificate (mTLS); origin rejects anything without it

Real scenario: paid video courses (prefix tokens or signed cookies so every segment is authorised); invoices and exports (short-lived signed links); a leaked origin IP being hammered; image hotlinking by other sites; an S3 bucket that must never be public.

ControlCloudflareFastlyCloudFrontAkamaiBunny
WAFCloudflare WAFNext-Gen WAFAWS WAFApp & API ProtectorShield/WAF features
Signed accessWAF HMAC rules, WorkersVCL or Compute token checkSigned URLs and signed cookiesToken authenticationToken Authentication
HotlinkHotlink Protection (gif, ico, jpg, jpeg, png)VCL Referer checkAWS WAF Referer ruleReferrer checkingAllowed referrers
Origin lockAuthenticated Origin Pulls (mTLS), Full (strict)mTLS to backend, shared secret headerOAC for S3, custom header + HTTPSSite Shield, mTLSOrigin headers, IP lists

Fix / how to use it: sign URLs or cookies for paid or private content and keep the signature parameters out of the cache key; sign a path prefix for streams; lock the origin; use full, verified TLS on the origin leg. Go: signedurl.Signer (HMAC with expiry and prefix scope); Laravel: URL::temporarySignedRoute with the signed middleware, and Storage::temporaryUrl for presigned S3 URLs.

Video streaming: HLS, DASH, CMAF, adaptive bitrate, live and VOD Must-know ​

In plain words: A video is cut into small files (segments) of a few seconds each, at several qualities. A text file (the manifest or playlist) lists them. The player downloads segments one after another and picks the quality that the network can sustain right now. To a CDN, a video is just many small, immutable files plus a frequently changing list.

Common misunderstanding: "Streaming needs a special streaming server." HLS and DASH were designed for plain HTTP caches. RFC 8216 HLS and MPEG-DASH run on ordinary CDNs; the special parts are packaging (cutting and describing segments) and, for live, keeping the manifest fresh.

Definition: HLS (RFC 8216) has a multivariant (master) playlist that "provides a set of Variant Streams, each of which describes a different version of the same content", and media playlists listing segments: "The duration of each Media Segment is indicated in the Media Playlist by its EXTINF tag", EXT-X-TARGETDURATION "specifies the maximum Media Segment duration", and EXT-X-ENDLIST "indicates that no more Media Segments will be added". DASH (ISO/IEC 23009-1) describes the same with an XML MPD (Media Presentation Description). CMAF (ISO/IEC 23000-19) is a common fragmented MP4 segment format so one set of segments serves both HLS and DASH; DASH-IF IOP v5 is "further constrained to deliver media formatted according to the MPEG CMAF Specification". Adaptive bitrate (ABR): the player estimates throughput and buffer and chooses the next segment's rendition. Packaging (just-in-time at an origin packager such as AWS Elemental MediaPackage, or ahead of time into storage) produces segments, init segments and manifests from encoded renditions. VOD content is a finished presentation (EXT-X-PLAYLIST-TYPE:VOD, ends with EXT-X-ENDLIST); live content is a sliding window whose media playlist changes every segment.

Video: encode once, package once (CMAF), cache segments long and live manifests shortEncoderladder: 360p720p, 1080pPackagerCMAF fMP4 partsHLS + DASH manifestsOrigin(or objectstorage for VOD)Shieldcollapsessegment missesEdge AEdge BPlayer 1720p -> 1080pPlayer 21080p -> 360psegment seg_00042.m4s: Cache-Control: public, max-age=31536000, immutable (never changes once published)live media playlist index.m3u8: max-age = half the target duration (2 s for 4 s segments)VOD playlist: long TTL; ends with #EXT-X-ENDLISTLow-latency HLS: partial segments (EXT-X-PART), blocking reload (_HLS_msn), preload hintsAdaptive bitrate: the player measures throughput and buffer, then picks the next segment renditionMulti-CDN: the player or a steering service switches CDN per session or per segment
 1  player -> edge  GET /v/abc/master.m3u8           (VOD: long TTL; live: short)
 2  player          choose 720p from BANDWIDTH/RESOLUTION and measured throughput
 3  player -> edge  GET /v/abc/720p/index.m3u8       (live: max-age=2 for 4 s segments)
 4  player -> edge  GET /v/abc/720p/init.mp4, seg_100.m4s, seg_101.m4s   (immutable, HIT for everyone after the first)
 5  player          throughput drops -> next request is /v/abc/360p/seg_102.m4s
 6  live edge       index.m3u8 expires every 2 s; coalescing makes it one shield fetch per PoP per 2 s

Real scenario: a course platform (VOD, signed cookies, multi-bitrate); a sports stream (live, millions of concurrent viewers on the same segments); a news channel (live with DVR window); user uploads transcoded to a ladder; YouTube- and Netflix-scale designs are worked in Case Study: YouTube and Case Study: Netflix.

ObjectChanges?Cache-ControlEdge behaviour
Segment .m4s / .tsNever after publishpublic, max-age=31536000, immutableLong-lived, high byte share
Init segment init.mp4Per rendition versionLong, immutableTiny, very hot
VOD media playlistNeverLong (a day or more)Hit after first fetch
Live media playlistEvery segmentmax-age about half the target durationCollapsed refresh per PoP
Multivariant playlistRarelyMinutesHit
DASH MPD (live, type="dynamic")PeriodicallyShort, as with live playlistsCollapsed refresh

Fix / how to use it: package once into CMAF and publish both HLS and DASH manifests; cache segments forever and live manifests briefly; sign the stream by prefix or cookie; put a shield in front of the packager. Go: the hls package renders both playlist kinds and returns the right Cache-Control for each object.

Low-latency HLS Good to know ​

In plain words: Normal live HLS is 10 to 30 seconds behind real time because players wait for whole segments. Low-latency HLS publishes small parts of the segment as they are encoded and lets the player ask "give me the playlist as soon as part N exists".

Common misunderstanding: "Shorter segments are the same thing." Very short segments increase request rate and overhead and hurt ABR. The second-edition draft says it directly: "A shorter Target Duration reduces latency but also reduces available buffer, handicaps adaption and increases delivery overhead, increasing the likelihood of playback stall." LL-HLS keeps normal segments and adds parts.

Definition: The HLS second-edition draft (draft-pantos-hls-rfc8216bis, May 2026) adds "Partial Segments, Blocking Playlist Reload and preload hinting to enable playback at a reduced delay from live". EXT-X-PART-INF declares the part target duration; EXT-X-PART lists parts; EXT-X-SERVER-CONTROL advertises CAN-BLOCK-RELOAD=YES and PART-HOLD-BACK; the client requests index.m3u8?_HLS_msn=M&_HLS_part=P and the server "MUST defer responding" until that segment or part exists; EXT-X-PRELOAD-HINT names the next part so the player can request it before it is complete. Apple's developer documentation for LL-HLS could not be fetched for this chapter; the draft is the cited source. LL-DASH achieves similar latency with CMAF chunks and chunked transfer.

 1  #EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES,PART-HOLD-BACK=3.0
 2  #EXT-X-PART-INF:PART-TARGET=1.0
 3  #EXTINF:4.000,  seg_100.m4s
 4  #EXT-X-PART:DURATION=1.000,URI="seg_101.part0.m4s"
 5  #EXT-X-PRELOAD-HINT:TYPE=PART,URI="seg_101.part1.m4s"
 6  player -> edge   GET index.m3u8?_HLS_msn=101&_HLS_part=1   (held open until part 1 exists)

Real scenario: live betting and sports where 20 s delay spoils the experience; live auctions; interactive streams with chat.

ConcernClassic live HLSLow-latency HLS
Glass-to-glass delayRoughly 3 segment durations or moreA few seconds
Playlist requestsPolling every target durationBlocking reload, held at the edge
CDN requirementStandard cachingEdge must hold blocking requests and cache query-specific playlist URLs briefly
Origin loadLowHigher; shield and coalescing essential

Fix / how to use it: use LL-HLS only where latency is a product requirement; confirm the CDN supports blocking playlist reload with the _HLS_ query parameters in the cache key; keep segment caching identical to normal HLS.

Large files and range requests Important ​

In plain words: A client can ask for a slice of a file ("bytes 0 to 1 MB"). Video players, download managers and resumable downloads do this all the time. The CDN must cache slices or the whole file sensibly, or every slice goes to the origin.

Common misunderstanding: "206 responses are not cacheable." They are (Cloudflare caches 206 by default for 120 minutes; CloudFront caches the range it fetched). The trap is the opposite: a CDN that cannot assemble ranges may fetch the full 4 GB file to answer a 1 MB range, or never cache it at all because it exceeds the cacheable size limit.

Definition: RFC 9110: 206 Partial Content "indicates that the server is successfully fulfilling a range request for the target resource by transferring one or more parts of the selected representation", with Content-Range: bytes 0-9/46; 416 Range Not Satisfiable when no range fits; If-Range makes a range conditional on the validator so a changed file is not stitched from two versions; Accept-Ranges: bytes advertises support. CloudFront: if the origin supports Range GET, "CloudFront serves the requested range and also caches it for future requests". CDNs implement large-file strategies such as slicing the object into fixed-size chunks fetched and cached independently.

 1  player -> edge    GET /movie.mp4  Range: bytes=104857600-105906175
 2  edge              chunked cache: needs chunks 100 and 101 of 1 MiB each
 3  edge -> origin    GET /movie.mp4  Range: bytes=104857600-106954751   (only the missing chunks)
 4  origin -> edge    206, Content-Range: bytes 104857600-106954751/4294967296, ETag "v3"
 5  edge -> player    206, Content-Range: bytes 104857600-105906175/4294967296
 6  next viewer       same chunks: HIT without touching the origin

Real scenario: progressive MP4 playback with seeking; resumable downloads of installers; HTTP-based backups; game patches downloaded by launchers in parallel ranges.

ProductRange behaviourLarge-object control
Cloudflare206 cacheable by default (120 min)Cacheable size limits by plan; Cache Reserve for large long-tail
FastlySegmented Caching "allows you to cache resources of any size"Breaks resources into segments and recombines them
CloudFrontCaches the ranges it fetchedLarge-object behaviour documented per origin type
Go http.ServeContentHandles Range, If-Range, 206, 416Serves from any io.ReadSeeker

Fix / how to use it: serve large files with Accept-Ranges, a strong ETag and If-Range support (Go's http.ServeContent does all three); enable the CDN's large-object or chunked caching; put large files behind a shield so a long-tail miss is one origin read.

Multi-CDN and failover Important ​

In plain words: Use two (or more) CDNs at once so one outage, one bad region or one price increase does not take you down, and steer each user to whichever performs best.

Common misunderstanding: "Multi-CDN is just two CNAMEs." Each CDN has its own cache key rules, header semantics, purge API, token scheme, TLS certificates and logs. Without a common configuration, a purge reaches one CDN and not the other, and a signed URL valid on one is rejected on the other.

Definition: Multi-CDN steering happens at DNS (weighted or performance-based answers from a DNS provider or a steering service, with health checks), in the player (video players switch CDN per session or per segment on errors), or by a front CDN that fails over to another. Origin failover inside one CDN is a different feature: CloudFront origin groups have "a primary and a secondary" origin and switch when the primary "is unavailable, or returns specific HTTP response status codes that indicate a failure".

 1  steering DNS   health: CDN-A ok, CDN-B ok; RUM says CDN-B faster in Indonesia
 2  user (ID)      -> CDN-B; user (DE) -> CDN-A
 3  t=10:00        CDN-A regional incident: health checks fail in EU
 4  t=10:01        steering moves EU to CDN-B (DNS TTL 30-60 s; players switch on next segment error)
 5  CDN-B          colder cache in EU: hit ratio dips, shield in front of origin absorbs the refill
 6  purge          app purges both CDNs (one tag list, two APIs)

Real scenario: large streaming services and live events (where a CDN outage is a public incident); regulated markets where one provider lacks presence; cost negotiation; a migration from one CDN to another done gradually.

ConcernSingle CDNMulti-CDN
AvailabilityOne provider's SLASurvives a provider-wide incident
Cache efficiencyOne cache to warmEach CDN warms its own; more origin traffic
ConfigurationOne rule setLowest common denominator or per-CDN translation
Purge, tokens, logsOne APIFan-out purge, portable token scheme, merged logs
CostVolume discountsNegotiation leverage; more origin egress

Fix / how to use it: keep cache policy in origin headers (both CDN-Cache-Control and Surrogate-Control, Cache-Tag and Surrogate-Key), use a token scheme you verify yourself or one both CDNs support, fan purges out from one job, and put your own shield or object storage in front of the origin so two CDNs do not double the origin load.

Cost: egress pricing and cache hit economics Important ​

In plain words: Clouds charge for bytes leaving them (egress). A CDN charges for bytes it delivers, often less per GB, and every cache hit is a byte your cloud did not send.

Common misunderstanding: "The CDN bill is the cost." The total is CDN delivery + origin egress to the CDN (misses, revalidations, shield refills) + requests (some CDNs and object stores charge per request) + edge compute + log shipping. Cutting the CDN price while doubling origin egress (for example by removing the shield) can raise the total.

Definition: For a back-of-envelope (an estimate, not a price quote; check your contracts and current price pages): monthly cost ≈ delivered GB × CDN price per GB + delivered GB × (1 − byte hit ratio at the last tier) × origin egress price per GB + requests × per-request price. Some providers zero-rate transfer between partner networks (Cloudflare's Bandwidth Alliance is listed on its Tiered Cache page), and object stores that sit inside the CDN network avoid the egress leg entirely. Method for traffic and bandwidth estimates: Capacity Estimation.

 1  delivered          500 TB/month
 2  last-tier byte hit 90%   -> origin egress 50 TB
 3  raise to 97% (shield + fingerprinting + longer image TTL) -> origin egress 15 TB
 4  saving             35 TB x (origin egress price per GB) every month
 5  plus               fewer origin servers (requests at origin fell by the same factor)

Real scenario: an image service whose originals live in S3 in one region; a video platform where segments dominate bytes; a SaaS paying per-request fees on API calls through the CDN; a download site whose costs are almost all bytes.

LeverEffect on costEffect on freshness
Shield / tiered cacheFewer origin fetches and egressNone
Longer TTL + tag purgeHigher hit ratioCorrect, if purges are reliable
Fingerprinted assetsNear 100% hit on assetsNone
Cache key normalisationFewer duplicate objectsNone
stale-if-errorFewer emergency origin fetchesStale during outages only
Compression (Brotli)Fewer bytes deliveredNone
Object storage in the CDN networkRemoves the egress legNone

Fix / how to use it: measure byte hit ratio at the last tier and origin egress per content class; fix the biggest-byte misses first (the SQL "keys that cost the most origin bytes" query).

Products: what each one is for Must-know ​

In plain words: All five do edge caching; they differ in how you configure them, where they are strong, and what else they bundle.

Common misunderstanding: "CDNs are interchangeable commodities." Cache key control, purge speed and granularity, edge compute model, shielding, logging and pricing differ enough to change designs. Pick by the features your design depends on (tag purge, coalescing, shielding, signed cookies, edge code), then by price and presence.

Definition: Cloudflare: anycast network with CDN, WAF, DDoS, Workers, R2 and Tiered Cache; tag purge via Cache-Tag; CDN-Cache-Control honoured. Fastly: programmable CDN (VCL services and Compute) with instant purge, surrogate keys, soft purge, request collapsing and shielding. Akamai: the oldest large CDN, configured through Property Manager behaviors, with Tiered Distribution, ESI, Fast Purge (invalidate or delete) and cache tags. Amazon CloudFront: AWS's CDN with cache policies, regional edge caches, Origin Shield, signed URLs and cookies, CloudFront Functions and Lambda@Edge, OAC for S3 and origin groups. Bunny: a lower-cost CDN with Pull Zones, Storage Zones, token authentication and a video product.

 1  need: tag purge in < 1 s + coalescing + edge code      -> Fastly or Cloudflare
 2  need: everything already in AWS, S3 private origin      -> CloudFront + OAC + Origin Shield
 3  need: enterprise media at very large scale, ESI         -> Akamai
 4  need: simple, cheap static and video delivery           -> Bunny
 5  need: availability beyond one provider                 -> two of the above + steering

Real scenario: a Laravel SaaS on AWS (CloudFront); a media publisher with heavy purge needs (Fastly); a small team wanting WAF, DDoS and CDN in one (Cloudflare); a global retailer with complex per-path rules (Akamai); an indie video course site (Bunny).

FeatureCloudflareFastlyAkamaiCloudFrontBunny
ConfigurationDashboard, Rules, API, WorkersVCL / Compute, APIProperty Manager, APIDistributions, cache policies, APIPull Zones, API
Tag purgeCache-TagSurrogate-KeyCache tagsInvalidation by cache tagsNot covered by the pages read
Soft purgeVia stale directivesFastly-Soft-PurgeInvalidate methodNoNot documented here
Mid-tierTiered CacheShieldingTiered DistributionRegional caches, Origin ShieldOrigin Shield
Edge codeWorkersComputeEdgeWorkersCloudFront Functions, Lambda@EdgeEdge Scripting (product docs)
Signed accessHMAC rules, WorkersCode in VCL/ComputeToken authSigned URLs and cookiesToken Authentication
Targeted headerCDN-Cache-ControlSurrogate-ControlEdge-ControlCache policy TTLsEdge rules

Rows marked "product docs" summarise vendor product pages rather than the specific documents saved for this chapter; verify on the vendor site before relying on them.

Mechanics ​

Header precedence, per product ​

CacheFirst choiceThenThenFallback
RFC 9111 shared caches-maxagemax-ageExpiresHeuristic freshness
RFC 9213 aware CDNCDN-Cache-Control(the above, ignored when targeted field present)
CloudflareCache Rules (Edge Cache TTL)Cloudflare-CDN-Cache-Control / CDN-Cache-ControlCache-Control / ExpiresDefault TTL by status
FastlySurrogate-Control: max-ageCache-Control: s-maxageCache-Control: max-age, Expires2 minutes
CloudFrontHeader within the policy's min/max TTLs-maxage, max-age, ExpiresDefault TTL
Browsermax-ageExpiresHeuristic (for example 10% of age since Last-Modified)

The exact knobs ​

KnobWhereExample
Edge TTL overrideCloudflare Cache RulesEdge TTL 5 min for /products/*
Cache everythingCloudflare Cache Rules, Workers cacheEverythingCache HTML too
TTL by statusWorkers cacheTtlByStatus{"200-299": 300, "404": 60, "500-599": 0}
Min/Default/Max TTLCloudFront cache policy0 / 300 / 86400
Query string behaviourCloudFront cache policywhitelist with page, sort
Accept-Encoding in keyCloudFront cache policyEnableAcceptEncodingBrotli, EnableAcceptEncodingGzip
Shield POPFastly backend settingShield closest to origin
Origin Shield RegionCloudFront origin settingRegion nearest the origin
Tiered Cache topologyCloudflareSmart Tiered Cache
Soft purgeFastly purge headerFastly-Soft-Purge: 1
Tag header sizeCloudflare Cache-Tag16 KB aggregate, 1,024 characters per tag in an API purge
Surrogate-Key header sizeFastlyHeader value up to 16 KB
Laravel cache headerscache.headers middlewarepublic;max_age=30;s_maxage=300;stale_while_revalidate=600;etag
NGINX self-hosted collapseproxy_cache_lockon

Status words and headers you will read ​

HeaderValuesMeaning
CF-Cache-Status (Cloudflare)HIT, MISS, EXPIRED, STALE, BYPASS, REVALIDATED, UPDATING, DYNAMIC, NONE/UNKNOWNMISS: eligible but not present; DYNAMIC: not eligible for cache
AgeSecondsTime since the response was generated or validated; a local HIT can inherit Age from an upper tier
X-Cache (Fastly, CloudFront)HIT, MISS, Hit from cloudfront, RefreshHit from cloudfront, Miss from cloudfrontPer-tier result (Fastly may show one entry per tier)
Via1.1 varnish, 1.1 <id>.cloudfront.net (CloudFront)Proxies traversed
Server-Timing, CF-Ray, X-Amz-Cf-IdRequest idsQuote these in support tickets

Errors the edge produces ​

CodeProducerMeaningFirst check
520CloudflareWeb server returns an unknown errorOrigin crashed or sent an empty/invalid response
521CloudflareWeb server is downOrigin refused the connection; firewall blocking Cloudflare ranges
522CloudflareConnection timed outTCP to origin did not complete
523CloudflareOrigin is unreachableDNS or routing to origin
524CloudflareA timeout occurredOrigin accepted but did not answer in time
525CloudflareSSL handshake failedOrigin TLS config in Full mode
526CloudflareInvalid SSL certificateFull (strict) with an untrusted or expired origin certificate
502 / 504CloudFront and othersBad Gateway / Gateway TimeoutOrigin TLS, DNS, timeouts; CloudFront documents both
403Any CDNForbiddenBad or expired signature, WAF block, geo restriction, OAC misconfiguration
416Origin or CDNRange Not SatisfiableRange beyond file size; changed file without If-Range
304Origin or CDNNot ModifiedNormal revalidation; not an error

What a request costs ​

PathRound trips the user waits forOrigin work
Browser fresh hit0None
Browser revalidation, edge hit1 to the PoPNone
Edge hitTLS + 1 to the PoPNone
Edge miss, shield hitPoP + backbone to shieldNone
Edge and shield missPoP + shield + originFull render
STALE (SWR)Same as an edge hitOne background fetch per PoP or shield

Go ​

Before: one header for everything ​

The naive origin uses the same Cache-Control for JavaScript, HTML and a personal page, unversioned asset names and no validators. It is not broken code; it is the configuration behind "users see the old app for a day" and "a user saw someone else's account page".

go
// Package before shows an origin that leaves caching to luck: one header for
// every route, unversioned asset names and no validators. It works, and it is
// the reason a CDN either serves stale JavaScript for a day or caches a
// logged-in page for everyone.
package before

import (
	"fmt"
	"net/http"
)

// Handler returns the naive origin.
func Handler() http.Handler {
	mux := http.NewServeMux()

	// Same name on every deploy: a CDN and every browser keep the old file
	// for a day after a release, and purging is the only way out.
	mux.HandleFunc("GET /app.js", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "public, max-age=86400")
		w.Header().Set("Content-Type", "text/javascript")
		fmt.Fprint(w, "console.log('v2')")
	})

	// HTML with a one-day public TTL: a price change is invisible until
	// someone purges, and there is no ETag, so every refresh is a full body.
	mux.HandleFunc("GET /products/{id}", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "public, max-age=86400")
		fmt.Fprintf(w, "<h1>Product %s</h1><p>Price 19.90</p>", r.PathValue("id"))
	})

	// The worst line in the file: a personalised page marked public. A shared
	// cache that ignores Set-Cookie (or a cache rule that says "cache
	// everything") serves the first visitor's account page to the next one.
	mux.HandleFunc("GET /account", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "public, max-age=86400")
		http.SetCookie(w, &http.Cookie{Name: "session", Value: "abc", HttpOnly: true})
		fmt.Fprint(w, "<h1>Hello, Alice</h1>")
	})
	return mux
}

After: an origin that makes a decision per route ​

Fingerprinted assets with immutable and ranges via http.ServeContent; HTML with a zero browser TTL, a targeted CDN TTL, stale directives, surrogate keys and ETag revalidation; personal pages with private, no-store; short negative caching for 404.

go
// Package origin is a small HTTP origin that a CDN can cache correctly.
//
// Every route makes a deliberate caching decision:
//
//   - /assets/{file}: fingerprinted names, one year, immutable, ranges and
//     conditional requests handled by http.ServeContent.
//   - /products/{id}: HTML. Browsers revalidate every time (max-age=0) while
//     the CDN keeps it for five minutes, may serve it stale for one more
//     minute while it refetches, and for a day if the origin is failing.
//     Surrogate keys let a price change purge exactly the pages that show it.
//   - /account: personalised, never stored by anyone.
package origin

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"mime"
	"net/http"
	"path"
	"strings"
	"sync"
	"time"
)

// Header values, kept as constants so tests and the page quote the same text.
const (
	ImmutableAsset = "public, max-age=31536000, immutable"
	BrowserHTML    = "public, max-age=0, must-revalidate"
	EdgeHTML       = "max-age=300, stale-while-revalidate=60, stale-if-error=86400"
	NotFoundShort  = "public, max-age=60"
	Personal       = "private, no-store"
)

// Product is the data behind one HTML page.
type Product struct {
	ID       string
	Name     string
	Price    string
	Category string
	Updated  time.Time
}

// Site holds the content. It is safe for concurrent use.
type Site struct {
	mu       sync.RWMutex
	assets   map[string][]byte // fingerprinted file name -> bytes
	products map[string]Product
	modTime  time.Time // build time of the assets
}

// NewSite returns an empty site whose assets were built at modTime.
func NewSite(modTime time.Time) *Site {
	return &Site{assets: map[string][]byte{}, products: map[string]Product{}, modTime: modTime}
}

// AddAsset stores content under a fingerprinted name such as app.3f9a1c2b.js
// and returns that name. The fingerprint is the first 8 hex digits of the
// SHA-256 of the content, so a new build produces a new URL.
func (s *Site) AddAsset(logical string, content []byte) string {
	sum := sha256.Sum256(content)
	ext := path.Ext(logical)
	name := strings.TrimSuffix(logical, ext) + "." + hex.EncodeToString(sum[:4]) + ext
	s.mu.Lock()
	s.assets[name] = content
	s.mu.Unlock()
	return name
}

// PutProduct creates or replaces a product.
func (s *Site) PutProduct(p Product) {
	s.mu.Lock()
	s.products[p.ID] = p
	s.mu.Unlock()
}

// Handler returns the origin's routes.
func (s *Site) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /assets/{file}", s.asset)
	mux.HandleFunc("GET /products/{id}", s.product)
	mux.HandleFunc("GET /account", s.account)
	return mux
}

func (s *Site) asset(w http.ResponseWriter, r *http.Request) {
	name := r.PathValue("file")
	s.mu.RLock()
	body, ok := s.assets[name]
	s.mu.RUnlock()
	h := w.Header()
	if !ok {
		// Cache the 404 briefly so a broken link cannot hammer the origin,
		// but not long enough to hide a file that a deploy is about to add.
		h.Set("Cache-Control", NotFoundShort)
		http.NotFound(w, r)
		return
	}
	h.Set("Cache-Control", ImmutableAsset)
	h.Set("Vary", "Accept-Encoding")
	h.Set("ETag", strongETag(body))
	if ct := mime.TypeByExtension(path.Ext(name)); ct != "" {
		h.Set("Content-Type", ct)
	}
	// ServeContent answers If-None-Match with 304, If-Range and Range with
	// 206 Partial Content, and an unsatisfiable range with 416.
	http.ServeContent(w, r, name, s.modTime, bytes.NewReader(body))
}

func (s *Site) product(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	s.mu.RLock()
	p, ok := s.products[id]
	s.mu.RUnlock()
	h := w.Header()
	if !ok {
		h.Set("Cache-Control", NotFoundShort)
		http.NotFound(w, r)
		return
	}
	body := []byte(fmt.Sprintf("<h1>%s</h1><p>Price %s</p>", p.Name, p.Price))
	etag := strongETag(body)

	// Browser: always revalidate. CDN: targeted fields (RFC 9213
	// CDN-Cache-Control, read by Cloudflare; Surrogate-Control, read and
	// stripped by Fastly) give the edge its own lifetime.
	h.Set("Cache-Control", BrowserHTML)
	h.Set("CDN-Cache-Control", EdgeHTML)
	h.Set("Surrogate-Control", EdgeHTML)
	// Tags for purge: Fastly reads Surrogate-Key (space separated),
	// Cloudflare reads Cache-Tag (comma separated).
	keys := []string{"product-" + p.ID, "category-" + p.Category, "products"}
	h.Set("Surrogate-Key", strings.Join(keys, " "))
	h.Set("Cache-Tag", strings.Join(keys, ","))
	h.Set("ETag", etag)
	h.Set("Last-Modified", p.Updated.UTC().Format(http.TimeFormat))
	h.Set("Vary", "Accept-Encoding")

	if NoneMatch(r.Header.Get("If-None-Match"), etag) {
		// 304 carries the same caching headers and no body (RFC 9110 15.4.5).
		w.WriteHeader(http.StatusNotModified)
		return
	}
	h.Set("Content-Type", "text/html; charset=utf-8")
	w.Write(body)
}

func (s *Site) account(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", Personal)
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprint(w, "<h1>Your orders</h1>")
}

// strongETag is a quoted hex digest of the representation.
func strongETag(b []byte) string {
	sum := sha256.Sum256(b)
	return `"` + hex.EncodeToString(sum[:8]) + `"`
}

// NoneMatch reports whether an If-None-Match value matches etag, using the
// weak comparison RFC 9110 section 13.1.2 requires for If-None-Match:
// W/"x" and "x" are equal, and "*" matches any current representation.
func NoneMatch(header, etag string) bool {
	if header == "" {
		return false
	}
	want := strings.TrimPrefix(etag, "W/")
	for _, part := range strings.Split(header, ",") {
		t := strings.TrimSpace(part)
		if t == "*" || strings.TrimPrefix(t, "W/") == want {
			return true
		}
	}
	return false
}
go
package origin

import (
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

func newSite(t *testing.T) (*Site, string) {
	t.Helper()
	s := NewSite(time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC))
	name := s.AddAsset("app.js", []byte("console.log('hello from the edge, version 7');"))
	s.PutProduct(Product{ID: "42", Name: "Kettle", Price: "19.90", Category: "kitchen", Updated: time.Date(2026, 11, 20, 9, 0, 0, 0, time.UTC)})
	return s, name
}

func do(t *testing.T, h http.Handler, path string, hdr map[string]string) *http.Response {
	t.Helper()
	req := httptest.NewRequest("GET", path, nil)
	for k, v := range hdr {
		req.Header.Set(k, v)
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec.Result()
}

func TestAssetIsFingerprintedAndImmutable(t *testing.T) {
	s, name := newSite(t)
	if !strings.HasPrefix(name, "app.") || len(name) != len("app.12345678.js") {
		t.Fatalf("unexpected fingerprinted name %q", name)
	}
	res := do(t, s.Handler(), "/assets/"+name, nil)
	if res.StatusCode != 200 {
		t.Fatalf("status %d", res.StatusCode)
	}
	if got := res.Header.Get("Cache-Control"); got != ImmutableAsset {
		t.Fatalf("Cache-Control = %q", got)
	}
	if res.Header.Get("ETag") == "" {
		t.Fatal("missing ETag")
	}
}

func TestAssetConditionalGetReturns304(t *testing.T) {
	s, name := newSite(t)
	first := do(t, s.Handler(), "/assets/"+name, nil)
	etag := first.Header.Get("ETag")
	res := do(t, s.Handler(), "/assets/"+name, map[string]string{"If-None-Match": etag})
	if res.StatusCode != http.StatusNotModified {
		t.Fatalf("want 304, got %d", res.StatusCode)
	}
	if b, _ := io.ReadAll(res.Body); len(b) != 0 {
		t.Fatalf("304 must have no body, got %d bytes", len(b))
	}
}

func TestAssetRangeReturns206(t *testing.T) {
	s, name := newSite(t)
	res := do(t, s.Handler(), "/assets/"+name, map[string]string{"Range": "bytes=0-9"})
	if res.StatusCode != http.StatusPartialContent {
		t.Fatalf("want 206, got %d", res.StatusCode)
	}
	if got := res.Header.Get("Content-Range"); !strings.HasPrefix(got, "bytes 0-9/") {
		t.Fatalf("Content-Range = %q", got)
	}
	b, _ := io.ReadAll(res.Body)
	if string(b) != "console.lo" {
		t.Fatalf("body %q", b)
	}
	bad := do(t, s.Handler(), "/assets/"+name, map[string]string{"Range": "bytes=9999-"})
	if bad.StatusCode != http.StatusRequestedRangeNotSatisfiable {
		t.Fatalf("want 416, got %d", bad.StatusCode)
	}
}

func TestProductHeadersSplitBrowserAndEdge(t *testing.T) {
	s, _ := newSite(t)
	res := do(t, s.Handler(), "/products/42", nil)
	want := map[string]string{
		"Cache-Control":     BrowserHTML,
		"CDN-Cache-Control": EdgeHTML,
		"Surrogate-Control": EdgeHTML,
		"Surrogate-Key":     "product-42 category-kitchen products",
		"Cache-Tag":         "product-42,category-kitchen,products",
		"Vary":              "Accept-Encoding",
	}
	for k, v := range want {
		if got := res.Header.Get(k); got != v {
			t.Errorf("%s = %q, want %q", k, got, v)
		}
	}
}

func TestProductRevalidation(t *testing.T) {
	s, _ := newSite(t)
	etag := do(t, s.Handler(), "/products/42", nil).Header.Get("ETag")
	if res := do(t, s.Handler(), "/products/42", map[string]string{"If-None-Match": "W/" + etag}); res.StatusCode != 304 {
		t.Fatalf("weak match must give 304, got %d", res.StatusCode)
	}
	s.PutProduct(Product{ID: "42", Name: "Kettle", Price: "17.50", Category: "kitchen", Updated: time.Now()})
	res := do(t, s.Handler(), "/products/42", map[string]string{"If-None-Match": etag})
	if res.StatusCode != 200 {
		t.Fatalf("changed content must give 200, got %d", res.StatusCode)
	}
	if res.Header.Get("ETag") == etag {
		t.Fatal("ETag must change with content")
	}
}

func TestAccountIsNeverStored(t *testing.T) {
	s, _ := newSite(t)
	if got := do(t, s.Handler(), "/account", nil).Header.Get("Cache-Control"); got != Personal {
		t.Fatalf("Cache-Control = %q", got)
	}
}

func TestNotFoundIsCachedBriefly(t *testing.T) {
	s, _ := newSite(t)
	res := do(t, s.Handler(), "/assets/app.00000000.js", nil)
	if res.StatusCode != 404 || res.Header.Get("Cache-Control") != NotFoundShort {
		t.Fatalf("got %d %q", res.StatusCode, res.Header.Get("Cache-Control"))
	}
}

func TestNoneMatch(t *testing.T) {
	cases := []struct {
		h, e string
		want bool
	}{
		{"", `"a"`, false},
		{`"a"`, `"a"`, true},
		{`W/"a"`, `"a"`, true},
		{`"b", "a"`, `"a"`, true},
		{`*`, `"a"`, true},
		{`"b"`, `"a"`, false},
	}
	for _, c := range cases {
		if got := NoneMatch(c.h, c.e); got != c.want {
			t.Errorf("NoneMatch(%q,%q)=%v", c.h, c.e, got)
		}
	}
}

Example: a cache tier with LRU, TTL, stale serving and singleflight ​

edgecache.Cache is one tier. It is also a Fetcher, so an edge can sit in front of a shield that sits in front of the origin, exactly like a CDN hierarchy. It parses CDN-Cache-Control, Surrogate-Control and Cache-Control with the precedence described above, refuses Set-Cookie, private and no-store, revalidates with If-None-Match, collapses concurrent misses with singleflight, serves STALE and STALE-IF-ERROR, evicts by bytes, supports hard and soft purge by tag, and counts hit ratio and byte hit ratio.

go
// Package edgecache simulates one CDN cache tier: an LRU bounded by bytes,
// freshness from targeted cache headers, stale-while-revalidate,
// stale-if-error, revalidation with ETag/If-None-Match and request
// coalescing (collapsed forwarding) with golang.org/x/sync/singleflight.
//
// A Cache is itself a Fetcher, so tiers chain the way a CDN does:
// edge -> shield (mid-tier) -> origin.
package edgecache

import (
	"container/list"
	"context"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"

	"golang.org/x/sync/singleflight"
)

// Request is the part of an HTTP request a cache tier looks at.
type Request struct {
	Host, Path     string
	Query          url.Values
	AcceptEncoding string
	IfNoneMatch    string
}

// Response is immutable once stored; tiers copy headers before changing them.
type Response struct {
	Status int
	Header http.Header
	Body   []byte
}

// Fetcher is anything that can answer a Request: an origin or a parent tier.
type Fetcher interface {
	Fetch(ctx context.Context, r Request) (*Response, error)
}

// FetcherFunc adapts a function to Fetcher.
type FetcherFunc func(ctx context.Context, r Request) (*Response, error)

// Fetch calls f.
func (f FetcherFunc) Fetch(ctx context.Context, r Request) (*Response, error) { return f(ctx, r) }

// Outcome mirrors the cache-status words CDNs print (Cloudflare CF-Cache-Status,
// Fastly X-Cache, CloudFront X-Cache).
type Outcome string

// Outcomes of Get.
const (
	Hit          Outcome = "HIT"
	Miss         Outcome = "MISS"
	Stale        Outcome = "STALE"          // served stale, refresh started in background
	Revalidated  Outcome = "REVALIDATED"    // upstream answered 304, stored body reused
	StaleIfError Outcome = "STALE-IF-ERROR" // upstream failed, stale copy served
)

// Policy is how long a tier may keep and reuse a response.
type Policy struct {
	Store         bool
	TTL, SWR, SIE time.Duration
}

// Stats are the numbers a CDN dashboard shows.
type Stats struct {
	Requests, Hits, Stale, Revalidated, StaleIfError, Misses int64
	UpstreamFetches, Evictions                               int64
	BytesServed, BytesFromCache                              int64
}

// HitRatio is the share of requests answered without a full upstream body.
func (s Stats) HitRatio() float64 {
	if s.Requests == 0 {
		return 0
	}
	return float64(s.Hits+s.Stale+s.Revalidated+s.StaleIfError) / float64(s.Requests)
}

// ByteHitRatio is the share of bytes served from cache.
func (s Stats) ByteHitRatio() float64 {
	if s.BytesServed == 0 {
		return 0
	}
	return float64(s.BytesFromCache) / float64(s.BytesServed)
}

// Options configure a Cache.
type Options struct {
	Name          string
	CapacityBytes int64
	Now           func() time.Time
	Key           func(Request) string
	FetchTimeout  time.Duration
}

type entry struct {
	key      string
	resp     *Response
	storedAt time.Time
	pol      Policy
	size     int64
}

// Cache is one tier.
type Cache struct {
	name     string
	parent   Fetcher
	capacity int64
	now      func() time.Time
	keyFn    func(Request) string
	timeout  time.Duration

	mu    sync.Mutex
	ll    *list.List
	items map[string]*list.Element
	used  int64
	stats Stats

	sf singleflight.Group
	bg sync.WaitGroup
}

// New returns a tier in front of parent.
func New(parent Fetcher, o Options) *Cache {
	if o.Now == nil {
		o.Now = time.Now
	}
	if o.Key == nil {
		o.Key = DefaultKey
	}
	if o.FetchTimeout == 0 {
		o.FetchTimeout = 10 * time.Second
	}
	return &Cache{name: o.Name, parent: parent, capacity: o.CapacityBytes, now: o.Now,
		keyFn: o.Key, timeout: o.FetchTimeout, ll: list.New(), items: map[string]*list.Element{}}
}

// Stats returns a snapshot.
func (c *Cache) Stats() Stats {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.stats
}

// Wait blocks until background revalidations finish (used by tests and the lab).
func (c *Cache) Wait() { c.bg.Wait() }

// Fetch lets a child tier use this cache as its parent.
func (c *Cache) Fetch(ctx context.Context, r Request) (*Response, error) {
	resp, _, err := c.Get(ctx, r)
	return resp, err
}

type filled struct {
	resp    *Response
	outcome Outcome
}

// Get answers r from cache or upstream and reports what happened.
func (c *Cache) Get(ctx context.Context, r Request) (*Response, Outcome, error) {
	key := c.keyFn(r)
	now := c.now()

	c.mu.Lock()
	c.stats.Requests++
	var e *entry
	if el, ok := c.items[key]; ok {
		c.ll.MoveToFront(el)
		e = el.Value.(*entry)
		age := now.Sub(e.storedAt)
		switch {
		case age < e.pol.TTL:
			c.stats.Hits++
			out := c.answerLocked(e, r, now, Hit, true)
			c.mu.Unlock()
			return out, Hit, nil
		case age < e.pol.TTL+e.pol.SWR:
			c.stats.Stale++
			out := c.answerLocked(e, r, now, Stale, true)
			c.mu.Unlock()
			c.refreshAsync(key, r, e)
			return out, Stale, nil
		}
	}
	c.mu.Unlock()

	// Every concurrent miss for this key waits for one upstream fetch.
	v, err, _ := c.sf.Do(key, func() (any, error) { return c.fetchAndStore(ctx, key, r, e) })
	if err != nil {
		c.mu.Lock()
		c.stats.Misses++
		c.mu.Unlock()
		return nil, Miss, err
	}
	f := v.(filled)
	c.mu.Lock()
	defer c.mu.Unlock()
	fromCache := f.outcome != Miss
	switch f.outcome {
	case Revalidated:
		c.stats.Revalidated++
	case StaleIfError:
		c.stats.StaleIfError++
	default:
		c.stats.Misses++
	}
	tmp := &entry{resp: f.resp, storedAt: now}
	return c.answerLocked(tmp, r, now, f.outcome, fromCache), f.outcome, nil
}

// answerLocked copies headers, adds Age and the tier's cache status, and turns
// a matching If-None-Match from the child into a 304.
func (c *Cache) answerLocked(e *entry, r Request, now time.Time, o Outcome, fromCache bool) *Response {
	h := e.resp.Header.Clone()
	if h == nil {
		h = http.Header{}
	}
	h.Set("Age", strconv.Itoa(int(now.Sub(e.storedAt).Seconds())))
	h.Add("X-Cache", fmt.Sprintf("%s %s", c.name, o))
	if r.IfNoneMatch != "" && etagMatch(r.IfNoneMatch, h.Get("ETag")) {
		return &Response{Status: http.StatusNotModified, Header: h}
	}
	n := int64(len(e.resp.Body))
	c.stats.BytesServed += n
	if fromCache {
		c.stats.BytesFromCache += n
	}
	return &Response{Status: e.resp.Status, Header: h, Body: e.resp.Body}
}

func (c *Cache) refreshAsync(key string, r Request, e *entry) {
	c.bg.Add(1)
	go func() {
		defer c.bg.Done()
		<-c.sf.DoChan(key, func() (any, error) { return c.fetchAndStore(context.Background(), key, r, e) })
	}()
}

// fetchAndStore runs once per key at a time (inside singleflight).
func (c *Cache) fetchAndStore(ctx context.Context, key string, r Request, old *entry) (any, error) {
	// The fetch must not die because the first waiter hung up: other
	// callers share its result. Detach from the caller and bound it.
	fctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), c.timeout)
	defer cancel()

	up := r
	up.IfNoneMatch = ""
	if old != nil {
		up.IfNoneMatch = old.resp.Header.Get("ETag")
	}
	c.mu.Lock()
	c.stats.UpstreamFetches++
	c.mu.Unlock()
	resp, err := c.parent.Fetch(fctx, up)
	now := c.now()

	if err != nil || resp.Status >= 500 {
		if old != nil && now.Sub(old.storedAt) < old.pol.TTL+old.pol.SIE {
			return filled{old.resp, StaleIfError}, nil
		}
		if err != nil {
			return nil, err
		}
		return filled{resp, Miss}, nil // 5xx passes through, not stored
	}

	if resp.Status == http.StatusNotModified && old != nil {
		// RFC 9111 4.3.4: update the stored headers from the 304.
		h := old.resp.Header.Clone()
		for k, v := range resp.Header {
			if k != "Content-Length" && k != "Age" && k != "X-Cache" {
				h[k] = v
			}
		}
		fresh := &Response{Status: old.resp.Status, Header: h, Body: old.resp.Body}
		c.store(key, fresh, ParsePolicy(fresh.Status, h), now)
		return filled{fresh, Revalidated}, nil
	}

	clean := &Response{Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body}
	clean.Header.Del("Age")
	c.store(key, clean, ParsePolicy(resp.Status, resp.Header), now)
	return filled{clean, Miss}, nil
}

func (c *Cache) store(key string, resp *Response, pol Policy, now time.Time) {
	c.mu.Lock()
	defer c.mu.Unlock()
	if el, ok := c.items[key]; ok {
		c.removeLocked(el)
	}
	if !pol.Store {
		return
	}
	size := int64(len(resp.Body)) + 200 // rough per-object overhead
	if size > c.capacity {
		return
	}
	for c.used+size > c.capacity {
		c.removeLocked(c.ll.Back())
		c.stats.Evictions++
	}
	c.items[key] = c.ll.PushFront(&entry{key: key, resp: resp, storedAt: now, pol: pol, size: size})
	c.used += size
}

func (c *Cache) removeLocked(el *list.Element) {
	e := el.Value.(*entry)
	c.ll.Remove(el)
	delete(c.items, e.key)
	c.used -= e.size
}

// Purge removes one key (a hard purge by URL).
func (c *Cache) Purge(r Request) {
	c.mu.Lock()
	defer c.mu.Unlock()
	if el, ok := c.items[c.keyFn(r)]; ok {
		c.removeLocked(el)
	}
}

// PurgeTag hard-purges every object whose Surrogate-Key or Cache-Tag
// contains tag. Soft purge would mark them stale instead; see SoftPurgeTag.
func (c *Cache) PurgeTag(tag string) int { return c.purgeTag(tag, false) }

// SoftPurgeTag marks tagged objects stale so they can still be served under
// stale-while-revalidate or stale-if-error (Fastly's soft purge).
func (c *Cache) SoftPurgeTag(tag string) int { return c.purgeTag(tag, true) }

func (c *Cache) purgeTag(tag string, soft bool) int {
	c.mu.Lock()
	defer c.mu.Unlock()
	n := 0
	for el := c.ll.Front(); el != nil; {
		next := el.Next()
		e := el.Value.(*entry)
		if hasTag(e.resp.Header, tag) {
			n++
			if soft {
				e.storedAt = c.now().Add(-e.pol.TTL)
			} else {
				c.removeLocked(el)
			}
		}
		el = next
	}
	return n
}

func hasTag(h http.Header, tag string) bool {
	for _, t := range strings.Fields(h.Get("Surrogate-Key")) {
		if t == tag {
			return true
		}
	}
	for _, t := range strings.Split(h.Get("Cache-Tag"), ",") {
		if strings.TrimSpace(t) == tag {
			return true
		}
	}
	return false
}

// ParsePolicy reads freshness the way a CDN tier does: a targeted field
// (CDN-Cache-Control, then Surrogate-Control) wins over Cache-Control; in
// Cache-Control, s-maxage wins over max-age. Set-Cookie, private and
// no-store prevent storing. Only explicit freshness is used (no heuristics).
func ParsePolicy(status int, h http.Header) Policy {
	if h.Get("Set-Cookie") != "" || !cacheableStatus(status) {
		return Policy{}
	}
	field, targeted := h.Get("CDN-Cache-Control"), true
	if field == "" {
		field = h.Get("Surrogate-Control")
	}
	if field == "" {
		field, targeted = h.Get("Cache-Control"), false
	}
	d := directives(field)
	for _, k := range []string{"no-store", "private", "no-cache"} {
		if _, ok := d[k]; ok {
			return Policy{}
		}
	}
	ttl, ok := time.Duration(0), false
	if !targeted {
		ttl, ok = d["s-maxage"]
	}
	if !ok {
		ttl = d["max-age"]
	}
	if ttl <= 0 {
		return Policy{}
	}
	return Policy{Store: true, TTL: ttl, SWR: d["stale-while-revalidate"], SIE: d["stale-if-error"]}
}

func directives(v string) map[string]time.Duration {
	out := map[string]time.Duration{}
	for _, part := range strings.Split(v, ",") {
		name, val, _ := strings.Cut(strings.TrimSpace(part), "=")
		name = strings.ToLower(name)
		if name == "" {
			continue
		}
		n, _ := strconv.Atoi(strings.Trim(val, `"`))
		out[name] = time.Duration(n) * time.Second
	}
	return out
}

func cacheableStatus(s int) bool {
	switch s {
	case 200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, 501:
		return true
	}
	return false
}

func etagMatch(header, etag string) bool {
	if etag == "" {
		return false
	}
	want := strings.TrimPrefix(etag, "W/")
	for _, p := range strings.Split(header, ",") {
		t := strings.TrimSpace(p)
		if t == "*" || strings.TrimPrefix(t, "W/") == want {
			return true
		}
	}
	return false
}

// DefaultKey normalises a request into a cache key: lower-case host, marketing
// parameters dropped, remaining parameters sorted, Accept-Encoding collapsed
// to the one encoding the origin will actually choose.
func DefaultKey(r Request) string { return key(r, nil) }

// AllowListKey keeps only the named query parameters (CloudFront cache
// policies and Cloudflare custom cache keys work this way).
func AllowListKey(params ...string) func(Request) string {
	allow := map[string]bool{}
	for _, p := range params {
		allow[p] = true
	}
	return func(r Request) string { return key(r, allow) }
}

func key(r Request, allow map[string]bool) string {
	var names []string
	for k := range r.Query {
		lk := strings.ToLower(k)
		if allow != nil && !allow[k] {
			continue
		}
		if strings.HasPrefix(lk, "utm_") || lk == "fbclid" || lk == "gclid" {
			continue
		}
		names = append(names, k)
	}
	sort.Strings(names)
	var b strings.Builder
	b.WriteString(strings.ToLower(r.Host))
	b.WriteString(r.Path)
	for i, k := range names {
		vals := append([]string(nil), r.Query[k]...)
		sort.Strings(vals)
		for j, v := range vals {
			if i == 0 && j == 0 {
				b.WriteByte('?')
			} else {
				b.WriteByte('&')
			}
			b.WriteString(url.QueryEscape(k) + "=" + url.QueryEscape(v))
		}
	}
	b.WriteString("|ae=" + NormalizeEncoding(r.AcceptEncoding))
	return b.String()
}

// NormalizeEncoding maps an Accept-Encoding header to br, gzip or identity,
// so "gzip, deflate, br" and "br;q=1, gzip" share one cache entry.
func NormalizeEncoding(ae string) string {
	has := func(enc string) bool {
		for _, p := range strings.Split(ae, ",") {
			name, params, _ := strings.Cut(strings.TrimSpace(p), ";")
			if strings.EqualFold(name, enc) && !strings.Contains(strings.ReplaceAll(params, " ", ""), "q=0") {
				return true
			}
		}
		return false
	}
	switch {
	case has("br"):
		return "br"
	case has("gzip"):
		return "gzip"
	}
	return "identity"
}

// HTTPOrigin fetches from a real HTTP server (the origin package in tests).
type HTTPOrigin struct {
	Base   string
	Client *http.Client
}

// Fetch issues a GET with the conditional and encoding headers.
func (o HTTPOrigin) Fetch(ctx context.Context, r Request) (*Response, error) {
	u := o.Base + r.Path
	if len(r.Query) > 0 {
		u += "?" + r.Query.Encode()
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
	if err != nil {
		return nil, err
	}
	if r.AcceptEncoding != "" {
		req.Header.Set("Accept-Encoding", r.AcceptEncoding)
	}
	if r.IfNoneMatch != "" {
		req.Header.Set("If-None-Match", r.IfNoneMatch)
	}
	cl := o.Client
	if cl == nil {
		cl = http.DefaultClient
	}
	res, err := cl.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	return &Response{Status: res.StatusCode, Header: res.Header, Body: body}, nil
}
go
package edgecache

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"net/url"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"academy/cdn/origin"
)

type clock struct {
	mu sync.Mutex
	t  time.Time
}

func (c *clock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t }
func (c *clock) Add(d time.Duration) {
	c.mu.Lock()
	c.t = c.t.Add(d)
	c.mu.Unlock()
}

func newClock() *clock { return &clock{t: time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)} }

// counting wraps a Fetcher and counts calls.
type counting struct {
	next  Fetcher
	calls atomic.Int64
}

func (c *counting) Fetch(ctx context.Context, r Request) (*Response, error) {
	c.calls.Add(1)
	return c.next.Fetch(ctx, r)
}

func startOrigin(t *testing.T) (*origin.Site, *counting) {
	t.Helper()
	site := origin.NewSite(time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC))
	site.PutProduct(origin.Product{ID: "42", Name: "Kettle", Price: "19.90", Category: "kitchen", Updated: time.Now()})
	srv := httptest.NewServer(site.Handler())
	t.Cleanup(srv.Close)
	return site, &counting{next: HTTPOrigin{Base: srv.URL}}
}

var product = Request{Host: "shop.example", Path: "/products/42", AcceptEncoding: "br, gzip"}

func TestCoalescingCollapsesConcurrentMisses(t *testing.T) {
	var calls atomic.Int64
	slow := FetcherFunc(func(ctx context.Context, r Request) (*Response, error) {
		calls.Add(1)
		time.Sleep(100 * time.Millisecond)
		return &Response{Status: 200, Header: http.Header{"Cache-Control": {"max-age=60"}}, Body: []byte("hot")}, nil
	})
	c := New(slow, Options{Name: "edge", CapacityBytes: 1 << 20})
	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			resp, _, err := c.Get(context.Background(), product)
			if err != nil || string(resp.Body) != "hot" {
				t.Errorf("err=%v body=%q", err, resp.Body)
			}
		}()
	}
	wg.Wait()
	if n := calls.Load(); n != 1 {
		t.Fatalf("origin fetched %d times, want 1", n)
	}
}

func TestHitThenRevalidateWith304(t *testing.T) {
	_, up := startOrigin(t)
	clk := newClock()
	c := New(up, Options{Name: "edge", CapacityBytes: 1 << 20, Now: clk.Now})
	ctx := context.Background()

	if _, o, _ := c.Get(ctx, product); o != Miss {
		t.Fatalf("first: %s", o)
	}
	clk.Add(299 * time.Second)
	if _, o, _ := c.Get(ctx, product); o != Hit {
		t.Fatalf("within TTL: %s", o)
	}
	clk.Add(62 * time.Second) // past TTL (300) + SWR (60)
	resp, o, _ := c.Get(ctx, product)
	if o != Revalidated || resp.Status != 200 || len(resp.Body) == 0 {
		t.Fatalf("after expiry: %s %d", o, resp.Status)
	}
	if n := up.calls.Load(); n != 2 {
		t.Fatalf("origin calls %d, want 2 (fill + 304)", n)
	}
}

func TestChangedContentIsRefetched(t *testing.T) {
	site, up := startOrigin(t)
	clk := newClock()
	c := New(up, Options{Name: "edge", CapacityBytes: 1 << 20, Now: clk.Now})
	ctx := context.Background()
	first, _, _ := c.Get(ctx, product)
	site.PutProduct(origin.Product{ID: "42", Name: "Kettle", Price: "17.50", Category: "kitchen", Updated: time.Now()})
	clk.Add(400 * time.Second)
	second, o, _ := c.Get(ctx, product)
	if o != Miss || string(second.Body) == string(first.Body) {
		t.Fatalf("want fresh body via MISS, got %s %q", o, second.Body)
	}
}

func TestStaleWhileRevalidateServesOldCopyAtOnce(t *testing.T) {
	_, up := startOrigin(t)
	clk := newClock()
	c := New(up, Options{Name: "edge", CapacityBytes: 1 << 20, Now: clk.Now})
	ctx := context.Background()
	c.Get(ctx, product)
	clk.Add(330 * time.Second) // inside the 60 s stale-while-revalidate window
	if _, o, _ := c.Get(ctx, product); o != Stale {
		t.Fatalf("want STALE, got %s", o)
	}
	c.Wait()
	if _, o, _ := c.Get(ctx, product); o != Hit {
		t.Fatalf("after background refresh want HIT, got %s", o)
	}
}

func TestStaleIfErrorHidesOriginOutage(t *testing.T) {
	var down atomic.Bool
	_, up := startOrigin(t)
	flaky := FetcherFunc(func(ctx context.Context, r Request) (*Response, error) {
		if down.Load() {
			return nil, errors.New("dial tcp 192.0.2.10:443: connect: connection refused")
		}
		return up.Fetch(ctx, r)
	})
	clk := newClock()
	c := New(flaky, Options{Name: "edge", CapacityBytes: 1 << 20, Now: clk.Now})
	ctx := context.Background()
	c.Get(ctx, product)
	down.Store(true)
	clk.Add(2 * time.Hour)
	resp, o, err := c.Get(ctx, product)
	if err != nil || o != StaleIfError || resp.Status != 200 {
		t.Fatalf("want stale-if-error, got %s %v", o, err)
	}
	clk.Add(48 * time.Hour) // beyond stale-if-error=86400
	if _, _, err := c.Get(ctx, product); err == nil {
		t.Fatal("beyond stale-if-error the outage must surface")
	}
}

func TestPrivateIsNeverStored(t *testing.T) {
	_, up := startOrigin(t)
	c := New(up, Options{Name: "edge", CapacityBytes: 1 << 20})
	acct := Request{Host: "shop.example", Path: "/account"}
	c.Get(context.Background(), acct)
	if _, o, _ := c.Get(context.Background(), acct); o != Miss {
		t.Fatalf("private response served from cache: %s", o)
	}
}

func TestLRUEvictsLeastRecentlyUsed(t *testing.T) {
	body := make([]byte, 100)
	up := FetcherFunc(func(ctx context.Context, r Request) (*Response, error) {
		return &Response{Status: 200, Header: http.Header{"Cache-Control": {"max-age=600"}}, Body: body}, nil
	})
	c := New(up, Options{Name: "edge", CapacityBytes: 650}) // room for two 300-byte entries
	ctx := context.Background()
	a, b, d := Request{Path: "/a"}, Request{Path: "/b"}, Request{Path: "/d"}
	c.Get(ctx, a)
	c.Get(ctx, b)
	c.Get(ctx, a) // a is now most recent
	c.Get(ctx, d) // evicts b
	if _, o, _ := c.Get(ctx, a); o != Hit {
		t.Fatalf("a should survive, got %s", o)
	}
	if _, o, _ := c.Get(ctx, b); o != Miss {
		t.Fatalf("b should be evicted, got %s", o)
	}
	if c.Stats().Evictions < 1 {
		t.Fatal("no eviction counted")
	}
}

func TestShieldCollapsesTwoEdgesToOneOriginFetch(t *testing.T) {
	_, up := startOrigin(t)
	shield := New(up, Options{Name: "shield", CapacityBytes: 1 << 20})
	fra := New(shield, Options{Name: "edge-fra", CapacityBytes: 1 << 20})
	sin := New(shield, Options{Name: "edge-sin", CapacityBytes: 1 << 20})
	ctx := context.Background()
	fra.Get(ctx, product)
	resp, o, _ := sin.Get(ctx, product)
	if o != Miss {
		t.Fatalf("sin edge is cold, want MISS, got %s", o)
	}
	if got := resp.Header.Values("X-Cache"); len(got) != 2 || got[0] != "shield HIT" || got[1] != "edge-sin MISS" {
		t.Fatalf("X-Cache chain = %v", got)
	}
	if n := up.calls.Load(); n != 1 {
		t.Fatalf("origin calls %d, want 1", n)
	}
}

func TestPurgeAndSoftPurgeByTag(t *testing.T) {
	_, up := startOrigin(t)
	clk := newClock()
	c := New(up, Options{Name: "edge", CapacityBytes: 1 << 20, Now: clk.Now})
	ctx := context.Background()
	c.Get(ctx, product)
	if n := c.SoftPurgeTag("category-kitchen"); n != 1 {
		t.Fatalf("soft purge matched %d", n)
	}
	if _, o, _ := c.Get(ctx, product); o != Stale {
		t.Fatalf("after soft purge want STALE, got %s", o)
	}
	c.Wait()
	if n := c.PurgeTag("product-42"); n != 1 {
		t.Fatalf("hard purge matched %d", n)
	}
	if _, o, _ := c.Get(ctx, product); o != Miss {
		t.Fatalf("after hard purge want MISS, got %s", o)
	}
}

func TestDefaultKeyNormalisation(t *testing.T) {
	q1, _ := url.ParseQuery("size=m&color=red&utm_source=mail&gclid=x")
	q2, _ := url.ParseQuery("color=red&size=m")
	k1 := DefaultKey(Request{Host: "Shop.Example", Path: "/p", Query: q1, AcceptEncoding: "gzip, deflate, br"})
	k2 := DefaultKey(Request{Host: "shop.example", Path: "/p", Query: q2, AcceptEncoding: "br;q=1, gzip;q=0.8"})
	if k1 != k2 {
		t.Fatalf("keys differ:\n%s\n%s", k1, k2)
	}
	if k1 != "shop.example/p?color=red&size=m|ae=br" {
		t.Fatalf("key = %s", k1)
	}
	k3 := AllowListKey("size")(Request{Host: "shop.example", Path: "/p", Query: q1})
	if k3 != "shop.example/p?size=m|ae=identity" {
		t.Fatalf("allow-list key = %s", k3)
	}
}

func TestParsePolicyPrecedence(t *testing.T) {
	h := http.Header{}
	h.Set("Cache-Control", "public, max-age=10, s-maxage=20")
	if p := ParsePolicy(200, h); p.TTL != 20*time.Second {
		t.Fatalf("s-maxage should win: %v", p.TTL)
	}
	h.Set("CDN-Cache-Control", "max-age=300, stale-while-revalidate=60")
	if p := ParsePolicy(200, h); p.TTL != 300*time.Second || p.SWR != time.Minute {
		t.Fatalf("CDN-Cache-Control should win: %+v", p)
	}
	h.Set("Set-Cookie", "session=1")
	if ParsePolicy(200, h).Store {
		t.Fatal("Set-Cookie response must not be stored")
	}
	if ParsePolicy(500, http.Header{"Cache-Control": {"max-age=300"}}).Store {
		t.Fatal("500 is not cacheable here")
	}
}

func TestByteHitRatio(t *testing.T) {
	s := Stats{Requests: 10, Hits: 9, Misses: 1, BytesServed: 1000, BytesFromCache: 400}
	if s.HitRatio() != 0.9 || s.ByteHitRatio() != 0.4 {
		t.Fatalf("%v %v", s.HitRatio(), s.ByteHitRatio())
	}
}

Example: signed URLs and HLS playlists ​

go
// Package signedurl implements expiring, HMAC-signed URLs of the kind CDNs
// verify at the edge (Bunny token authentication, Cloudflare WAF
// is_timed_hmac_valid_v0, Akamai token auth; CloudFront uses RSA/ECDSA key
// pairs instead of a shared secret, with the same idea).
//
// A token can cover one exact path or a path prefix. Prefix tokens are what
// video needs: one token for /video/abc/ authorises the manifest and every
// segment the player requests after it.
package signedurl

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

// Errors returned by Verify.
var (
	ErrMissing   = errors.New("signedurl: missing token")
	ErrExpired   = errors.New("signedurl: token expired")
	ErrSignature = errors.New("signedurl: bad signature")
	ErrScope     = errors.New("signedurl: path outside signed prefix")
)

// Signer holds the shared secret (rotate it like any key; keep two during rotation).
type Signer struct{ Secret []byte }

// Sign returns path?exp=...&[prefix=...&]sig=... valid until expires.
// When prefix is non-empty the signature covers the prefix, not the path.
func (s Signer) Sign(path, prefix string, expires time.Time) string {
	exp := strconv.FormatInt(expires.Unix(), 10)
	scope := path
	q := url.Values{"exp": {exp}}
	if prefix != "" {
		scope = prefix
		q.Set("prefix", prefix)
	}
	q.Set("sig", s.mac(scope, exp))
	return path + "?" + q.Encode()
}

// Verify checks a request path and query at time now.
func (s Signer) Verify(path string, q url.Values, now time.Time) error {
	exp, sig := q.Get("exp"), q.Get("sig")
	if exp == "" || sig == "" {
		return ErrMissing
	}
	scope := path
	if p := q.Get("prefix"); p != "" {
		if !strings.HasPrefix(path, p) {
			return ErrScope
		}
		scope = p
	}
	// Check the signature before the clock so a forged exp learns nothing.
	if !hmac.Equal([]byte(sig), []byte(s.mac(scope, exp))) {
		return ErrSignature
	}
	n, err := strconv.ParseInt(exp, 10, 64)
	if err != nil || now.Unix() > n {
		return ErrExpired
	}
	return nil
}

func (s Signer) mac(scope, exp string) string {
	m := hmac.New(sha256.New, s.Secret)
	m.Write([]byte(scope))
	m.Write([]byte{0})
	m.Write([]byte(exp))
	return base64.RawURLEncoding.EncodeToString(m.Sum(nil))
}
go
// Package hls writes the two HLS playlist kinds (RFC 8216) and the caching
// header each object in a stream should carry.
//
// The rule a CDN cares about: segments never change once published, so they
// are cached for a long time; a live media playlist changes every segment, so
// its TTL must stay below the target duration or players see a frozen stream.
package hls

import (
	"fmt"
	"strings"
)

// Variant is one rendition in the multivariant (master) playlist.
type Variant struct {
	Bandwidth  int    // peak bits per second
	Average    int    // average bits per second
	Resolution string // e.g. 1280x720
	Codecs     string // e.g. avc1.64001f,mp4a.40.2
	URI        string // media playlist
}

// Segment is one media segment.
type Segment struct {
	Duration float64
	URI      string
}

// Multivariant renders the master playlist the player loads first.
func Multivariant(vs []Variant) string {
	var b strings.Builder
	b.WriteString("#EXTM3U\n#EXT-X-VERSION:7\n#EXT-X-INDEPENDENT-SEGMENTS\n")
	for _, v := range vs {
		fmt.Fprintf(&b, "#EXT-X-STREAM-INF:BANDWIDTH=%d,AVERAGE-BANDWIDTH=%d,RESOLUTION=%s,CODECS=\"%s\"\n%s\n",
			v.Bandwidth, v.Average, v.Resolution, v.Codecs, v.URI)
	}
	return b.String()
}

// Media renders a media playlist with fMP4 (CMAF) segments. vod=true adds
// EXT-X-PLAYLIST-TYPE:VOD and EXT-X-ENDLIST; otherwise it is a live sliding window.
func Media(target int, firstSeq int, segs []Segment, vod bool) string {
	var b strings.Builder
	b.WriteString("#EXTM3U\n#EXT-X-VERSION:7\n")
	fmt.Fprintf(&b, "#EXT-X-TARGETDURATION:%d\n#EXT-X-MEDIA-SEQUENCE:%d\n", target, firstSeq)
	if vod {
		b.WriteString("#EXT-X-PLAYLIST-TYPE:VOD\n")
	}
	b.WriteString("#EXT-X-MAP:URI=\"init.mp4\"\n")
	for _, s := range segs {
		fmt.Fprintf(&b, "#EXTINF:%.3f,\n%s\n", s.Duration, s.URI)
	}
	if vod {
		b.WriteString("#EXT-X-ENDLIST\n")
	}
	return b.String()
}

// CacheControl returns the header for one stream object.
func CacheControl(name string, live bool, target int) string {
	switch {
	case strings.HasSuffix(name, ".m4s"), strings.HasSuffix(name, ".ts"),
		strings.HasSuffix(name, ".mp4"), strings.HasSuffix(name, ".aac"):
		return "public, max-age=31536000, immutable"
	case strings.HasSuffix(name, ".m3u8") && !live:
		return "public, max-age=86400"
	case strings.HasSuffix(name, ".m3u8"):
		// Half a target duration: fresh enough to show the next segment,
		// long enough that a million viewers still collapse to a few fetches.
		ttl := target / 2
		if ttl < 1 {
			ttl = 1
		}
		return fmt.Sprintf("public, max-age=%d, stale-while-revalidate=%d", ttl, ttl)
	}
	return "no-store"
}
go
package hls

import (
	"strings"
	"testing"
)

func TestMultivariantListsEveryRendition(t *testing.T) {
	out := Multivariant([]Variant{
		{Bandwidth: 800000, Average: 650000, Resolution: "640x360", Codecs: "avc1.4d401e,mp4a.40.2", URI: "360p/index.m3u8"},
		{Bandwidth: 3000000, Average: 2500000, Resolution: "1280x720", Codecs: "avc1.64001f,mp4a.40.2", URI: "720p/index.m3u8"},
	})
	if !strings.HasPrefix(out, "#EXTM3U\n") || strings.Count(out, "#EXT-X-STREAM-INF:") != 2 {
		t.Fatalf("bad playlist:\n%s", out)
	}
	if !strings.Contains(out, "BANDWIDTH=3000000,AVERAGE-BANDWIDTH=2500000,RESOLUTION=1280x720") {
		t.Fatalf("missing 720p attributes:\n%s", out)
	}
}

func TestMediaLiveVsVOD(t *testing.T) {
	segs := []Segment{{4, "seg_100.m4s"}, {4, "seg_101.m4s"}, {3.2, "seg_102.m4s"}}
	live := Media(4, 100, segs, false)
	vod := Media(4, 0, segs, true)
	if strings.Contains(live, "#EXT-X-ENDLIST") || !strings.Contains(live, "#EXT-X-MEDIA-SEQUENCE:100") {
		t.Fatalf("live playlist wrong:\n%s", live)
	}
	if !strings.HasSuffix(vod, "#EXT-X-ENDLIST\n") || !strings.Contains(vod, "#EXT-X-PLAYLIST-TYPE:VOD") {
		t.Fatalf("vod playlist wrong:\n%s", vod)
	}
	if !strings.Contains(live, "#EXTINF:3.200,\nseg_102.m4s") {
		t.Fatalf("segment line wrong:\n%s", live)
	}
}

func TestCacheControlPerObject(t *testing.T) {
	cases := map[string]string{
		"seg_101.m4s":  "public, max-age=31536000, immutable",
		"init.mp4":     "public, max-age=31536000, immutable",
		"index.m3u8":   "public, max-age=2, stale-while-revalidate=2",
		"unknown.json": "no-store",
	}
	for name, want := range cases {
		if got := CacheControl(name, true, 4); got != want {
			t.Errorf("%s: %q, want %q", name, got, want)
		}
	}
	if got := CacheControl("index.m3u8", false, 4); got != "public, max-age=86400" {
		t.Errorf("VOD playlist: %q", got)
	}
}

The Go angle ​

  • net/http.ServeContent is the origin's best friend: given an io.ReadSeeker, a modification time and an ETag header set beforehand, it answers If-None-Match, If-Modified-Since, Range, If-Range, returns 206 with Content-Range, and 416 for unsatisfiable ranges. http.FileServer uses it.
  • golang.org/x/sync/singleflight (Group.Do, DoChan, Forget) is request coalescing in one type. The leader's context is shared by every waiter; detach it with context.WithoutCancel and bound it with a timeout, as fetchAndStore does, or one impatient client cancels the fetch for everyone.
  • container/list plus a map is the classic O(1) LRU; production caches add sharding (one lock per shard) and admission policies.
  • crypto/hmac with hmac.Equal (constant time) is enough for CDN-style tokens; check the signature before the expiry so a forged exp learns nothing.
  • embed.FS with content-hash names gives a single Go binary that serves immutable assets; httptest.NewServer makes the origin testable from the cache tier, as in edgecache_test.go.
  • For a real edge in Go (self-hosted), net/http/httputil.ReverseProxy handles the proxying; caching, coalescing and key normalisation are what you add.

Laravel ​

Example: Vite fingerprinting, cache headers, purge, signed and temporary URLs ​

The Blade layout uses @vite, which reads the Vite manifest and prints hashed URLs under ASSET_URL (the docs show ASSET_URL=https://cdn.example.com producing https://cdn.example.com/build/assets/app.9dce8d17.js).

php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <title>{{ $title ?? config('app.name') }}</title>
    {{-- With ASSET_URL=https://cdn.example.com this prints
         https://cdn.example.com/build/assets/app-<hash>.css: a new hash on every
         change, so the file can be cached for a year. --}}
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body>
    {{ $slot }}
    <img src="{{ Vite::asset('resources/images/logo.svg') }}" alt="logo">
</body>
</html>
js
// vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
    ],
    build: {
        // `npm run build` writes public/build/manifest.json, which @vite reads
        // to map resources/js/app.js to build/assets/app-<hash>.js.
        manifest: 'manifest.json',
    },
});

A middleware splits browser and CDN lifetimes, adds tags, and turns matching If-None-Match into 304. Routes that are cached remove the session and CSRF middleware so no Set-Cookie header is sent; the built-in cache.headers middleware covers simple pages ("If etag is specified in the list of directives, an xxh128 hash of the response content will automatically be set as the ETag identifier").

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Split caching: browsers always revalidate, the CDN keeps the page.
 *
 * Usage: ->middleware('cdn.cache:300,60,86400')  (edge TTL, SWR, SIE in seconds)
 * Controllers add purge tags with $request->attributes->set('cdn_tags', [...]).
 */
class CdnCacheHeaders
{
    public function handle(Request $request, Closure $next, string $ttl = '300', string $swr = '60', string $sie = '86400'): Response
    {
        $response = $next($request);

        $shareable = $request->isMethodCacheable()
            && $response->isSuccessful()
            && $request->user() === null
            && ! $response->headers->has('Set-Cookie');

        if (! $shareable) {
            // Personal or failed responses must never land in a shared cache.
            $response->headers->set('Cache-Control', 'private, no-store');

            return $response;
        }

        $edge = "max-age={$ttl}, stale-while-revalidate={$swr}, stale-if-error={$sie}";
        $response->headers->set('Cache-Control', 'public, max-age=0, must-revalidate');
        $response->headers->set('CDN-Cache-Control', $edge);   // RFC 9213, read by Cloudflare
        $response->headers->set('Surrogate-Control', $edge);   // read and stripped by Fastly
        $response->headers->set('Vary', 'Accept-Encoding');

        $tags = array_values(array_unique($request->attributes->get('cdn_tags', [])));
        if ($tags !== []) {
            $response->headers->set('Surrogate-Key', implode(' ', $tags)); // Fastly
            $response->headers->set('Cache-Tag', implode(',', $tags));     // Cloudflare
        }

        // Strong validator over the body; isNotModified() turns a matching
        // If-None-Match into 304 and drops the body.
        $response->setEtag(hash('xxh128', (string) $response->getContent()));
        $response->isNotModified($request);

        return $response;
    }
}
php
<?php

// bootstrap/app.php (excerpt): register the alias used in routes/web.php.

use App\Http\Middleware\CdnCacheHeaders;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias([
            'cdn.cache' => CdnCacheHeaders::class,
        ]);
        // Behind Cloudflare or CloudFront, trust the edge so the scheme and
        // client address are right (see the proxies chapter).
        $middleware->trustProxies(at: '*');
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();
php
<?php

use App\Http\Controllers\Admin\ProductPriceController;
use App\Http\Controllers\ExportController;
use App\Http\Controllers\PrivateDownloadController;
use App\Http\Controllers\ProductPageController;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Foundation\Http\Middleware\PreventRequestForgery;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\Support\Facades\Route;
use Illuminate\View\Middleware\ShareErrorsFromSession;

// Public, CDN-cached pages. The web group would start a session and add the
// session and XSRF-TOKEN cookies to every response; a Set-Cookie header makes
// Cloudflare refuse to cache and is a data leak on any CDN told to ignore it.
Route::withoutMiddleware([
    StartSession::class,
    ShareErrorsFromSession::class,
    PreventRequestForgery::class,
    AddQueuedCookiesToResponse::class,
])->group(function () {
    Route::get('/products/{product}', [ProductPageController::class, 'show'])
        ->middleware('cdn.cache:300,60,86400')
        ->name('products.show');

    // Laravel's built-in SetCacheHeaders middleware for simple pages.
    Route::middleware('cache.headers:public;max_age=30;s_maxage=300;stale_while_revalidate=600;etag')
        ->group(function () {
            Route::view('/privacy', 'legal.privacy');
            Route::view('/terms', 'legal.terms');
        });
});

// Private files: authorise in Laravel, then hand the bytes to S3/CloudFront.
Route::get('/downloads/{file}', [PrivateDownloadController::class, 'show'])
    ->middleware('auth')
    ->where('file', '[A-Za-z0-9._/-]+')
    ->name('downloads.show');

// Links in e-mails: no login, the signature is the permission.
Route::get('/exports/{export}', [ExportController::class, 'show'])
    ->middleware('signed')
    ->name('exports.show');

Route::put('/admin/products/{product}/price', [ProductPriceController::class, 'update'])
    ->middleware(['auth', 'can:update,product']);
php
<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class ProductPageController extends Controller
{
    public function show(Request $request, Product $product): Response
    {
        // Every object this page shows becomes a purge tag.
        $request->attributes->set('cdn_tags', [
            "product-{$product->id}",
            "category-{$product->category_id}",
            'products',
        ]);

        return response()->view('products.show', ['product' => $product]);
    }
}

Purges run after the transaction commits, from a queued job with backoff, against Cloudflare (purge_cache with tags) or Fastly (soft purge per surrogate key).

php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Jobs\PurgeCdnTags;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ProductPriceController extends Controller
{
    public function update(Request $request, Product $product): JsonResponse
    {
        $data = $request->validate(['price' => ['required', 'decimal:0,2', 'min:0']]);

        DB::transaction(function () use ($product, $data) {
            $product->update(['price' => $data['price']]);

            // Purge only after COMMIT: purging first lets a request refill the
            // edge with the old row before the transaction is visible.
            PurgeCdnTags::dispatch(["product-{$product->id}", "category-{$product->category_id}"])
                ->afterCommit();
        });

        return response()->json(['id' => $product->id, 'price' => $product->price]);
    }
}
php
<?php

namespace App\Jobs;

use App\Services\CdnPurger;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class PurgeCdnTags implements ShouldQueue
{
    use Queueable;

    public int $tries = 5;

    /** @param list<string> $tags */
    public function __construct(public array $tags, public bool $soft = true) {}

    /** @return list<int> */
    public function backoff(): array
    {
        return [5, 30, 120, 600];
    }

    public function handle(CdnPurger $purger): void
    {
        // Purges are idempotent, so a retry after a timeout is safe.
        $purger->purgeTags($this->tags, $this->soft);
    }
}
php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use InvalidArgumentException;

/**
 * Purge by tag on Cloudflare (Cache-Tag) or Fastly (Surrogate-Key).
 * Tokens come from config/cdn.php; never log them.
 */
class CdnPurger
{
    /** @param list<string> $tags */
    public function purgeTags(array $tags, bool $soft = true): void
    {
        $tags = array_values(array_unique($tags));

        match (config('cdn.driver')) {
            'cloudflare' => $this->cloudflare($tags),
            'fastly' => $this->fastly($tags, $soft),
            'none' => null,
            default => throw new InvalidArgumentException('Unknown CDN driver'),
        };
    }

    /** @param list<string> $tags */
    private function cloudflare(array $tags): void
    {
        $zone = config('cdn.cloudflare.zone_id');

        // The dashboard accepts up to 100 tags per purge; keep API calls in the same range.
        foreach (array_chunk($tags, 100) as $chunk) {
            Http::withToken(config('cdn.cloudflare.api_token'))
                ->timeout(10)
                ->post("https://api.cloudflare.com/client/v4/zones/{$zone}/purge_cache", ['tags' => $chunk])
                ->throw();
        }
    }

    /** @param list<string> $tags */
    private function fastly(array $tags, bool $soft): void
    {
        $service = config('cdn.fastly.service_id');

        foreach ($tags as $tag) {
            Http::withHeaders(array_filter([
                'Fastly-Key' => config('cdn.fastly.api_token'),
                'Accept' => 'application/json',
                // Soft purge marks objects stale instead of deleting them, so
                // stale-while-revalidate and stale-if-error keep working.
                'Fastly-Soft-Purge' => $soft ? '1' : null,
            ]))
                ->timeout(10)
                ->post("https://api.fastly.com/service/{$service}/purge/".rawurlencode($tag))
                ->throw();
        }
    }
}
php
<?php

// config/cdn.php

return [
    'driver' => env('CDN_DRIVER', 'none'), // cloudflare | fastly | none

    'cloudflare' => [
        'zone_id' => env('CLOUDFLARE_ZONE_ID'),
        'api_token' => env('CLOUDFLARE_API_TOKEN'),
    ],

    'fastly' => [
        'service_id' => env('FASTLY_SERVICE_ID'),
        'api_token' => env('FASTLY_API_TOKEN'),
    ],
];

Private files: Storage::temporaryUrl for presigned S3 links, URL::temporarySignedRoute plus the signed middleware for links that Laravel itself verifies.

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PrivateDownloadController extends Controller
{
    public function show(Request $request, string $file): RedirectResponse
    {
        abort_unless($request->user()->can('download-file', $file), 403);

        // A presigned S3 URL that lives five minutes. With CloudFront in front
        // of a private bucket you would sign a CloudFront URL instead, so the
        // bytes come from the edge and the bucket stays closed (OAC).
        $url = Storage::disk('s3')->temporaryUrl(
            "private/{$file}",
            now()->plus(minutes: 5),
            [
                'ResponseContentType' => 'application/octet-stream',
                'ResponseContentDisposition' => 'attachment; filename="'.basename($file).'"',
            ],
        );

        // The redirect itself is personal: never cache it.
        return redirect()->away($url)->header('Cache-Control', 'private, no-store');
    }
}
php
<?php

namespace App\Http\Controllers;

use App\Models\Export;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ExportController extends Controller
{
    /** Build the link that goes into the "your export is ready" e-mail. */
    public static function linkFor(Export $export): string
    {
        return URL::temporarySignedRoute('exports.show', now()->plus(minutes: 30), ['export' => $export->id]);
    }

    /** The 'signed' middleware has already rejected tampered or expired links with 403. */
    public function show(Export $export): StreamedResponse
    {
        return Storage::disk('s3')->download($export->path, $export->filename, [
            'Cache-Control' => 'private, no-store',
        ]);
    }
}
php
<?php

namespace Tests\Feature;

use App\Jobs\PurgeCdnTags;
use App\Models\Product;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\URL;
use Tests\TestCase;

class CdnHeadersTest extends TestCase
{
    use RefreshDatabase;

    public function test_product_page_is_edge_cacheable_and_tagged(): void
    {
        $product = Product::factory()->create();

        $this->get("/products/{$product->id}")
            ->assertOk()
            ->assertHeader('Cache-Control', 'max-age=0, must-revalidate, public')
            ->assertHeader('CDN-Cache-Control', 'max-age=300, stale-while-revalidate=60, stale-if-error=86400')
            ->assertHeader('Cache-Tag', "product-{$product->id},category-{$product->category_id},products")
            ->assertHeaderMissing('Set-Cookie');
    }

    public function test_matching_etag_gives_304(): void
    {
        $product = Product::factory()->create();
        $etag = $this->get("/products/{$product->id}")->headers->get('ETag');

        $this->get("/products/{$product->id}", ['If-None-Match' => $etag])->assertStatus(304);
    }

    public function test_price_change_purges_after_commit(): void
    {
        Queue::fake();
        $product = Product::factory()->create();
        $admin = User::factory()->admin()->create();

        $this->actingAs($admin)->putJson("/admin/products/{$product->id}/price", ['price' => '17.50'])->assertOk();

        Queue::assertPushed(PurgeCdnTags::class, fn ($job) => in_array("product-{$product->id}", $job->tags, true));
    }

    public function test_tampered_signed_link_is_rejected(): void
    {
        $url = URL::temporarySignedRoute('exports.show', now()->plus(minutes: 30), ['export' => 1]);

        $this->get(str_replace('exports/1', 'exports/2', $url))->assertForbidden();
    }
}

The Laravel angle ​

  • The session is the enemy of the edge. The web middleware group in Laravel 13 is EncryptCookies, AddQueuedCookiesToResponse, StartSession, ShareErrorsFromSession, PreventRequestForgery and SubstituteBindings. The session and CSRF middleware add cookies to every response; Cloudflare does not cache a response when "The Set-Cookie header exists". Cached routes must run without them (Route::withoutMiddleware([...])), and must not read the user.
  • cache.headers (Illuminate\Http\Middleware\SetCacheHeaders) takes snake-case directives separated by semicolons and can add an xxh128 ETag; it does not set CDN-Cache-Control or tags, hence the custom middleware.
  • Vite writes hashed files and manifest.json on npm run build; @vite and Vite::asset read the manifest; ASSET_URL prefixes the CDN host. Upload public/build to the bucket before switching HTML.
  • Signed URLs: URL::signedRoute, URL::temporarySignedRoute, $request->hasValidSignature() and the signed middleware (Illuminate\Routing\Middleware\ValidateSignature) protect links that hit Laravel. They are verified by the application, not by the CDN; for edge-verified tokens use the CDN's scheme (CloudFront signed URLs or cookies, Bunny token authentication) and sign them in PHP.
  • Storage::temporaryUrl works for the local and s3 drivers; extra S3 parameters such as ResponseContentDisposition go in the third argument, and buildTemporaryUrlsUsing customises it for other disks.
  • Purging belongs in a queued job dispatched with afterCommit(), using the HTTP client with ->throw() and a backoff; never purge inside the transaction.
  • Trusted proxies: behind a CDN configure trustProxies so URLs and redirects use https and the real client IP; the details are in Forward vs Reverse Proxies.

Solving the classic problems ​

Users run the old JavaScript after a deploy ​

Cause: unversioned asset names with long TTLs, or HTML cached longer than assets. Fix: fingerprint every asset (Vite does), immutable on hashed paths, short or zero browser TTL on HTML, upload assets before switching HTML, keep old assets for a retention window.

SolutionHowAdvantageCost / limitation
Fingerprinted namesVite manifest, Go AddAssetNever stale, no purgeKeep old files during rollout
Purge assets on deployAPI purge of /build/*Works with old namingRace between purge and refill; misses everyone
Short asset TTLmax-age=300SimpleLow hit ratio, still stale for 5 minutes

A logged-in page was shown to another user ​

Cause: a "cache everything" rule, public on a personal response, a cache key without the session, or web cache deception (/account/style.css treated as static). Fix: private, no-store on every personal response; bypass the cache when a session cookie is present; restrict "cache everything" rules to explicit paths; reject unknown path suffixes on personal routes; never cache responses with Set-Cookie.

SolutionHowAdvantageCost / limitation
private, no-store by defaultMiddleware: non-shareable responsesFails safeNeed opt-in for cacheable routes
Bypass on session cookieEdge rule or WorkerProtects even with wrong headersLogged-in users get no edge caching
Strict route matchingNo catch-all suffixesStops cache deceptionFramework config work

The origin melts when a hot object expires or after a purge ​

Cause: thundering herd. Fix: request collapsing at the edge (default on Fastly, consolidated on CloudFront), a shield, stale-while-revalidate, soft purge instead of hard purge, and singleflight in your own caches.

SolutionHowAdvantageCost / limitation
CoalescingCDN default, singleflightOne fetch per keyWaiters share one slow fetch
ShieldTiered Cache, Origin ShieldOne fetch per key globallyOne more hop on misses
stale-while-revalidateHeaderUsers never wait for refreshBrief staleness
Soft purgeFastly-Soft-Purge: 1Purge without a herdOnly on Fastly-style CDNs

Hit ratio is low although TTLs are long ​

Cause: key fragmentation (query strings, Vary: User-Agent, cookies in the key), many PoPs with a long tail, or Set-Cookie on every response. Fix: normalise the key, enable tiering, remove cookies, look at BYPASS and DYNAMIC counts per path, and compute the top miss keys with the SQL above.

SolutionHowAdvantageCost / limitation
Key normalisationAllow-list, sort, drop utm_*Fewer duplicate objectsMust know which params change output
Tiered cacheSmart Tiered Cache, shieldLong tail hits upper tierSmall extra latency on misses
Remove Set-CookieSession-less routesMakes HTML cacheableSeparate authenticated paths

Price changed but the CDN shows the old price ​

Cause: long edge TTL without purge, or purge before commit. Fix: tag pages with entity ids, purge by tag after commit from a queue with retries, keep must-revalidate (no stale serving) on prices if staleness is not acceptable, and cap the edge TTL so a lost purge heals itself.

SolutionHowAdvantageCost / limitation
Tag purge after commitPurgeCdnTags::dispatch()->afterCommit()Precise and fastPurge API dependency
TTL as a safety netEdge TTL 5 to 15 minutesLost purge healsOrigin load proportional to 1/TTL
No SWR on pricesOmit stale directivesNever stale beyond TTLUsers may wait for refresh

Video stalls at the start of a live event ​

Cause: every PoP fetching the live playlist and the newest segment at the same instant, an origin packager without a shield, or a manifest TTL longer than the segment duration (players see no new segment). Fix: shield in front of the packager, coalescing, manifest TTL about half the target duration, immutable segments, and a second CDN for overflow.

SolutionHowAdvantageCost / limitation
Shield + coalescingOrigin Shield or shield POPPackager sees one request per objectShield capacity planning
Manifest TTL = target/2hls.CacheControlFresh enough, still collapsibleShort TTL = more shield traffic
Multi-CDN for eventsSteering by player or DNSSurvives one provider's limitsDouble configuration

The origin is attacked directly ​

Cause: origin address reachable from the internet. Fix: accept only the CDN (Authenticated Origin Pulls / mTLS, OAC for S3, provider IP allow-lists with a secret header as defence in depth), move the origin to a new address after a leak, use full verified TLS to the origin.

SolutionHowAdvantageCost / limitation
mTLS from the CDNCloudflare AOP, client certificate checkCryptographic proofCertificate management
Private bucket + OACCloudFront OACBucket never publicAWS only
IP allow-list + secret headerFirewall + header checkSimpleIP lists change; secret can leak

Choosing ​

SituationRecommendationExtra techniqueReason
Marketing site, docs, blogPull CDN, HTML cached minutes at edgeTag purge on publish, SWR + SIECheap, always up, fast
E-commerce product and category pagesPull CDN, max-age=0 browser, 5 to 15 min edgeTags per product/category, purge after commit, bypass on sessionFresh enough, origin protected
Cart, checkout, accountNot cachedprivate, no-store, API acceleration onlyPersonal data
Public read APIEdge TTL seconds, key allow-listCoalescing, SWRAbsorbs mobile app polling
Authenticated APINot cached at the edgeEdge JWT check, rate limiting, WAFCorrectness over hit ratio
Static assetsPush or pull, fingerprinted, one yearimmutable, keep old versionsNear 100% hit, no purge
User uploads (images)Object storage origin + CDNResizing at edge, signed URLs if privateStorage durability, edge transforms
VOD libraryPush to object storage, CMAF, HLS + DASHShield, signed cookies or prefix tokensSegments immutable, huge byte share
Live eventsOrigin packager + shield + coalescingManifest TTL half target, multi-CDNFlash crowds on the same objects
Low-latency liveLL-HLS on a CDN that supports blocking reloadShort parts, preload hintsLatency is the product
Software downloadsPush, range supportChunked caching, If-RangeLarge files, resumes
Global with strict uptimeMulti-CDNHeader-driven policy, fan-out purgeProvider independence

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A Laravel monolith on one server puts Cloudflare or CloudFront in front of it and gets most of the benefit with three changes: Vite fingerprinting with ASSET_URL, the CdnCacheHeaders middleware on public pages (with session middleware removed), and a queued tag purge after updates. Everything else (TLS, HTTP/3, compression, WAF) the CDN does for free. The simplest correct setup: assets one year immutable, public HTML 5 minutes at the edge with stale-if-error, everything personal private, no-store.

Modular monolith: boundaries without the network ​

Modules own their purge tags. The catalogue module emits product-{id} and category-{id}; the content module emits article-{id}; a page composed of both carries both sets. A module that changes data publishes a domain event; one purge listener maps events to tags. This keeps the "what does this page depend on" knowledge next to the code that renders it, rather than in a central purge script that nobody updates.

Microservices: every arrow is a decision ​

The CDN fronts the API gateway or BFF, not each service. Each service sets caching headers for its own public GET endpoints, and the gateway must pass Cache-Control, CDN-Cache-Control, Surrogate-Key/Cache-Tag and ETag through unchanged. Purges become events:

 1  catalog-svc   UPDATE price; COMMIT; outbox row ProductPriceChanged{id: 42}
 2  relay         publish to broker topic catalog.events
 3  cdn-purger    consume; map to tags [product-42, category-7, search]; POST purge (soft); ack
 4  cdn-purger    on 429/5xx from purge API: retry with backoff; purges are idempotent
 5  edge          next request: STALE + background refresh -> BFF -> catalog-svc (new price)

The outbox and idempotent consumer are owned by Transactional Outbox and Idempotent Consumers. Purging is at-least-once by design.

Distributed data: replicas, caches, regions ​

A purge can race replication. The writer commits on the primary, the purge goes out, a PoP refills from an origin instance that reads from a lagging replica, and the old price is cached again for the full TTL. Defences: purge after the replica has caught up (or read-your-writes on the refill path), a version in the surrogate-key flow (purge again after a delay), short edge TTL on volatile pages, and ETags derived from a version column so a revalidation against a lagging replica does not refresh an entry with old data under a new ETag. With multi-region origins, put a shield per origin region or route the shield to the primary region for HTML. Replica lag mechanics: Replication & Failover.

Scaling path: 1x, 10x, 100x ​

LoadDesignWhat changes
1x (thousands of requests/min)One CDN, default tiering, headers per routeAssets fingerprinted; HTML edge TTL 5 min
10x (tens of thousands/s, launches)Shield enabled, tag purge, SWR + SIE everywhere publicOrigin sized for misses; byte hit ratio tracked; purge via queue
100x (live events, millions concurrent)Multi-CDN, origin packager with shield, object storage for VOD, edge compute for personalisationSteering, fan-out purge, per-CDN dashboards, capacity reservations for events

Lab: cache headers, 304, 206 and a shield, with real output ​

Single-process Go programs only; nothing else is started. Steps 1 to 3 were run on the author's machine (Go 1.27, macOS); the output is pasted as produced. Step 4 is expected, not run.

  1. Run the tests (origin headers, conditional GET, ranges, coalescing, SWR, SIE, LRU, shield, purge, key normalisation, signed URLs, HLS):
cd docs/snippets/system-design/cdn/go
go test ./...
ok   academy/cdn/edgecache  0.189s
ok   academy/cdn/hls        0.052s
ok   academy/cdn/origin     0.056s
ok   academy/cdn/signedurl  0.052s
  1. Start the origin (go run ./cmd/origin, it prints the fingerprinted asset name) and look at the headers:
$ curl -sS -D - -o /dev/null http://127.0.0.1:8080/products/42
HTTP/1.1 200 OK
Cache-Control: public, max-age=0, must-revalidate
Cache-Tag: product-42,category-kitchen,products
Cdn-Cache-Control: max-age=300, stale-while-revalidate=60, stale-if-error=86400
Etag: "8bb0a6a4931615f1"
Surrogate-Control: max-age=300, stale-while-revalidate=60, stale-if-error=86400
Surrogate-Key: product-42 category-kitchen products
Vary: Accept-Encoding

$ curl -sS -D - -o /dev/null -H 'If-None-Match: "8bb0a6a4931615f1"' http://127.0.0.1:8080/products/42
HTTP/1.1 304 Not Modified          (same caching headers, no body)

$ curl -sS -D - -H 'Range: bytes=0-9' http://127.0.0.1:8080/assets/app.b186f4d6.js
HTTP/1.1 206 Partial Content
Accept-Ranges: bytes
Cache-Control: public, max-age=31536000, immutable
Content-Range: bytes 0-9/46
console.lo

$ curl -sS -D - -o /dev/null -H 'Range: bytes=9999-' http://127.0.0.1:8080/assets/app.b186f4d6.js
HTTP/1.1 416 Requested Range Not Satisfiable
Content-Range: bytes */46          (Go dropped Cache-Control and ETag on the error response)

$ curl -sS -D - -o /dev/null http://127.0.0.1:8080/account
HTTP/1.1 200 OK
Cache-Control: private, no-store

Note the 416: Go's ServeContent removes the caching headers from error responses, so the CDN applies its own default for that status (Cloudflare does not cache 416 by default).

  1. Run the hierarchy simulation (20,000 objects, Zipf s=1.1, 8 edges with 64 MiB each, optional 512 MiB shield):
$ go run ./cmd/sim
20000 objects, 400000 requests, 8 edges, Zipf s=1.1
edges -> origin           edge hit 0.667  edge byte hit 0.118  origin fetches 133357 (offload 0.667)  origin GiB 20.74
edges -> shield -> origin  edge hit 0.667  edge byte hit 0.118  origin fetches  72222 (offload 0.819)  origin GiB 17.19
  shield: requests 133357  hit 0.458  byte hit 0.171

Read it: the edges are identical in both runs, so the edge hit ratio is unchanged; the shield turned 46% of edge misses into shield hits, cutting origin fetches by 46%. The byte hit ratios are far below the request hit ratios because the long tail is made of 512 KiB objects that do not fit in small edge caches: exactly the request-vs-byte gap from the hit ratio block.

  1. Against a real CDN (expected, not run): put the origin behind Cloudflare with Smart Tiered Cache and request the product page three times from one location.
1  curl -sI https://shop.example/products/42 | grep -i -E 'cf-cache-status|age'
   cf-cache-status: MISS
2  (again)  cf-cache-status: HIT      age: 3
3  purge by tag product-42 via API, then request: cf-cache-status: MISS (hard purge) 
4  wait > 300 s, request: cf-cache-status: STALE or UPDATING, then HIT (REVALIDATED in logs)

Common misconceptions ​

BeliefReality
A CDN caches my HTML automaticallyCloudflare does not cache HTML or JSON by default; most CDNs need explicit headers or rules
no-cache means not cachedIt means store and revalidate; no-store forbids storing
Purge is the way to deployFingerprint assets; purge is for data changes and emergencies
High hit ratio means low costBytes and origin egress decide cost; watch byte hit ratio
A shield slows everything downIt adds a hop only on edge misses and removes most origin fetches
Vary: User-Agent is a good way to serve mobileIt fragments the cache; key on a normalised device class
206 responses cannot be cachedThey can; Cloudflare caches 206 by default and CloudFront caches fetched ranges
Edge compute brings my database closerOnly the code moves; data calls still cross the network
Signed URLs make the cache uselessKeep signature parameters out of the cache key; all viewers share the object
The CDN protects the originOnly if the origin rejects traffic that did not come through the CDN
Revalidation is freeA 304 saves bytes, not the round trip or the origin request
Live video needs a special serverHLS and DASH are plain HTTP; the CDN caches segments like files
Multi-CDN is two DNS recordsEach CDN needs matching keys, purges, tokens, TLS and logs

Cheat sheet ​

TopicRemember
Hashed assetspublic, max-age=31536000, immutable, never purge
Public HTMLBrowser max-age=0, must-revalidate; CDN max-age=300, stale-while-revalidate=60, stale-if-error=86400
Personalprivate, no-store, no Set-Cookie on cacheable routes
Targeted headersCDN-Cache-Control (Cloudflare, RFC 9213), Surrogate-Control (Fastly)
Shared vs browsers-maxage overrides max-age for shared caches
ValidatorsStrong ETag; answer If-None-Match with 304 and the same headers
StampedeCoalescing + shield + SWR; singleflight in Go
Cache keyInclude what changes bytes; drop utm_*; sort params; Vary: Accept-Encoding only
PurgeTags per entity, after commit, from a queue, soft when possible
RatiosRequest hit ratio, byte hit ratio, origin requests: report all three
VideoSegments immutable; live playlist TTL about half the target duration; CMAF for HLS + DASH
LL-HLSParts, CAN-BLOCK-RELOAD=YES, _HLS_msn/_HLS_part, preload hints
RangesAccept-Ranges, ETag, If-Range; 206 and 416; enable chunked/segmented caching
SecurityWAF at edge, signed URLs/cookies or tokens, lock origin (mTLS/OAC), full TLS to origin
Cloudflare errors521 down, 522 TCP timeout, 524 slow response, 525/526 origin TLS

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A page has Cache-Control: public, max-age=60, s-maxage=600. How long does the browser keep it fresh, and how long does a CDN? Must-know ​

Answer

Answer: The browser uses max-age: 60 seconds. A shared cache uses s-maxage, which overrides max-age for shared caches: 600 seconds (unless a CDN rule or a targeted header such as CDN-Cache-Control says otherwise).

2 — Why does no-cache not stop caching, and what does? Must-know ​

Answer

Answer: no-cache allows storing but requires revalidation before each reuse. no-store forbids storing; private forbids shared caches only.

3 — Your edge hit ratio is 96% but the origin egress bill went up. Give two explanations. Important ​

Answer

Answer: The misses are the large objects (byte hit ratio is low), and/or tiering was disabled so each PoP fetches misses from the origin separately. Revalidations with a body, Range misses on large files and purges also add origin bytes.

4 — A hot JSON object with a 1 s TTL is requested 5,000 times per second at each of 200 PoPs. Without coalescing or a shield, roughly how many origin requests per second at worst, and with both? Must-know ​

Answer

Answer: Without coalescing, at each expiry every concurrent request can miss: up to thousands per PoP per second, hundreds of thousands in total. With per-PoP coalescing it is about one per PoP per second (200/s); with a shield as well, about one per second.

5 — What exactly does stale-if-error=86400 permit, and when should you not send it? Important ​

Answer

Answer: When the cache hits an error (5xx, timeout, connection failure) while refreshing, it may serve the stale copy for up to 86,400 seconds past its freshness. Do not send it for content where a stale value is harmful: prices at checkout, stock, legal or security-sensitive content.

6 — Why is ?v=2 weaker than a hash in the file name? Important ​

Answer

Answer: It depends on every cache keeping the query string in the key, on someone remembering to bump it, and it does not let two versions coexist safely. A content hash changes automatically with content and works with any cache.

7 — A product page reads an A/B cookie. How do you cache it without serving the wrong variant? Important ​

Answer

Answer: Keep the number of variants small and put the bucket (not the raw cookie) in the cache key at the edge (Worker, VCL, cache policy with that one cookie), or move the variant into the URL. Never cache it with the cookie ignored.

8 — Why should a purge run after COMMIT, not inside the transaction? Important ​

Answer

Answer: If the purge runs first, a request can refill the edge from the database before the new value is visible, caching the old value for the full TTL. After commit (and ideally after replicas catch up) the refill sees the new data.

9 — In HLS, which objects get long TTLs and which short, for live and VOD? Important ​

Answer

Answer: Segments and init segments are immutable: long TTLs for both live and VOD. VOD playlists are complete (EXT-X-ENDLIST): long TTL. Live media playlists change every segment: TTL about half the target duration so players see new segments while the CDN still collapses refreshes.

10 — How does a signed URL coexist with a high hit ratio on video segments? Important ​

Answer

Answer: The edge verifies the token (signature over a path prefix and expiry) and then looks up the object with a cache key that excludes the token parameters, so every authorised viewer shares one cached segment. Signed cookies achieve the same without query parameters.

11 — Name three ways to make sure attackers cannot bypass the CDN. Must-know ​

Answer

Answer: mTLS from the CDN to the origin (Cloudflare Authenticated Origin Pulls), private object storage reached only through the CDN (CloudFront OAC), and a firewall allow-list of CDN ranges plus a secret header. Also rotate the origin address if it leaked.

12 — Why does Go's singleflight need a detached context in a cache? Good to know ​

Answer

Answer: All waiters share the leader's call. If the fetch uses the leader's request context and that client disconnects, the fetch is cancelled and every waiter fails. Use context.WithoutCancel with a timeout for the shared fetch.

Glossary ​

TermMeaning
CDNContent delivery network: shared caches and proxies near users, in front of an origin
EdgeThe PoPs closest to users; also code and caches running there
PoPPoint of presence: one CDN site (data centre)
OriginThe server or bucket that holds the source of truth
AnycastOne IP prefix announced from many sites; routing picks a near one
GeoDNSDNS answers chosen by the client's or resolver's location
Pull CDNCaches fill on demand by fetching from the origin on a miss
Push CDNContent uploaded to CDN or CDN-read storage ahead of requests
Shared cacheA cache that stores responses for more than one user (RFC 9111)
Private cacheA single user's cache, usually the browser
Cache keyIdentifier under which a response is stored; method + URI + Vary inputs, as shaped by the CDN
Cache-ControlResponse and request header carrying caching directives
max-ageFreshness lifetime in seconds for all caches
s-maxageFreshness lifetime for shared caches, overriding max-age
CDN-Cache-ControlRFC 9213 header targeted at CDN caches
Surrogate-ControlFastly's targeted freshness header, removed before the client
no-store / private / no-cacheDo not store / not in shared caches / store but revalidate
immutableRFC 8246: no revalidation while fresh
ETagOpaque validator of a representation
If-None-MatchConditional request header carrying ETags
304 Not ModifiedConditional request whose condition was false; reuse the stored body
RevalidationChecking a stored response with the origin using validators
stale-while-revalidateServe stale for N s while refreshing in the background (RFC 5861)
stale-if-errorServe stale for N s when the origin errors (RFC 5861)
Request coalescingCollapsing concurrent misses for a key into one upstream request
Collapsed forwardingAnother name for request coalescing
Thundering herdMany simultaneous misses hitting the origin at once (cache stampede)
singleflightGo package suppressing duplicate in-flight calls per key
Tiered cachingLower-tier caches ask upper tiers before the origin
Origin shieldOne designated cache tier in front of the origin
Cache hit ratioShare of requests served from cache
Byte hit ratioShare of bytes served from cache
Origin offloadShare of edge requests (or bytes) that did not reach the origin
VaryResponse header naming request headers that select the variant
Accept-EncodingRequest header listing acceptable compressions (br, gzip)
Query string normalisationSorting, dropping and allow-listing query parameters in the key
PurgeRemoving or invalidating cached objects before expiry
Soft purgeMarking objects stale instead of deleting them
Surrogate keyFastly tag on a response for group purge (Surrogate-Key)
Cache tagCloudflare/Akamai tag for group purge (Cache-Tag on Cloudflare)
FingerprintingContent hash in the asset file name
Versioned assetAn asset whose URL changes when its content changes
Vite manifestmanifest.json mapping source files to hashed build files for @vite
Edge computeCustomer code in the CDN: Workers, Compute, CloudFront Functions, Lambda@Edge
WorkersCloudflare's edge compute platform
Lambda@EdgeAWS Lambda functions replicated to CloudFront locations
ComputeFastly's edge computing platform
ESIEdge Side Includes: fragment assembly by surrogates (W3C Note 2001)
WAFWeb application firewall: request rules at the edge
Signed URLURL with an expiry and signature that the CDN or app verifies
Signed cookieCookie carrying a signed policy for many files (CloudFront)
Token authenticationCDN-verified token in the URL (Bunny, Akamai)
temporaryUrlLaravel Storage::temporaryUrl: presigned, expiring file URL
Hotlink protectionBlocking embeds of your files on other sites (Referer checks)
Origin pull TLSTLS (often mTLS) on the CDN-to-origin connection
HLSHTTP Live Streaming (RFC 8216): playlists + segments
DASHMPEG-DASH (ISO/IEC 23009-1): MPD manifest + segments
CMAFCommon Media Application Format (ISO/IEC 23000-19), fMP4 segments for HLS and DASH
Adaptive bitratePlayer picks the rendition per segment from throughput and buffer
ManifestPlaylist (HLS) or MPD (DASH) describing renditions and segments
SegmentA few seconds of media in one file
Low-latency HLSPartial segments, blocking playlist reload, preload hints
Live / VODSliding window that grows vs a complete presentation
PackagingCutting encoded renditions into segments and writing manifests
Range requestRequest for part of a representation (Range: bytes=)
206 Partial ContentSuccessful range response with Content-Range
Multi-CDNUsing several CDNs with steering and failover
Egress costPrice per GB of data leaving a cloud or network

References ​

Built by Morteza Negahi