Lab — Cloudflare CDN, R2 and the Worker sample
Time: 120 minutes — 10 pre-flight, 10 buckets, 20 Worker, 25 cache, 15 measure, 20 evidence, 10 teardown, 10 buffer.
Prerequisite: an active Cloudflare zone for your root domain (registered and added in S1 self-study), a Cloudflare account with R2 enabled, Node ≥ 22.12, and the sample folder. If your zone is not active, use the fallback chain at the end — full marks remain available.
You need to know: a CDN copies an origin's bytes to an edge near the viewer. A hit is served from the edge; a miss pays the round trip to the origin and then stores a copy. The TTL is how long that copy stays fresh. An R2 custom domain exposes every key in its bucket, so public and private objects must live in different buckets. A Worker reaches a private bucket through a binding, and a Cache Rule decides what a proxied zone is allowed to keep. The lesson page above carries the full mechanism; this brief stops only to explain what each command does.
Safe-data acknowledgement: I have read the lab safe-data policy. I will use only the course-supplied synthetic media, will not upload real personal media, and will not put account IDs, emails, tokens or signing keys in screenshots or logs.
Task
Deploy the S4 catalogue sample on Cloudflare: two R2 buckets, the Worker on workers.dev, an R2 custom domain for public thumbnails, and a Cache Rule on that hostname. Prove a hit and a miss, reproduce the stale-update failure, recover with a purge, fix the design with a versioned key, and prove the private catalogue is unreachable through the public hostname.
| Piece | Name | Visibility |
|---|---|---|
| Public media bucket | course-media-public — thumbs/thumb-0001.jpg, thumbs/thumb-0001.v2.jpg, thumbs/manifest.json |
Public through media.<root> |
| Private catalogue bucket | course-catalogue — catalogue.json, files/asset-0001.txt |
Worker binding only; no public hostname |
| Worker | course-catalogue — /health, /assets, /asset/:id, /asset/:id/file?exp=&sig=, / |
https://course-catalogue.<sub>.workers.dev |
| Cache Rule | Cache Everything on media.<root>/thumbs/*, Edge TTL 2 h, Browser TTL 60 s |
Zone-scoped |
Steps
0. Pre-flight: prove the zone and the toolchain
The Cache Rule step later needs a proxied zone; a Worker alone does not give you one. Check the nameservers first, so a failure at step 8 is not a surprise.
# Show the zone's authoritative nameservers. Two Cloudflare nameservers means
# the S1 registration and NS change worked and the zone is active.
dig NS <root> +short
# Node must be 22.12 or newer: the current Wrangler refuses older releases.
node --version
# Confirm which Cloudflare account Wrangler is using, without printing its ID.
npx wrangler whoami
Expected: exactly two *.ns.cloudflare.com nameservers, v22.12.0 or newer, and one account listed.
Panel path: Cloudflare dashboard → the zone → Overview must show Active, and R2 → Overview must show the subscription enabled (the one-time checkout). Without the R2 checkout no bucket exists and no S3 token can be created.
1. Copy the sample and run its tests
The sample is the deployable half of this session. Its tests run offline, against a mocked R2 binding, so they prove the Worker logic before any cloud resource exists.
# Copy the sample out of the course repository (or unzip the Classroom copy).
cp -r course/samples/s4-worker-catalogue ~/s4-worker-catalogue
cd ~/s4-worker-catalogue
# Install the pinned Wrangler and Vitest versions.
npm install
# Run the eight behaviour tests: health, list, detail, the three capability
# refusals, a valid capability, the landing page, no-store headers and
# public/private key isolation. All eight must pass.
npm test
Expected: Test Files 1 passed, Tests 8 passed. If npm test fails, stop: a deployment of a failing Worker cannot produce valid evidence.
2. Create the two buckets
The two-bucket split is the safety design, not tidiness. An R2 custom domain exposes every key in its bucket, so a single bucket would make the private catalogue public the moment the thumbnail hostname is attached.
# Create the public bucket for thumbnails; the custom domain will attach here.
npx wrangler r2 bucket create course-media-public
# Create the private bucket for the catalogue; it never gets a public hostname.
npx wrangler r2 bucket create course-catalogue
Panel path: R2 → Create bucket twice with the same two names. If a name is taken, add a unique suffix and use it consistently in every later command and in the binding.
3. Upload the synthetic objects
Each object has a job in the experiment: the JPEG is the control that caches by default, the manifest is the treatment that only caches after the rule, and the catalogue is the private object that must never appear on the public hostname.
# Version 1 of the thumbnail: the object that will be replaced in place later.
npx wrangler r2 object put course-media-public/thumbs/thumb-0001.jpg \
--file data/thumbs/thumb-0001.jpg --remote --content-type image/jpeg
# The versioned thumbnail, uploaded now so the final step needs no purge.
npx wrangler r2 object put course-media-public/thumbs/thumb-0001.v2.jpg \
--file data/thumbs/thumb-0001.v2.jpg --remote --content-type image/jpeg
# The public manifest: JSON, not cached by default, and the rule's real subject.
npx wrangler r2 object put course-media-public/thumbs/manifest.json \
--file data/thumbs/manifest.json --remote --content-type application/json
# The private catalogue the Worker reads through its CATALOGUE binding.
npx wrangler r2 object put course-catalogue/catalogue.json \
--file data/catalogue.json --remote
# The one private file behind the signed route.
npx wrangler r2 object put course-catalogue/files/asset-0001.txt \
--file data/files/asset-0001.txt --remote --content-type text/plain
Expected: five Upload complete lines. The --content-type flag matters: R2 serves what you set, and a JPEG served as application/octet-stream may not follow the same cache path.
Panel path: R2 → the bucket → Objects → Upload, setting the same key and content type. Uploading through the panel is the fallback if Wrangler is blocked; the keys must match exactly.
4. Deploy the Worker and store the signing secret
The Worker needs a key to sign capabilities. A Worker secret is encrypted at rest and injected at runtime; it is never in wrangler.toml, never in git and never on screen for the evidence bundle. Deploy first: Wrangler cannot attach a secret to a Worker that does not exist yet.
# Generate a 32-byte random key for this deployment.
export SIGNING_KEY=$(openssl rand -hex 32)
# Deploy. Wrangler prints the workers.dev URL it created.
npx wrangler deploy
# Upload the key as an encrypted Worker secret; the value is read from stdin.
# The secret takes effect immediately; no second deploy is needed.
printf '%s' "$SIGNING_KEY" | npx wrangler secret put SIGNING_KEY
Expected: a deployment line and https://course-catalogue.<sub>.workers.dev. Keep that URL; every later check uses it.
Panel path: Workers & Pages → Create → Worker, paste src/index.js, then Settings → Variables and Secrets to add STUDIO_NAME (plain text) and SIGNING_KEY (secret), and Settings → Bindings → R2 bucket: binding CATALOGUE, bucket course-catalogue.
5. Verify the API and the capability
Three requests establish that the Worker reads the private bucket. The next three establish the capability boundary: it must refuse, then accept, then refuse again after expiry. That sequence is the evidence that the private file is protected by a clock, not by obscurity.
# Health: ok, the studio name and five assets.
curl -s https://course-catalogue.<sub>.workers.dev/health
# The full catalogue, read live from the private bucket.
curl -s https://course-catalogue.<sub>.workers.dev/assets
# One record.
curl -s https://course-catalogue.<sub>.workers.dev/asset/asset-0001
# No capability: expect 401.
curl -s -o /dev/null -w '%{http_code}\n' \
https://course-catalogue.<sub>.workers.dev/asset/asset-0001/file
# Print a signed, 60-second capability; paste the printed URL into the next command.
node scripts/sign.mjs asset-0001 https://course-catalogue.<sub>.workers.dev 60
# A valid capability: expect 200.
curl -s -o /dev/null -w '%{http_code}\n' '<printed-url>'
# Wait past the expiry, reuse the same URL: expect 401 again.
sleep 61
curl -s -o /dev/null -w '%{http_code}\n' '<printed-url>'
Expected: {"ok":true,...}, five records, 401, 200, 401. Record the three status codes and the timestamps; do not record the URL. Use curl, not the default Python urllib — workers.dev rejects the stock Python User-Agent with error 1010, and a descriptive User-Agent or curl avoids that trap.
6. Attach the public media hostname
media.<root> is an R2 custom domain: a hostname attached to one bucket. Cloudflare creates a proxied DNS record and the certificate automatically. Do not create the record by hand — a manual CNAME conflicts with the generated one.
# Store the zone ID from the zone's Overview page (right-hand sidebar).
export ZONE_ID=<zone-id>
# Attach media.<root> to the public bucket. The bucket and the zone must be in
# the same Cloudflare account; --zone-id scopes the generated proxied record.
npx wrangler r2 bucket domain add course-media-public --domain media.<root> \
--zone-id "$ZONE_ID" -y
# Confirm the hostname is attached and the certificate is issuing.
npx wrangler r2 bucket domain list course-media-public
Expected: the domain listed with a certificate status. The first request may take a minute while the certificate issues.
Panel path: R2 → course-media-public → Settings → Custom Domains → Add → media.<root>. Confirm the generated DNS record is proxied (orange cloud).
7. Prove the public path and the private boundary
The JPEG is cacheable by default; the JSON is not. Requesting each twice therefore produces two different stories, and the difference is the reason a Cache Rule exists. The last command is the safety checkpoint: a 404 is the proof that the private key is not exposed.
# First JPEG request: MISS — the edge fetched it from R2 and stored a copy.
curl -sD - -o /dev/null https://media.<root>/thumbs/thumb-0001.jpg | grep -i cf-cache-status
# Second JPEG request: HIT — the edge answered, the origin saw nothing.
curl -sD - -o /dev/null https://media.<root>/thumbs/thumb-0001.jpg | grep -i cf-cache-status
# The JSON manifest: DYNAMIC (or no header) — not eligible for caching yet.
curl -sD - -o /dev/null https://media.<root>/thumbs/manifest.json | grep -i cf-cache-status
# Safety checkpoint: the private catalogue key must be 404 through media.<root>.
# A 200 means the custom domain was attached to the private bucket — fix it now.
curl -s -o /dev/null -w '%{http_code}\n' https://media.<root>/catalogue.json
Expected: MISS, HIT, DYNAMIC, and 404. Write the four outputs down; they are evidence items 3 and the checkpoint.
8. Add the Cache Rule
A Cache Rule is zone-level configuration: for matching requests, it says whether the edge may cache and for how long. The Free plan's minimum Edge TTL is 2 hours, which is why the stale-copy failure later is visible; the Browser TTL is set to 60 seconds so your own browser does not add a second cache in front of the edge.
Panel path: Caching → Cache Rules → Create rule. Match https://media.<root>/thumbs/*; set Cache eligibility: Eligible for cache, Edge TTL: Override origin, 2 hours, Browser TTL: Override origin, 60 seconds. Save and note the rule name.
The API path is equivalent, and the instructor's runner uses it. It needs a token with Zone → Cache Rules: Edit:
# Store the zone ID from the zone Overview page.
export ZONE_ID=<zone-id>
# Create or replace the cache-settings entrypoint with one rule.
curl -s -X PUT \
"https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_request_cache_settings/entrypoint" \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
-H "Content-Type: application/json" \
--data @cache-rule.json
The body in cache-rule.json matches the panel settings:
{
"rules": [
{
"description": "S4 thumbs Cache Everything (2h edge / 60s browser)",
"expression": "(http.host eq \"media.<root>\" and starts_with(http.request.uri.path, \"/thumbs/\"))",
"action": "set_cache_settings",
"action_parameters": {
"cache": true,
"edge_ttl": { "mode": "override_origin", "default": 7200 },
"browser_ttl": { "mode": "override_origin", "default": 60 }
}
}
]
}
Now re-run the manifest test. The rule changed what the edge is allowed to keep:
# First manifest request after the rule: MISS.
curl -sD - -o /dev/null https://media.<root>/thumbs/manifest.json | grep -i cf-cache-status
# Second: HIT. Before the rule both were DYNAMIC.
curl -sD - -o /dev/null https://media.<root>/thumbs/manifest.json | grep -i cf-cache-status
Expected: MISS then HIT. The JPEG was already cacheable; the JSON was not; the rule is what changed.
9. Reproduce the stale-update failure, purge, then fix the design
This is the lab's failure-and-recovery moment. A cache is bytes under a key. Overwriting the bytes does not change the key, so the edge keeps its copy until the TTL expires. On this plan that can be two hours, which is long enough to see.
# Make the edge copy definitely warm: request the URL twice and expect the
# second response to print cf-cache-status: HIT. A single request can race the
# edge's store and the origin.
curl -sD - -o /dev/null https://media.<root>/thumbs/thumb-0001.jpg | grep -i cf-cache-status
curl -sD - -o /dev/null https://media.<root>/thumbs/thumb-0001.jpg | grep -i cf-cache-status
# Keep the checksum of the bytes you saw.
curl -s https://media.<root>/thumbs/thumb-0001.jpg -o stale.jpg
shasum -a 256 stale.jpg
# Replace the bytes under the same key with version 2's bytes.
npx wrangler r2 object put course-media-public/thumbs/thumb-0001.jpg \
--file data/thumbs/thumb-0001.v2.jpg --remote --content-type image/jpeg
# The origin changed; the edge did not. The checksum still matches stale.jpg.
curl -s https://media.<root>/thumbs/thumb-0001.jpg -o after-upload.jpg
shasum -a 256 after-upload.jpg
Expected: both checksums match. The upload succeeded and the edge still serves the old copy — cf-cache-status: HIT. Diagnose it from the status header, not from the upload log.
Recover with a purge. A purge is a correction, not a publishing strategy. On the Free plan it is limited to 5 per minute.
Panel path: Caching → Cache Purge → Purge by URL, paste https://media.<root>/thumbs/thumb-0001.jpg. API equivalent (needs Zone → Cache Purge):
# Remove the one cached URL from the edge.
curl -s -X POST \
"https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache" \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"files":["https://media.<root>/thumbs/thumb-0001.jpg"]}'
# The next request misses, fetches the new bytes, and the checksum changes.
curl -s https://media.<root>/thumbs/thumb-0001.jpg -o fresh.jpg
shasum -a 256 fresh.jpg
Expected: fresh.jpg has a different checksum from stale.jpg. The purge worked.
Fix the design. A versioned name is not a new key to purge; it is a new key from the start. The lab uploaded thumb-0001.v2.jpg in step 3 for exactly this moment.
# The versioned key's first request: MISS.
curl -sD - -o /dev/null https://media.<root>/thumbs/thumb-0001.v2.jpg | grep -i cf-cache-status
# Second request: HIT. No purge anywhere in this flow.
curl -sD - -o /dev/null https://media.<root>/thumbs/thumb-0001.v2.jpg | grep -i cf-cache-status
Expected: MISS then HIT. In your note, state which object in the unit's workflow should be versioned and which one genuinely needs a purge.
10. Measure, write the evidence, tear down
Open the lab notebook and replace its sample table with your measurements. The notebook computes the hit rate, origin offload, the three-row delivery comparison, the TTL-floor exercise and the Worker request headroom, then writes cdn_results.json.
Evidence bundle — nine items
- The deployed Worker's
/healthJSON (the URL visible, no token or account ID). /assetsand one/asset/:idresponse.- The output of step 7: the JPEG
MISS → HIT, the JSONDYNAMICbefore the rule, and thecatalogue.json404 checkpoint. - The Cache Rule configuration (pattern, Edge TTL 2 h, Browser TTL 60 s) — a panel screenshot or the API response — and the purge with before/after checksums.
- The versioned key's
MISS → HITwith no purge. - The capability sequence
401 → 200 → 401, with timestamps and the URL redacted. - The sanitized command log from your own run.
- The teardown log, an empty bucket list, and
doctl compute droplet listshowing no Droplet. - A 150–250 word what this proves note.
Say for each item what it proves, not just what it is. The bundle is scored 3/2/1/0 (see PLO.md).
Failure and recovery
| Symptom | Likely cause | Fix |
|---|---|---|
dig NS shows non-Cloudflare servers |
Registrar still lists its own NS, or an extra NS remains | Replace the full list with the two Cloudflare NS; wait; recheck |
media.<root> returns 404 for every key |
Custom domain not attached, or certificate still issuing | npx wrangler r2 bucket domain list; wait a minute; recheck |
catalogue.json returns 200 on media.<root> |
The custom domain points at the private bucket | Remove it and attach it to course-media-public — this is a data-exposure bug |
cf-cache-status: DYNAMIC after the rule |
Rule not saved, wrong zone, wrong host, or path not matching | Check the rule expression and that the request host is exactly media.<root> |
| Manifest still HIT with old bytes after upload | The 2 h edge TTL is doing its job | Purge that URL; then use a versioned key next time |
curl on workers.dev returns 1010 |
Default Python urllib User-Agent |
Use curl or set a descriptive User-Agent |
wrangler refuses to run |
Node older than 22.12 | Install Node 22 LTS; node --version; rerun npm install |
| No R2 bucket can be created | The one-time R2 subscription checkout is incomplete | Complete it in the dashboard; then rerun step 2 |
| Purge returns 429 | More than 5 purges in a minute | Wait 60 seconds; one URL is enough for this lab |
Cost ceiling
$0 on Cloudflare for every path in this lab: Workers Free (100,000 requests/day), R2 Free (10 GB storage, free egress), Cloudflare CDN on the Free plan. The domain is student-paid and outside the lab envelope. No DigitalOcean resource is created, so there is no Droplet or volume cost.
Teardown
Remove the custom domain before deleting the bucket, or the bucket delete fails.
# Remove the public hostname.
npx wrangler r2 bucket domain remove course-media-public --domain media.<root> -y
# Delete the Worker.
npx wrangler delete course-catalogue
# Delete every object, then both buckets.
npx wrangler r2 object delete course-media-public/thumbs/thumb-0001.jpg --remote
npx wrangler r2 object delete course-media-public/thumbs/thumb-0001.v2.jpg --remote
npx wrangler r2 object delete course-media-public/thumbs/manifest.json --remote
npx wrangler r2 object delete course-catalogue/catalogue.json --remote
npx wrangler r2 object delete course-catalogue/files/asset-0001.txt --remote
npx wrangler r2 bucket delete course-catalogue
npx wrangler r2 bucket delete course-media-public
# Prove no DigitalOcean Droplet survived from the earlier sessions.
doctl compute droplet list
# Prove the public hostname no longer serves content.
curl -s -o /dev/null -w '%{http_code}\n' https://media.<root>/thumbs/thumb-0001.jpg
Panel path: Caching → Cache Rules → the rule → Delete; R2 → the bucket → Settings → Custom Domains → remove; Workers & Pages → course-catalogue → Delete. Keep the bucket list empty in the screenshot.
Fallback chain
If the zone is missing or inactive, the lab still works, and full points remain available if your note names each substitution:
- Worker on
workers.dev— steps 1–5 are unchanged. Prove hit/miss with Workers Cache: uncomment[cache]inwrangler.toml, setenabled = true, redeploy, and request the same Worker URL twice. Its limitation is part of the lesson: Workers Cache can only be purged from inside the Worker. - Instructor demo hostname — for the Cache Rule, purge and versioned-key evidence, use the hostnames and bucket announced in class. The commands are identical with
<root>replaced by the demo root; say so in the note. - Wrangler blocked — the instructor-verified dashboard path in the sample's README produces the same evidence.
- Cloudflare account blocked —
wrangler dev --localplus the demo hostname and the notebook still produce the Worker, capability and calculation evidence. A fallback that changes the submitted shape is a defect; if the shape must change, say exactly how and why.
Notebook
Open the lab notebook; it computes the hit rate, the origin offload, the three-row delivery comparison and the Worker headroom from your measurement table, and writes cdn_results.json.