skip to content

Content Delivery Settings

Cloudflare caches responses at its locations and rewrites requests by rule before they reach the origin. Interviewers ask why HTML is not cached by default and how to purge safely.

on this pageshow

explore

questions

28

In a Cloudflare Worker, how do you reuse an expensive JSON response with caches.default, cache.match() and cache.put()?

level: juniorimportance: must knowfreq 45%

answer

  1. a key-value store you drive
  2. a GET Request is the key
  3. undefined means a miss
  4. store a clone, return the original
  5. Cache-Control sets the lifetime

basics

~10 s

Build a GET Request as the key and return caches.default.match(key) when it hits; on a miss, build the response with a Cache-Control lifetime, store response.clone() with cache.put() inside ctx.waitUntil, and return the original.

solid answer

~40 s

The Cache API is a key-value store I drive from code: the key is a `GET` `Request` (really its URL) and the value is a `Response`. I call `await caches.default.match(cacheKey)` first; it resolves to the stored response or `undefined`, and it never goes to the origin by itself. On a miss I make the upstream calls, build one `Response` whose `Cache-Control` (say `s-maxage=300`) sets the edge lifetime, and pass `cache.put(cacheKey, response.clone())` to `ctx.waitUntil()` so the write finishes after the reply. The clone matters because a body can be read only once. I strip tracking parameters before building the key so they do not split the cache, and I remember the entry exists only in the data center that ran the Worker.

code

javascript · 25 lines
javascript
export default {
  async fetch(request, env, ctx) {
    if (request.method !== "GET") {
      return new Response("Method not allowed", { status: 405 });
    }
    const url = new URL(request.url);
    url.searchParams.delete("utm_source");
    const cacheKey = new Request(url.toString());
    const cache = caches.default;

    const cached = await cache.match(cacheKey);
    if (cached) return cached;

    const [prices, stock] = await Promise.all([
      fetch("https://prices.example.com/v1/list").then((r) => r.json()),
      fetch("https://stock.example.com/v1/levels").then((r) => r.json()),
    ]);
    const response = Response.json(
      { prices, stock, builtAt: new Date().toISOString() },
      { headers: { "Cache-Control": "public, max-age=60, s-maxage=300" } },
    );
    ctx.waitUntil(cache.put(cacheKey, response.clone()));
    return response;
  },
};

go deeper

for a junior

Recall the four moves: build a GET key, match, on a miss build and store a clone, return the original. Know that match() returns undefined on a miss and never calls the origin.

for a middle

Explain what sets an entry's lifetime (Cache-Control, Expires on the stored response), why the clone is needed, and how query strings and tracking parameters shape the key.

for a senior

Show you know the entry is local to one data center, that put() reports nothing, and that per-user data must never share a key; describe how you would confirm a write actually landed.

for a principal

Frame the Cache API as the low-level option: the Worker runs on every request and owns keys, lifetimes and purges, which a team must standardise if several services use it.

## What the Cache API is Inside a Cloudflare Worker, the **Cache API** is a programmatic handle on Cloudflare's edge cache. It behaves like a small **key-value store**: the key is a `Request` (in practice its URL, and it must be a `GET`), and the value is a `Response`. Nothing enters the cache through this API unless the Worker writes it, and nothing comes out unless the Worker asks. That makes it the tool for caching a response the Worker *built itself*, such as a JSON document assembled from several upstream calls, which no origin cache would ever see as one object. Two handles exist: | Handle | How you get it | Shared with `fetch()` subrequests? | |---|---|---| | `caches.default` | a property, no `await` | yes, it is the zone cache that `fetch()` reads and fills | | a named cache | `await caches.open("api:v1")` | no, a separate namespace | ## The read-through pattern, step by step 1. **Build the key.** Create a `GET` `Request` for the URL that identifies the result. A string URL also works as a key. 2. **Look it up.** `await cache.match(cacheKey)` resolves to the stored `Response` or to `undefined`. It **never** sends a request to the origin on a miss. 3. **On a hit, return it.** The work is skipped. 4. **On a miss, do the work** (here, two upstream calls in parallel) and build one `Response`. 5. **Give it a lifetime.** Put a `Cache-Control` header on that response; `s-maxage` sets the edge lifetime and `max-age` what the browser keeps. 6. **Store a clone.** `cache.put(cacheKey, response.clone())` streams the body into the cache. Wrapping it in `ctx.waitUntil()` lets the write finish after the reply has gone out. 7. **Return the original** to the visitor. ## Choosing the key - The **full URL, query string included**, identifies the entry, so `?utm_source=a` and `?utm_source=b` are two entries unless you delete the parameter before building the key. - Keep **per-user data out of a shared key**. Two visitors who map to the same key get the same stored body; put a user or tenant id in the key, or do not cache. - `cache.put()` **throws** for a key whose method is not `GET`. To cache the result of a `POST`, hash its body into a synthetic `GET` URL. - `cache.match(request, { ignoreMethod: true })` treats any method as `GET` for the lookup. ## What decides how long an entry lives The Cache API reads the headers on the response passed to `put()`: - **`Cache-Control`** sets freshness, following Cloudflare's cache directives; `no-store` or `private` means the entry is not kept. - **`Expires`** is honoured as an expiry time. - **`ETag`** and **`Last-Modified`** let `match()` answer a conditional request (`If-None-Match`, `If-Modified-Since`) with `304 Not Modified`. - **`Cache-Tag`** labels the entry so a later purge by tag can remove it. - `stale-while-revalidate` and `stale-if-error` are **not supported** by `put()` and `match()`: an expired entry is simply a miss. ## Things that surprise newcomers - Unless it throws for an invalid input (a non-`GET` key, a `206`, `Vary: *`), `put()` resolves to `undefined` **whether or not** anything was stored, so success has to be checked with a later `match()`. - A response body can be read **once**. Passing the response you return to `put()` leaves nothing for the client; reading it afterwards throws "Body has already been used". - A response with **`Set-Cookie`** is never stored unless you remove that header or add `Cache-Control: private=Set-Cookie`. - The entry lives **only in the data center that ran the Worker**. Visitors elsewhere fill their own copies, so expect a lower hit ratio than a zone-wide cache would give. - Cache API calls count toward the per-request limit shared with subrequests: **50** per request on Workers Free, **1,000** on Workers Paid. The largest object is **512 MB**. - Calls made in the dashboard editor or the Playground preview have no effect, so test on a deployed route or locally with `wrangler dev`. ## When the Cache API is the wrong tool - **The Worker only proxies an origin.** A `fetch()` subrequest already reads through the zone cache, and through Tiered Cache where it is enabled, and its `cf` options set lifetimes without any `match()` or `put()` code. - **Every location must see the same value at once.** A per-location cache cannot promise that; a globally replicated store or a short lifetime has to. - **The response differs per visitor** and nothing in the key separates visitors. Caching it shares one person's data with the next. Used this way, an expensive aggregation runs once per data center per lifetime instead of once per request, and the Worker stays in control of what is stored, under which key and for how long.

  • What is the difference between caches.default and a cache returned by caches.open()?
    `caches.default` is the zone cache that `fetch()` subrequests also read and fill, so a `put()` there can replace what a fetch cached for the same URL. `await caches.open("api:v1")` returns a separate namespace that `fetch()` never touches, which keeps a Worker's own entries apart. `caches.default` is a property; `caches.open()` returns a promise. Both are local to one data center.
  • Why does the code store response.clone() rather than the response it returns?
    `cache.put()` consumes the body as it streams it into the cache. If you store the object you also return, the client is left with a used body, and reading it afterwards throws "Body has already been used". `response.clone()` tees the body, so one branch goes into the cache and the other to the visitor.
  • How does cache.match() answer a request that carries If-None-Match or Range?
    `match()` honours the request's conditional and range headers: `If-None-Match` against a stored `ETag` and `If-Modified-Since` against `Last-Modified` produce a `304 Not Modified`, and `Range` produces a `206` from a stored response with `Content-Length`. If you always want the full body, build the key as a fresh `Request` from the URL alone.

  • cache.match() fetches from the origin and stores the result when the key is missing
  • cache.put() returns false when the cache declines to store the response
  • The same Response object can be stored with cache.put() and also returned
  • An entry stored with cache.put() is available in every Cloudflare data center
  • stale-while-revalidate on the stored response makes match() serve stale copies
open as a page

On a site proxied by Cloudflare, which files does the edge cache by default, and why do HTML pages show cf-cache-status DYNAMIC?

level: juniorimportance: must knowfreq 75%

basics

~20 s

Cloudflare caches by file extension: images, CSS, JavaScript, fonts, media, documents and archives, plus robots.txt. HTML, JSON and extensionless paths are not on the list, so those requests go to the origin without a cache lookup and show DYNAMIC.

open as a page

In Cloudflare, how do you purge one corrected page from the edge cache, and how do you confirm the purge worked?

level: juniorimportance: must knowfreq 62%

basics

~20 s

Use purge by single-file: Custom Purge, then URL, on the zone's Caching Configuration page, or send the URL to the purge_cache API. A 200 only means Cloudflare accepted it; re-request the page and check cf-cache-status is no longer HIT.

open as a page

In Cloudflare's cf-cache-status header, what do HIT, MISS, EXPIRED, UPDATING, BYPASS and DYNAMIC mean, and how do BYPASS and DYNAMIC differ?

level: middleimportance: must knowfreq 65%

basics

~20 s

HIT is served from cache, MISS is cacheable but fetched, EXPIRED is a stale copy refetched, UPDATING is stale served during background revalidation. DYNAMIC means ineligible at request time; BYPASS means eligible, but the origin's response could not be stored.

open as a page

In Cloudflare, how do Cache-Tag response headers let a sports-results site purge a match page, its JSON feed and league tables in one request?

level: middleimportance: must knowfreq 55%

basics

~20 s

The origin adds a Cache-Tag header naming match-8812 to every response that shows that match's score. Cloudflare stores the tags with each cached object and strips the header. One purge by tag then removes every object carrying it, on any plan.

open as a page

Since Cloudflare deprecated Page Rules, which Rules products replace their settings, and how does matching change when you migrate?

level: middleimportance: must knowfreq 45%

basics

~20 s

Page Rules split into dedicated products: Single Redirects for Forwarding URL, Origin Rules for Host and resolve overrides, Configuration Rules for per-path settings, Managed Transforms for header settings, Cache Rules for caching. Modern rules stack rather than stopping at the first match.

open as a page

In Cloudflare Cache Rules, what does the default cache key contain, and which Cache Key settings stop tracking parameters splitting the cache on each plan?

level: middleimportance: must knowfreq 55%

basics

~20 s

The default key is the scheme, host, path and query string, plus the client's Origin header and a few override headers. Every plan can ignore or sort the query string; excluding single parameters, or keying on headers, cookies, host or user features, is Enterprise-only.

open as a page

In Cloudflare Cache Rules, how do you make a shop's anonymous HTML product pages cacheable, and what do Edge TTL and Browser TTL change?

level: middleimportance: must knowfreq 65%

basics

~20 s

Create a Cache Rule whose expression matches only the product paths and set it to Eligible for cache, which makes HTML cacheable. Edge TTL decides how long Cloudflare's edge keeps a copy; Browser TTL decides the lifetime sent to visitors' browsers.

open as a page

A shop's Cloudflare Cache Rule makes the whole hostname Eligible for cache with an Edge TTL ignoring Cache-Control; customers see others' account pages and sign-ins fail. Why, and what fixes it?

level: seniorimportance: must knowfreq 55%

basics

~20 s

The rule also matched account and login pages; its override Edge TTL ignored private, so Cloudflare stripped Set-Cookie and shared one customer's page. Narrow it, add a later Bypass cache rule on personal paths and the session cookie, then purge.

open as a page

With Cloudflare Transform Rules, how do you add security headers such as X-Frame-Options to every response on a zone?

level: juniorimportance: should knowfreq 35%

basics

~20 s

Turn on the Add security headers Managed Transform, which adds X-Frame-Options, X-Content-Type-Options and three other headers to every response, then write Response Header Transform Rules with a Set operation for headers it omits, such as Content-Security-Policy.

open as a page

In a Cloudflare Worker proxying an origin, what do fetch()'s cf options cacheTtl, cacheTtlByStatus, cacheEverything and cacheKey change?

level: middleimportance: should knowfreq 38%

basics

~20 s

They change how the edge caches that one subrequest: cacheTtl forces a lifetime whatever the origin says, cacheTtlByStatus sets one per status range, cacheEverything caches any file type but keeps origin lifetimes, and cacheKey (Enterprise only) replaces the cache key.

open as a page

Why is a response stored with cache.put() in a Cloudflare Worker served in only one data center, and how do you clear it everywhere?

level: middleimportance: should knowfreq 40%

basics

~20 s

The Cache API in a Worker writes only to the data center that ran it: entries never replicate and cache.put() skips Tiered Cache. cache.delete() is equally local, so clearing every location needs a zone purge by Cache-Tag or Purge Everything.

open as a page

How does Cloudflare set an eligible file's edge TTL from origin headers or defaults, and how does Browser Cache TTL change what browsers receive?

level: middleimportance: should knowfreq 50%

basics

~20 s

The edge follows the origin's s-maxage, max-age or Expires; with none, it uses status-code defaults (120 minutes for 200, 206 and 301). Browser Cache TTL, 4 hours by default, raises shorter origin lifetimes for browsers unless set to Respect Existing Headers.

open as a page

In Cloudflare, how does Smart Tiered Cache cut requests to the origin, and what does it change about origin load after a purge?

level: middleimportance: should knowfreq 40%

basics

~20 s

Tiered Cache makes lower-tier data centers ask an upper tier on a miss, and only upper tiers fetch from the origin. Smart Tiered Cache picks the lowest-latency upper tier per origin, so a purged object is refetched about once, not once per data center.

open as a page

With Cloudflare Origin Rules, how do you send /api requests to another backend host and port, and which overrides need Enterprise?

level: middleimportance: should knowfreq 30%

basics

~20 s

Write an Origin Rule matching starts_with(http.request.uri.path, "/api/") that overrides the destination port, available on every plan, and on Enterprise the DNS record and Host header, so Cloudflare connects to the API backend and presents its name.

open as a page

In Cloudflare, when do you use Single Redirects rather than Bulk Redirects to move an old blog's URLs onto a new domain?

level: middleimportance: should knowfreq 30%

basics

~20 s

Use a Single Redirect when one wildcard pattern maps the old paths onto the new domain, such as /blog/* to https://blog.example.net/${2}. Use Bulk Redirects for an irregular list of exact source and target URLs, kept at the account level.

open as a page

When a shop moves caching Page Rules to Cloudflare Cache Rules, how do stacking, last-match-wins and Eligible for cache's Cache Everything change the result?

level: middleimportance: should knowfreq 40%

basics

~20 s

Page Rules apply only the highest-priority match; Cache Rules all apply in order and the last match wins shared settings. Eligible for cache also turns on Cache Everything, so standard caching needs a Bypass-all rule followed by an eligible rule for default extensions.

open as a page

A Cloudflare Worker calls cache.put() on caches.default for every upstream API response, yet cache.match() never returns a hit; what explains it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Usually the stored copy carries the upstream's Set-Cookie or Cache-Control no-store, private or max-age=0, so it is silently not kept. Otherwise the put() and match() keys differ, the write is cut off without ctx.waitUntil, or requests land in other data centers.

open as a page

After a Cloudflare purge by URL of a corrected match page, some visitors still get the old score; why, and how do you clear every copy?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A URL purge removes one cache key. Copies under other keys, such as query-string variants or custom keys built from device type, headers or cookies, survive. Purge by prefix or tag, or send each variant's headers in an API purge.

open as a page

After a Cloudflare URL Rewrite Rule stripped /api from request paths, an Origin Rule matching /api/ stopped firing; why, and what fixes it?

level: seniorimportance: should knowfreq 22%

basics

~10 s

URL Rewrite Rules run in the http_request_transform phase, before Origin Rules, so when the Origin Rule is evaluated http.request.uri.path already holds the rewritten path without /api. Match on raw.http.request.uri.path, which keeps the received value.

open as a page

A security review of a shop behind Cloudflare finds /account/orders/receipt.css returns a customer's order page; what does Cache Deception Armor stop here, and what else must change?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Cache Deception Armor, a Cache Key setting in a Cache Rule, skips caching when the Content-Type does not match the URL's extension, so the HTML behind .css is not stored. Overrides can defeat it: also bypass account paths and return 404 there.

open as a page

As the lead for a team's Cloudflare Workers APIs, how do you choose between the Cache API, fetch() cf options and Workers Cache?

level: principalimportance: should knowfreq 22%

basics

~20 s

Choose by whether code must run on every request and where content comes from: fetch() cf options for origin proxies, Workers Cache for new Worker-generated output, the Cache API only for fine programmatic control, weighing tiering, purging, per-user keys and billing.

open as a page

As the lead for a sports-results publisher running several zones on one Cloudflare account, what purge policy would you set, and who may purge everything?

level: principalimportance: should knowfreq 28%

basics

~20 s

Make CMS-driven purge by tag the default and Purge Everything an incident action with sign-off. Keep the Cache Purge permission in one service, batch against the shared per-account limits, and invalidate only content that may be served stale.

open as a page

As the lead retiring a zone's Page Rules, how do you decide what belongs in Cloudflare Rules, in Snippets, or in a Worker?

level: principalimportance: should knowfreq 20%

basics

~20 s

Default to declarative Rules: no code, no per-request cost, visible in Cloudflare Trace. Use a Snippet on a paid plan for small stateless JavaScript, and a Worker when you need bindings, state, logs, versioned rollouts or more than 5 ms.

open as a page

As the lead for a shop on Cloudflare, what would you let Cache Rules cache, and who may change those rules and how?

level: principalimportance: should knowfreq 30%

basics

~20 s

Make caching an allowlist: eligible rules only for catalogue paths and static files, a final bypass rule for personal paths and session cookies, respect_origin on HTML. Limit who can edit Cache Rules, the Firewall role included, and review changes as code.

open as a page

When an origin behind Cloudflare sends Cloudflare-CDN-Cache-Control, CDN-Cache-Control and Cache-Control together, which decides edge caching, and which reach the browser?

level: middleimportance: nice to knowfreq 30%

basics

~10 s

Cloudflare-CDN-Cache-Control decides first, then CDN-Cache-Control, then Cache-Control. Cloudflare-CDN-Cache-Control is never forwarded; CDN-Cache-Control and Cache-Control are, and Browser Cache TTL rewrites only Cache-Control.

open as a page

A sports site on Cloudflare enabled Cache Reserve to cut origin egress, yet after each nightly purge by tag its origin egress and Class A operations jump; why?

level: seniorimportance: nice to knowfreq 24%

basics

~20 s

Since September 2026 every purge type forces a Cache Reserve miss: each purged object is refetched from the origin in full and rewritten, a Class A operation. For probably unchanged content, invalidate instead, so a 304 reuses the stored copy.

open as a page