skip to content

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%

answer

  1. put() reports nothing either way
  2. headers inherited from the upstream
  3. a cookie on the response
  4. same key, same place, same time?

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.

solid answer

~40 s

`cache.put()` resolves to `undefined` whether or not anything was stored, so the failure is silent. The usual cause is the upstream's headers riding along: a response with `Set-Cookie` is never cached unless that header is removed or marked private, and `Cache-Control: no-store`, `private` or `max-age=0` stop the entry being kept. I store a clone with `Set-Cookie` removed (or `Cache-Control: private=Set-Cookie`) and my own `s-maxage`. Next I compare the keys, because the URL including its query string is the key, and check that the write runs under `ctx.waitUntil()`. Entries are per data center, so tests from different locations miss. A `304` is dropped silently; `206`, `Vary: *` or a non-`GET` key throw. Cache API misses show in Cloudflare Logs as 504s with `RequestSource` `edgeWorkerCacheAPI`.

code

javascript · 21 lines
javascript
export default {
  async fetch(request, env, ctx) {
    if (request.method !== "GET") return fetch(request);

    const url = new URL(request.url);
    const cacheKey = new Request(url.toString());
    const cache = caches.default;
    const hit = await cache.match(cacheKey);
    if (hit) return hit;

    const upstream = await fetch(`https://rates.example.com${url.pathname}`);
    if (upstream.status !== 200) return upstream;

    const response = new Response(upstream.body, upstream);
    const stored = response.clone();
    stored.headers.delete("Set-Cookie");
    stored.headers.set("Cache-Control", "public, s-maxage=600");
    ctx.waitUntil(cache.put(cacheKey, stored));
    return response;
  },
};

go deeper

for a junior

Remember that the Cache API does not store a response carrying Set-Cookie unless that header is removed or marked private, and that put() gives no sign of failure.

for a middle

Explain which inherited headers block storage, which inputs make put() throw instead, and how the key is built from the URL.

for a senior

Work the diagnosis in order: log what put() receives, compare keys on both paths, pin requests to one data center, and read the edgeWorkerCacheAPI 504s in Cloudflare Logs.

for a principal

Push the team toward one shared helper that shapes stored copies and normalises keys, so per-user headers can never leak into a shared cache entry.

## Why the failure is silent `cache.put()` on `caches.default` resolves to `undefined` **whether or not the cache stored the response**. When the cache declines a response because of its headers or its size, the runtime does not raise anything to the Worker. So a Worker that stores every upstream response and never sees a hit is usually storing responses the cache refuses, or looking them up under a different key, in a different place, or at a different time. ## Causes, most common first 1. **The upstream sends `Set-Cookie`.** Responses with a `Set-Cookie` header are **never** cached, because the header can mean per-user data. Remove it from the copy you store, or add `Cache-Control: private=Set-Cookie`, which stores the response **without** that header. 2. **The upstream's `Cache-Control` forbids storing.** Passing the upstream response straight to `put()` carries its `no-store`, `private` or `max-age=0` along, and the Cache API honours them: the entry is not kept, or it expires at once. Set your own `Cache-Control` on the stored copy. 3. **The key differs between `put()` and `match()`.** The URL is the key, query string included. Storing under the upstream URL and looking up under the visitor URL, or letting `?utm_source=` and other tracking parameters through, produces a key that is never asked for again. 4. **The write never finishes.** A `put()` that is neither awaited nor passed to `ctx.waitUntil()` can be cut off once the response has been sent. 5. **The test runs in different data centers.** Entries are local to the data center that wrote them, so traffic spread across locations, or a check made from another network, misses on purpose. 6. **The status is not storable.** A `304 Not Modified` (from a forwarded conditional request) is discarded silently, while a `206 Partial Content`, a `Vary: *` header or a non-`GET` key makes `put()` **throw** a `TypeError`. 7. **The environment has no working cache.** Calls in the dashboard editor and the Playground preview have no effect, and the Cache API is not currently available to Workers fronted by Cloudflare Access. ## What throws and what fails quietly | Response or key passed to `put()` | Result | |---|---| | key with a method other than `GET` | throws `TypeError` | | `206 Partial Content` | throws `TypeError` | | `Vary: *` | throws `TypeError` | | `304 Not Modified` | discarded, no error | | `Set-Cookie` present | not stored, no error | | `Cache-Control: no-store` or `private` | not stored, no error | | body above the 512 MB object limit | not stored, no error | ## How to confirm the cause - **Log what you pass to `put()`**: the status, `Cache-Control` and whether `Set-Cookie` is present. Most cases are visible right there. - **Log the key URL** on both the `put()` path and the `match()` path and compare them. - **Repeat the request from one place** and check `request.cf.colo` in the log line, so both requests reach the same data center. - **Read Cloudflare Logs**: Cache API misses appear as `504` responses with `RequestSource` `edgeWorkerCacheAPI`. Cache Analytics already filters them out, so do not look for them there. - **Reproduce locally** with `wrangler dev`, which simulates the Cache API, to test the header handling; it cannot show per-location behaviour. ## Fixing it for good - Store a **copy you have shaped**: clone the response, delete `Set-Cookie` from the copy, set an explicit `Cache-Control` such as `public, s-maxage=600`, and return the original so the visitor still gets the upstream's cookie. - **Store only what is meant to be reused**: skip non-200 responses instead of letting them throw or vanish. - **Normalise the key** in one function used by both paths. - **Hand the write to `ctx.waitUntil()`** so it outlives the response. ## Why the upstream's headers deserve respect Overriding the upstream's `Cache-Control` is a decision, not a formality. An API that sends `private` or `Set-Cookie` may be telling you the body differs per caller. Before forcing a shared lifetime, confirm that the response is the same for everyone who maps to that key; if it is not, put the distinguishing input (a tenant or a currency, never a session token) into the key, or leave the response uncached. Once the stored copy is shaped by the Worker rather than inherited from the upstream, `match()` starts returning hits in each data center after its first fill.

  • What does Cache-Control: private=Set-Cookie do on a response passed to cache.put()?
    It tells the cache that only the `Set-Cookie` header is private, so the response is stored with that header stripped and later `match()` calls return it without the cookie. That keeps one visitor's cookie from being served to others while the body is still reused. Deleting `Set-Cookie` from the stored copy has the same effect and is more explicit.
  • Why does a Worker that forwards the browser's conditional request upstream sometimes store nothing?
    If the browser sends `If-None-Match` and the Worker forwards it, the upstream may answer `304 Not Modified`. `cache.put()` silently discards 304 responses, because caching one would answer later unconditional requests with an empty 304. Build the upstream request without the conditional headers when you mean to fill the cache, and let `cache.match()` answer conditional requests from the stored `ETag`.

  • cache.put() throws an error when the cache refuses a response
  • A Set-Cookie response is stored and simply served with its cookie
  • The upstream's Cache-Control is ignored once the Worker calls put() itself
  • Cache API misses can be counted as MISS in Cache Analytics
  • Two requests to the same URL always share a cache entry wherever they land

Assumes the platform as of 2026-10-10, when the Cache API was not available to Workers fronted by Cloudflare Access; the other causes have held for years.