Inconsistent performance on cache hit with CloudFlare worker

We have a setup with Cloudflare pointing to 3 different endpoints hosted on AWS:

  • /store/* is pointing to SSR API rendering HTML pages
  • /graphql is pointing to API endpoint
  • all the rest is pointing to an AWS S3 bucket with static assets

Routing logic is done with Cloudflare worker based on this article:
https://posthog.com/docs/advanced/proxy/cloudflare

This is our worker’s code:

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    const path = url.pathname;
    const search = url.search;

    const originRequest = new Request(request)
    if (path === '/graphql') {
      const originUrl = `${env.GRAPHQL_API_URL}${search}`;
      return await fetch(originUrl, originRequest);
      response = new Response(response.body, response);

      return response;
    }

    let response = await caches.default.match(request)
    if (!response) {
      if (path.startsWith("/store/")) {
        const originUrl = `${env.SSR_API_URL}${path}${search}`;
        response = await fetch(originUrl, originRequest);
        response = new Response(response.body, response);
        response.headers.set('CDN-Cache-Control', response.headers.get('Cache-Control'));
      } else {
        const originUrl = `${env.ASSETS_URL}${path}`;
        response = await fetch(originUrl, originRequest);
        response = new Response(response.body, response);
        response.headers.set('CDN-Cache-Control', response.headers.get('Cache-Control'));
      }

      ctx.waitUntil(caches.default.put(request, response.clone()));
    }

    return response;
  }
};

However we get a very inconsistent performance. Sometimes assets load in 30ms and sometimes in 700ms, even that response headers state that it was a cache hit…

We are using state-while-revalidate for our SSR pages, but it does not seem to work properly.

I tried to use worker cache API, and mangle with cache rules, without any success. Also tried to use CDN-Cache-Control header as described in docs: https://developers.cloudflare.com/cache/concepts/cdn-cache-control/ - no success.

Any idea what to do?
I’m quite new to Cloudflare, mostly working with AWS CloudFront, where I could set up this kind of behavior easily…