Putting a CDN in front of an origin and reading cache status
Run a small origin and a local stand-in for a CDN edge on your own machine, then watch Cache-Status and Age through a miss and a hit, a revalidation with a 304, a release with versioned URLs, a purge, and two cache-key mistakes; finish by mapping the same signals to a real CDN.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Write the origin
- Step 2: Write the edge
- Step 3: Build release 1 and start both servers
- Step 4: A miss, then hits
- Step 5: A revalidation answered with 304
- Step 6: Release 2 with versioned URLs
- Step 7: Purge a file that is not versioned
- Step 8: Two cache-key mistakes and the fix
- Step 9: Stop the servers
- Reading the same signals on a real CDN
- Check your understanding
- Apply it
- Review prompt
Lessons of CDN & Edge Delivery
- How a CDN request is served: edge, tiers and origin Concept · 20 min
- HTTP caching headers and cache keys Concept · 20 min
- Invalidation, versioned assets and signed URLs Concept · 15 min
- Putting a CDN in front of an origin and reading cache status Lab · 25 min
- Offload ratio, egress cost and edge compute Worked example · 20 min
- Edge delivery check Knowledge check · 6 questions
What you will learn
- Choose pull or push CDN delivery and set Cache-Control, cache keys and TTLs for static, media and personalized responses.
- Plan invalidation, versioned asset URLs, origin shielding and signed URLs for protected content.
Prerequisites: Caching Strategies
01. Goal and setup
In this lab you put a cache in front of an origin and read, from response headers alone, what it did with each request: a miss and a hit, a revalidation answered with 304, a release that changes asset URLs, a purge, and two cache-key mistakes.
This is a local stand-in, not a real CDN, so no CDN account is needed. edge.py plays one edge location: about 140 lines of Python that keep responses in memory, follow a small part of RFC 9111 and report each decision in a Cache-Status header (RFC 9211). It has no tiers, no request collapsing and no Vary support, and a restart empties it. Its headers are the ones you will read on a real CDN; the last section maps them to Cloudflare and CloudFront.
You need Python 3.10 or later and curl, in a bash or zsh shell on Linux or macOS (on Windows, use WSL 2). The lab was tested with Python 3.12.13 and curl 7.81.0. Both servers listen on 127.0.0.1 only: the origin on port 18741 and the edge on port 18740. When you are done, the folder looks like this:
cdn-lab/
origin.py the origin server: files from site/ plus a /thumb route
edge.py the edge cache stand-in
build.py a build step that names the script after its content
peek.sh prints the status line, cache headers and first body line
src/app.js the script before it is built
site/ what the origin serves (index.html, logo.svg, assets/)mkdir cdn-lab && cd cdn-lab
mkdir -p src site
python3 --version
curl --version | head -n 1 | cut -d' ' -f1-2Python 3.12.13
curl 7.81.002. Step 1: Write the origin
The origin serves files from site/ and a /thumb?w=<width> route that returns a different body for each width. The policy function gives each kind of file the headers from lesson 2: fingerprinted assets are cacheable for a year, HTML must be revalidated before every reuse, and everything else is fresh for five minutes. Every response carries an ETag, and the origin answers If-None-Match with a 304 when the content is unchanged. It logs one line per request to show what reached the origin. Save it as origin.py in cdn-lab.
"""origin.py: the origin server for the CDN lab. Serves ./site and /thumb."""
import hashlib
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
PORT = int(os.environ.get("ORIGIN_PORT", "18741"))
SITE = Path("site").resolve()
def policy(path: str) -> str:
"""The Cache-Control value for each kind of file."""
if path.startswith("/assets/"):
return "public, max-age=31536000, immutable" # fingerprinted names
if path.endswith(".html"):
return "no-cache" # may be stored, but must be checked before each reuse
return "public, max-age=300" # everything else: five minutes
class Origin(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_GET(self) -> None:
url = urlsplit(self.path)
if url.path == "/thumb":
width = parse_qs(url.query).get("w", ["100"])[0]
return self.answer(f"thumbnail {width}px wide\n".encode(), "/thumb")
name = "/index.html" if url.path == "/" else url.path
file = (SITE / name.lstrip("/")).resolve()
if not file.is_file() or SITE not in file.parents:
return self.answer(b"not found\n", name, code=404)
self.answer(file.read_bytes(), name)
def answer(self, body: bytes, name: str, code: int = 200) -> None:
etag = '"' + hashlib.sha256(body).hexdigest()[:16] + '"'
if code == 200 and etag in self.headers.get("If-None-Match", ""):
code, body = 304, b"" # the caller's copy is still current
self.send_response(code)
self.send_header("Cache-Control", policy(name))
self.send_header("ETag", etag)
if code != 304:
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_request(self, code="-", size="-") -> None:
print(f"origin: {self.command} {self.path} -> {int(code)}", flush=True)
if __name__ == "__main__":
print(f"origin on 127.0.0.1:{PORT}, serving {SITE.name}/", flush=True)
ThreadingHTTPServer(("127.0.0.1", PORT), Origin).serve_forever()03. Step 2: Write the edge
Read edge.py before you run it, because every result in this lab comes from one of its rules:
cache_keybuilds the key from the request target.KEY_QUERY=full(the default) keeps the whole path and query string,nonedrops the query string, andallow:wkeeps only the listed parameters.why_not_storerefuses non-200 responses,no-storeorprivate, a request withAuthorizationunless a directive allows shared caching, and any response that sets a cookie. HTTP allows storing that last one; refusing it is a safety policy, like Cloudflare's default.lifetimeusess-maxage, thenmax-age, and treatsno-cacheas a lifetime of zero, so such a response is stored but checked with the origin each time.do_GETserves a fresh entry as ahitwithAge. Otherwise it forwards the request, addingIf-None-Matchwhen it holds a copy with an ETag. A 304 refreshes the stored copy, which the user receives as a normal 200.do_PURGEdeletes the entry for a URL's cache key, for anyone who asks. Real CDNs offer purge through an API; some, such as Fastly, also accept aPURGErequest sent to the URL itself. Fastly does not require authentication for URL purges by default and recommends turning it on, so that each purge must carry an API token in aFastly-Keyheader. Check that strangers cannot purge your cache.
Save it as edge.py.
"""edge.py: a tiny stand-in for one CDN edge cache. For learning only.
It keeps responses in memory, follows a small subset of RFC 9111 and says what
it did in a Cache-Status header (RFC 9211). No Vary, no request collapsing.
"""
import http.client
import os
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qsl, urlencode, urlsplit
PORT = int(os.environ.get("EDGE_PORT", "18740"))
ORIGIN_PORT = int(os.environ.get("ORIGIN_PORT", "18741"))
KEY_QUERY = os.environ.get("KEY_QUERY", "full") # full | none | allow:a,b
NAME = "edge-lab"
SKIP = {"host", "connection", "if-none-match", "if-modified-since"}
DROP = {"connection", "keep-alive", "transfer-encoding", "content-length"}
SHARED_OK = {"public", "s-maxage", "must-revalidate"} # RFC 9111 section 3.5
CACHE: dict[str, dict] = {}
def cache_key(target: str) -> str:
"""The part of the request that picks a stored response."""
url = urlsplit(target)
if KEY_QUERY == "none":
return url.path
if KEY_QUERY.startswith("allow:"):
allowed = set(KEY_QUERY.removeprefix("allow:").split(","))
kept = sorted(p for p in parse_qsl(url.query) if p[0] in allowed)
return url.path + ("?" + urlencode(kept) if kept else "")
return target # "full": path and query string exactly as sent
def directives(headers) -> dict[str, str]:
found = {}
for part in headers.get("Cache-Control", "").split(","):
name, _, value = part.strip().lower().partition("=")
if name:
found[name] = value
return found
def why_not_store(status: int, request, headers) -> str | None:
cc = directives(headers)
if status != 200:
return "status"
if "no-store" in cc or "private" in cc:
return "no-store-or-private"
if "Authorization" in request and not SHARED_OK & cc.keys():
return "authorization"
if "Set-Cookie" in headers:
return "set-cookie" # a policy choice: never share one user's cookie
if "Vary" in headers:
return "vary-unsupported"
return None
def lifetime(headers) -> int:
"""Seconds a shared cache may reuse the response without asking the origin."""
cc = directives(headers)
if "no-cache" in cc:
return 0
for name in ("s-maxage", "max-age"):
if cc.get(name, "").isdigit():
return int(cc[name])
return 0
class Edge(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_GET(self) -> None:
key = cache_key(self.path)
entry = CACHE.get(key)
now = time.time()
if entry and now - entry["stored_at"] < entry["ttl"]:
age = int(now - entry["stored_at"])
status = f"hit; ttl={entry['ttl'] - age}"
return self.reply(200, entry["headers"], entry["body"], status, key, age)
extra = {}
if entry and "ETag" in entry["headers"]:
extra["If-None-Match"] = entry["headers"]["ETag"]
code, headers, body = self.forward(extra)
if code == 304 and entry:
for name in ("Cache-Control", "ETag", "Date"):
if name in headers:
del entry["headers"][name]
entry["headers"][name] = headers[name]
entry["stored_at"], entry["ttl"] = now, lifetime(entry["headers"])
status = "fwd=stale; fwd-status=304"
return self.reply(200, entry["headers"], entry["body"], status, key)
fwd = "fwd=stale" if entry else "fwd=uri-miss"
reason = why_not_store(code, self.headers, headers)
if reason:
CACHE.pop(key, None)
status = f"{fwd}; stored=?0; detail={reason}"
else:
CACHE[key] = {"headers": headers, "body": body,
"stored_at": now, "ttl": lifetime(headers)}
status = f"{fwd}; stored"
self.reply(code, headers, body, status, key)
def do_PURGE(self) -> None:
key = cache_key(self.path)
found = CACHE.pop(key, None) is not None
body = f"{'purged' if found else 'not cached'} {key}\n".encode()
self.send_response_only(200 if found else 404)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def forward(self, extra: dict):
conn = http.client.HTTPConnection("127.0.0.1", ORIGIN_PORT, timeout=5)
sent = {k: v for k, v in self.headers.items() if k.lower() not in SKIP}
conn.request("GET", self.path, headers=sent | extra)
resp = conn.getresponse()
body = resp.read()
conn.close()
return resp.status, resp.msg, body
def reply(self, code, headers, body, status, key, age=None) -> None:
self.send_response_only(code)
for name, value in headers.items():
if name.lower() not in DROP:
self.send_header(name, value)
if age is not None:
self.send_header("Age", str(age))
self.send_header("Cache-Status", f'{NAME}; {status}; key="{key}"')
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args) -> None:
pass # stay quiet: origin.log shows what reached the origin
if __name__ == "__main__":
print(f"edge on 127.0.0.1:{PORT}, KEY_QUERY={KEY_QUERY}", flush=True)
ThreadingHTTPServer(("127.0.0.1", PORT), Edge).serve_forever()04. Step 3: Build release 1 and start both servers
build.py copies src/app.js to site/assets/ under a name that contains the first eight hex digits of its SHA-256 hash, and writes an index.html that loads it. peek.sh sends one GET request through the edge and prints only the lines you need, or a hint when no response came back. Save both, then build release 1, create a logo, and start the origin and the edge in the background. Each echo $! saves a process ID so that you can stop the servers later. An interactive shell may also print job lines such as [1] 48211 or Terminated; ignore them.
"""build.py: give app.js a content-based name and write index.html."""
import hashlib
import sys
from pathlib import Path
release = sys.argv[1]
js = Path("src/app.js").read_bytes()
name = f"app.{hashlib.sha256(js).hexdigest()[:8]}.js" # new content, new name
assets = Path("site/assets")
assets.mkdir(parents=True, exist_ok=True)
(assets / name).write_bytes(js)
html = f'<h1>Release {release}</h1><script src="/assets/{name}"></script>\n'
Path("site/index.html").write_text(html)
print("built", name)# peek.sh: one GET request; print the status line, cache headers and first body line
rm -f body.txt
curl -s -o body.txt -D - "$1" | tr -d '\r' | grep -iE '^(HTTP/|age:|cache-status:)'
if [ -s body.txt ]; then head -n 1 body.txt
else echo "(no response: check edge.log)"; fiprintf 'console.log("release 1");\n' > src/app.js
printf '<svg xmlns="http://www.w3.org/2000/svg"><text y="20">logo v1</text></svg>\n' \
> site/logo.svg
python3 build.py 1
python3 origin.py > origin.log 2>&1 & echo $! > origin.pid
python3 edge.py > edge.log 2>&1 & echo $! > edge.pid
sleep 1
cat origin.log edge.logbuilt app.8f9dbbdd.js
origin on 127.0.0.1:18741, serving site/
edge on 127.0.0.1:18740, KEY_QUERY=full05. Step 4: A miss, then hits
Request the fingerprinted script three times, the last one after two seconds, then look at the origin log.
JS=$(ls site/assets)
sh peek.sh http://127.0.0.1:18740/assets/$JS
sh peek.sh http://127.0.0.1:18740/assets/$JS
sleep 2
sh peek.sh http://127.0.0.1:18740/assets/$JS
cat origin.logHTTP/1.1 200 OK
Cache-Status: edge-lab; fwd=uri-miss; stored; key="/assets/app.8f9dbbdd.js"
console.log("release 1");
HTTP/1.1 200 OK
Age: 0
Cache-Status: edge-lab; hit; ttl=31536000; key="/assets/app.8f9dbbdd.js"
console.log("release 1");
HTTP/1.1 200 OK
Age: 2
Cache-Status: edge-lab; hit; ttl=31535998; key="/assets/app.8f9dbbdd.js"
console.log("release 1");
origin on 127.0.0.1:18741, serving site/
origin: GET /assets/app.8f9dbbdd.js -> 200The first request is fwd=uri-miss; stored: the edge had nothing under this key, went to the origin and kept the response. The next two are hits: Age grows with the time the copy has been cached, and ttl (freshness left, in seconds) shrinks by the same amount. The origin saw one request.
06. Step 5: A revalidation answered with 304
sh peek.sh http://127.0.0.1:18740/
sh peek.sh http://127.0.0.1:18740/
tail -n 2 origin.logHTTP/1.1 200 OK
Cache-Status: edge-lab; fwd=uri-miss; stored; key="/"
<h1>Release 1</h1><script src="/assets/app.8f9dbbdd.js"></script>
HTTP/1.1 200 OK
Cache-Status: edge-lab; fwd=stale; fwd-status=304; key="/"
<h1>Release 1</h1><script src="/assets/app.8f9dbbdd.js"></script>
origin: GET / -> 200
origin: GET / -> 304The HTML is stored, but no-cache forbids reusing it unchecked. The second request therefore goes forward with If-None-Match, the origin answers 304 without a body, and the edge sends you its stored copy with a 200. fwd=stale; fwd-status=304 records that. Revalidation costs a round trip but almost no bytes.
07. Step 6: Release 2 with versioned URLs
Change the script and build again. The new content gets a new file name, and index.html now points to it.
printf 'console.log("release 2");\n' > src/app.js
python3 build.py 2
sh peek.sh http://127.0.0.1:18740/
ls site/assetsbuilt app.aadae269.js
HTTP/1.1 200 OK
Cache-Status: edge-lab; fwd=stale; stored; key="/"
<h1>Release 2</h1><script src="/assets/app.aadae269.js"></script>
app.8f9dbbdd.js
app.aadae269.jsThe revalidation of / found a new ETag, so the origin sent the full new page (fwd=stale; stored). No purge was needed: the HTML is checked on every use, and the script has a URL it never had before. Fetch the new script, then the old one:
sh peek.sh http://127.0.0.1:18740/assets/app.aadae269.jsHTTP/1.1 200 OK
Cache-Status: edge-lab; fwd=uri-miss; stored; key="/assets/app.aadae269.js"
console.log("release 2");sh peek.sh http://127.0.0.1:18740/assets/app.8f9dbbdd.jsHTTP/1.1 200 OK
Age: 2
Cache-Status: edge-lab; hit; ttl=31535998; key="/assets/app.8f9dbbdd.js"
console.log("release 1");The new script misses once, like any new URL. The old one is still a hit, so a browser that loaded release 1 before the deploy can still fetch the script its page names.
08. Step 7: Purge a file that is not versioned
logo.svg keeps its name between releases and is fresh for 300 seconds. Cache it, change it at the origin, request it again, then purge it.
sh peek.sh http://127.0.0.1:18740/logo.svg
printf '<svg xmlns="http://www.w3.org/2000/svg"><text y="20">logo v2</text></svg>\n' \
> site/logo.svg
sh peek.sh http://127.0.0.1:18740/logo.svg
curl -s -X PURGE http://127.0.0.1:18740/logo.svg
sh peek.sh http://127.0.0.1:18740/logo.svgHTTP/1.1 200 OK
Cache-Status: edge-lab; fwd=uri-miss; stored; key="/logo.svg"
<svg xmlns="http://www.w3.org/2000/svg"><text y="20">logo v1</text></svg>
HTTP/1.1 200 OK
Age: 0
Cache-Status: edge-lab; hit; ttl=300; key="/logo.svg"
<svg xmlns="http://www.w3.org/2000/svg"><text y="20">logo v1</text></svg>
purged /logo.svg
HTTP/1.1 200 OK
Cache-Status: edge-lab; fwd=uri-miss; stored; key="/logo.svg"
<svg xmlns="http://www.w3.org/2000/svg"><text y="20">logo v2</text></svg>After the change the edge still served logo v1 as a hit: the copy was fresh, so it had no reason to ask the origin. The purge removed the entry, and the next request fetched logo v2. A browser that already held v1 would keep it for up to 300 seconds, because no purge reaches a browser.
09. Step 8: Two cache-key mistakes and the fix
With the default key, a tracking parameter that does not change the thumbnail still creates a second entry:
sh peek.sh "http://127.0.0.1:18740/thumb?w=200"
sh peek.sh "http://127.0.0.1:18740/thumb?w=200&utm_source=mail"
tail -n 2 origin.logHTTP/1.1 200 OK
Cache-Status: edge-lab; fwd=uri-miss; stored; key="/thumb?w=200"
thumbnail 200px wide
HTTP/1.1 200 OK
Cache-Status: edge-lab; fwd=uri-miss; stored; key="/thumb?w=200&utm_source=mail"
thumbnail 200px wide
origin: GET /thumb?w=200 -> 200
origin: GET /thumb?w=200&utm_source=mail -> 200That is a split: two keys, two origin requests, one image. A tempting fix is to ignore the query string altogether. Restart the edge with KEY_QUERY=none and ask for two widths:
kill $(cat edge.pid)
KEY_QUERY=none python3 edge.py > edge.log 2>&1 & echo $! > edge.pid
sleep 1
sh peek.sh "http://127.0.0.1:18740/thumb?w=200"
sh peek.sh "http://127.0.0.1:18740/thumb?w=800"HTTP/1.1 200 OK
Cache-Status: edge-lab; fwd=uri-miss; stored; key="/thumb"
thumbnail 200px wide
HTTP/1.1 200 OK
Age: 0
Cache-Status: edge-lab; hit; ttl=300; key="/thumb"
thumbnail 200px wideThe request for an 800-pixel thumbnail received the 200-pixel one, reported as a perfectly healthy hit with key="/thumb". This wrong merge is the dangerous direction: no error, just the wrong content, and with personal data it would be a leak. The fix is an allow-list of the parameters that really change the response:
kill $(cat edge.pid)
KEY_QUERY=allow:w python3 edge.py > edge.log 2>&1 & echo $! > edge.pid
sleep 1
for q in "w=200" "w=200&utm_source=mail" "w=800"; do
sh peek.sh "http://127.0.0.1:18740/thumb?$q"
doneHTTP/1.1 200 OK
Cache-Status: edge-lab; fwd=uri-miss; stored; key="/thumb?w=200"
thumbnail 200px wide
HTTP/1.1 200 OK
Age: 0
Cache-Status: edge-lab; hit; ttl=300; key="/thumb?w=200"
thumbnail 200px wide
HTTP/1.1 200 OK
Cache-Status: edge-lab; fwd=uri-miss; stored; key="/thumb?w=800"
thumbnail 800px wide10. Step 9: Stop the servers
kill $(cat edge.pid) $(cat origin.pid)
sleep 1
curl -s http://127.0.0.1:18740/ || echo "edge stopped"edge stopped11. Reading the same signals on a real CDN
A real CDN reports the same decisions, often in its own header. Cloudflare's cf-cache-status uses these values:
HITandMISS: as in the lab.REVALIDATED: the origin confirmed the stored copy, likefwd=stale; fwd-status=304here.EXPIRED: a stale copy was replaced by a new one from the origin.BYPASS: the response was not cacheable, for example because it set a cookie.DYNAMIC: the request was never eligible for the cache. Cloudflare decides eligibility partly by file extension, so HTML showsDYNAMICuntil a Cache Rule makes it eligible.
Cloudflare sends Age on hits, but not on a miss or after revalidating with the origin. CloudFront logs Hit, RefreshHit (expired, so checked with the origin) or Miss; if you enable the Server-Timing header in a response headers policy, responses carry cdn-cache-hit, cdn-cache-refresh or cdn-cache-miss.
To check your own site, filter its response headers; this filter accepts several providers' header names:
curl -s -o /dev/null -D - https://www.example.com/assets/app.3f9a2c1e.js \
| grep -iE '^(age|cache-status|cf-cache-status|x-cache|server-timing):'cf-cache-status: HIT
age: 512412. Check your understanding
13. Apply it
Take the lab further before the practice project:
- Add
stale-if-error: when the origin cannot be reached, letdo_GETserve a stored copy still inside itsstale-if-errorwindow. Stop the origin and check thatlogo.svgis still served. - Add a header that tags responses with a cache tag, and a
PURGEvariant that removes every entry with a given tag. - Put your static site behind a CDN free tier, repeat steps 4 to 7 with the
curlfilter above, and note which provider status matches each lab line.
14. Review prompt
Without looking back, answer in your own words:
- What did
Ageandttlshow on the second and third request in step 4, and why do they move in opposite directions? - Why did the user receive a 200 in step 5 when the origin answered 304?
- Why did release 2 need no purge, while the logo did?
- Describe the split and the wrong merge from step 8, and why the allow-list fixes both.
References
- RFC 9211: The Cache-Status HTTP Response Header Field
- RFC 9111: HTTP Caching
- Cloudflare cache responses (CF-Cache-Status and Age)
- Standard logging reference: x-edge-result-type (Amazon CloudFront)
- Increase the cache hit ratio (Amazon CloudFront)
- Understand response headers policies: the Server-Timing header (Amazon CloudFront)
- Authenticating URL purge requests via API (Fastly documentation)
- http.server: HTTP servers (Python 3.12)
- HTTP caching (MDN)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.