Cache API for Cloudflare Workers - Beta Feedback

The Cache API gives you fine grained control of reading and writing from cache, and deciding exactly when to fetch data from your origin.

This API is strongly influenced by the web browsers’ Cache API, but there are some important differences (documented below).

Documentation for the Cache API can be found here:

2 Likes

Hi,

I’m no Javascript expert so I may be missing something, but what is the purpose of this line in the “Add Cache-Tag To Response” example in the docs?

response = new Response(response.body, response)

It seems to be copying the response, but why? It is copied again later using the clone() method in the call to cache.put().

Thanks

Responses are treated as a stream, so they can only be read once. This is why you see responses being cloned, or constructed into new responses. Mainly because of memory efficiency.

In this specific example:

// Resolves the fetch() Promise that returns a Response
response = await fetch(request)

// Headers are immutable, meaning we can't alter it unless we construct a new Response
response = new Response(response.body, response)
response.headers.append('Cache-Tag', 'apple')

// The cache API will consume the response, so we clone it to avoid buffering
event.waitUntil(cache.put(request, response.clone()))

// Return the newly created Response that hasn't been consumed yet
return response

The following article explains it with a little more details:

1 Like

:1st_place_medal: So far the experience with the Cache API has been coherent and stable, with the addition of Workers KV it is a bliss.

For me, it only makes sense using the two together:

:chart_with_downwards_trend: Without WorkerKV & Cache API:

:chart_with_upwards_trend: With WorkerKV & Cache API:

Our servers are near Amsterdam and Frankfurt, making a big impact in the distant locations (e.g Seoul, California). :+1:

1 Like

When I put a response in cache it has these headers:

cache-control: public, max-age=30
cache-tag: blah
content-type: text/plain

When I read it out again, it has these headers:

cache-control: public, max-age=14400
cf-cache-status: HIT
cf-ray: 4681eb1ed3472bee-AMS
connection: keep-alive
content-length: 19
content-type: text/plain
date: Thu, 11 Oct 2018 14:11:52 GMT
expires: Thu, 11 Oct 2018 18:11:52 GMT
server: Cloudflare

Why has the TTL increased from 30 secs to 4 hours? Why don’t I see the cache-tag header?

Thank you.

@rmaidment You need to change Browser Cache Expiration on the dashboard to Respect Existing Header. It should fix your issue.