How-To Guide

How to Implement Edge Caching with Workers

Cache at the edge with a worker: use the cache API and Cache-Control, do stale-while-revalidate at the edge, and purge by tag.

On this page

  1. Introduction
  2. Split cacheable from dynamic at the edge
  3. Use the cache API and honour Cache-Control
  4. Do stale-while-revalidate at the edge
  5. Purge by tag on a content change
  6. Test the hit, the revalidation, and the purge
  7. Common pitfalls
  8. Conclusion

Introduction

An origin in one region serves users everywhere, so a user an ocean away pays the network round trip on every request. Edge caching puts a copy close to the user, served by a CDN point of presence or a worker running at the edge, so a cache hit never reaches the origin. The worker handles the dynamic part and the cache handles the rest, and the split is what keeps latency low for users far from the origin.

This tutorial implements edge caching in a worker: split cacheable from dynamic, use the cache API and Cache-Control, do stale-while-revalidate at the edge, and purge by tag. The examples follow the web-standard cache API and HTTP headers, so they apply to any edge runtime that exposes them.

Split cacheable from dynamic at the edge

Decide what the edge can answer without the origin. Static assets, public API responses, and shared pages are cacheable and belong in the edge cache. Per-user or session-dependent content is not cacheable as a whole and must either be composed at the edge from cached fragments or fall through to the origin. The goal is that the fast path, a cache hit, handles as much traffic as possible.

The worker should do the smallest amount of work on the fast path: key the cache, look it up, and return on a hit. Any per-request logic, such as adding a security header or selecting a variant, runs after the cache lookup or is baked into the cached response. Pushing work into the worker’s fast path adds latency to every hit, which defeats part of the benefit.

export default {
  async fetch(request, env) {
    const cache = caches.default;
    const cached = await cache.match(request);
    if (cached) return cached;                       // hit: no origin trip

    const response = await fetch(request);           // miss: go to the origin
    if (response.ok && isCacheable(request, response)) {
      const toCache = new Response(response.body, response);
      toCache.headers.set('Cache-Control', 'public, max-age=60, stale-while-revalidate=300');
      await cache.put(request, toCache.clone());
    }
    return response;
  },
};

Use the cache API and honour Cache-Control

The edge cache is populated by the cache API, and entries are subject to the Cache-Control of the response. Set the headers you want the edge to honour, such as max-age and s-maxage, and put the response in the cache. A response without a cacheable Cache-Control may not be stored, so the headers and the explicit put work together.

Key the cache by the full request, or by a key you choose. The full URL includes the query string, so variants are distinct entries; a custom key lets you normalize query parameter order or ignore tracking parameters so equivalent requests share an entry. Be careful not to ignore a parameter that changes the response, which would serve the wrong variant.

function cacheKey(request) {
  const url = new URL(request.url);
  url.searchParams.delete('utm_source');           // ignore tracking, not data params
  url.searchParams.delete('utm_campaign');
  url.searchParams.sort();                         // normalise order so variants share
  return new Request(url.toString(), request);
}

Do stale-while-revalidate at the edge

An edge cache can serve a stale copy immediately and revalidate in the background, so the user is fast and the origin still refreshes. The worker checks the cached response’s age; if it is within the fresh window, return it; if it is stale but within the grace window, return it and trigger a background fetch to refresh the cache. Beyond the grace window, fetch from the origin and wait.

The background refresh must be non-blocking and coalesced. Use a promise that is not awaited, and guard it so concurrent requests do not each trigger a refresh. Where the runtime offers a waitUntil to keep the background work alive after the response, use it so the refresh completes even after the response is sent.

async function withStaleWhileRevalidate(request, cache, ctx) {
  const cached = await cache.match(request);
  if (!cached) return fetchAndCache(request, cache);
  const ageHeader = cached.headers.get('age');
  const age = ageHeader ? Number(ageHeader) : 0;
  if (age > 300) return fetchAndCache(request, cache);   // too old: wait
  if (age > 60) ctx.waitUntil(fetchAndCache(request, cache));  // stale: refresh in background
  return cached;                                          // fresh or stale: return now
}

Purge by tag on a content change

A content change must invalidate the edge copies that include it. Tag the cached responses with the entities they depend on, and purge by tag so every affected edge entry is removed, without listing each URL or clearing the whole cache. Because the edge cache is distributed, a purge propagates to every point of presence, and the next request refills each from the origin.

Prefer versioned URLs where you can, so a content change produces a new URL and no purge is needed. For pages that must keep their URL, use the tag purge. After a purge, the first request to each edge goes to the origin, so warm the content or accept the refill cost, and coalesce the refill so a hot URL does not stampede the origin from every edge at once.

// tag on the way into the cache, purge by tag on a change
function tagResponse(response, tags) {
  const r = new Response(response.body, response);
  r.headers.set('Cache-Tag', tags.join(','));
  return r;
}
// await caches.purgeByTag('product:42');  // edge-specific admin API

Test the hit, the revalidation, and the purge

Test that a second request for the same URL is served from the edge cache without an origin fetch, by counting origin requests. Test that a stale copy is served immediately and a background revalidation happens. Test that a tag purge removes the entry so the next request refills it. Test that an ignored tracking parameter makes two requests share an entry while a data parameter keeps them distinct.

curl -s -o /dev/null -w '%{http_code}\n' https://edge.example/page    # MISS
curl -sD - -o /dev/null https://edge.example/page | grep -i 'cf-cache-status\|x-cache'   # HIT
# after a tag purge, the next request is a MISS again and refills the edge

Common pitfalls

Caching a per-user response at the edge so one user sees another’s data, ignoring a data parameter in the cache key so variants collide, doing heavy work on the fast path so every hit pays it, a background revalidation that is awaited or not coalesced, and no purge path so a content change is not seen are the recurring mistakes. A cacheable/dynamic split, a correct key, a minimal fast path, a non-blocking coalesced revalidation, and tag purges address them.

Conclusion

Edge caching serves users from a copy close to them. Split cacheable from dynamic, use the cache API with the right Cache-Control and cache key, do stale-while-revalidate at the edge with a non-blocking coalesced refresh, and purge by tag on a change. Self-check by asserting a second request is an edge hit and that a tag purge forces a refill. Then a user far from the origin still gets a fast response from the edge.

Sources: MDN: Cache API (CacheStorage), Cloudflare: Cache API and cache tags, RFC 5861: stale-while-revalidate.

FAQ

What is edge caching?
It is caching at a location close to the user, such as a CDN point of presence or a worker running at the edge, so a cache hit is served without a trip to the origin. It cuts latency for users far from the origin and absorbs load the origin would otherwise see.
What should a worker cache?
Static and cacheable responses, and the cacheable parts of dynamic ones. Run only the per-request logic in the worker, and let the cache serve everything that does not depend on the request, so the worker's small work is the only thing on the fast path.

Related Examples