Worker cache is undefined

I’m trying to implement a simple worker solution to cache a response from an API triggered by a scheduled cron, and provide the cached response to users that make a request.

I upgraded to a paid plan and configured a custom domain to have access to the Cache API. Having a look at the realtime logs, the cron job is executed and fetch performed.

When querying to retrieve the result, the response is always Not Found. Indeed, running cache.match() in scheduled returns null. It seems the scheduled is somehow not saving responses.

import type { ScheduleEvent, Env } from './types';

const BASE_URL = 'https://acustomdomain.com';

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    const cache = caches.default;
 
    const url = new URL('results', BASE_URL).toString();
    const response = await cache.match(url);

    return response || new Response('Not Found', { status: 404 });
  },

  async scheduled(event: ScheduleEvent, env: Env, ctx: ExecutionContext) {
    const cache = caches.default;

    const results = await fetch(...);

    const url = new URL('results', BASE_URL).toString();
    const response = new Response(JSON.stringify(results), {
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': `max-age=120, s-maxage=120`,
        'Access-Control-Allow-Origin': '*',
      },
    });

    ctx.waitUntil(cache.put(url, response));
  },
};
1 Like

Cache is per-colo and the cached item can be evicted at any time - there’s no guarantee (it’s pretty unlikely even) that user’s requests for your fetch event are hitting the same colo that your scheduled event ran in.

1 Like