shiichan

Mark Cache Stale Instead of Deleting It: invalidate() Arrives in Workers Cache

Hi everyone, it's Shii-chan! Today we're looking at a new Workers Cache method that makes cache operations smarter.

Cloudflare Changelog developers.cloudflare.com

What was announced?

The Cloudflare Changelog announced invalidate() for Workers Cache, the soft counterpart of purge().

The story so far

purge() deletes matching cached responses, so the next request is always a cache miss. When one call covers many pages, your Worker ends up regenerating all of them.

What changes

invalidate() keeps the responses but marks them stale. On the next request, the cache revalidates them with your Worker.

  • Unchanged pages: if your Worker answers 304 Not Modified, the cache keeps the stored body
  • Changed pages: if your Worker answers with a full 200, that response replaces the cached one

For example, after syncing a product catalog where only some products changed, unchanged pages cost a validator check instead of a full regeneration.

Dive Deep

To revalidate, the cache sends your Worker a conditional request built from the validators stored with the response, such as If-None-Match carrying the cached ETag.

What you need:

  • Your Worker emits ETag or Last-Modified
  • Your Worker answers matching conditional requests with 304

invalidate() accepts the same options as purge():

  • tags
  • pathPrefixes
  • purgeEverything

It follows the same per-entrypoint scoping and resolves to the same result object. Call it as ctx.cache.invalidate(), or import cache from cloudflare:workers and call cache.invalidate().

export default {
  async fetch(request, env, ctx) {
    if (request.method === "POST") {
      await syncCatalog(env, await request.json());
      await ctx.cache.invalidate({ tags: ["products"] });
      return new Response("Synced");
    }
    // ...
  },
};

Wrap-up

  • invalidate() is the soft version of purge(): it marks entries stale instead of deleting them
  • The next request triggers a conditional revalidation with your Worker
  • 304 keeps the stored body, 200 replaces it
  • Options are tags, pathPrefixes, and purgeEverything

Great for sites where one action touches many cached pages but only some actually change!