Search code examples
cloudflarecloudflare-workers

Page stored using Cloudflare Cache API expires earlier than expected


I am developing a backend API using Cloudflare Workers to cache the tokens into respective individual pages, something like http://cache.api/[tokenId] with token value itself as body content, using Cache API.

        const tokenId = 'fakeJWT';

        const internalUrl = ''.concat(
          'http://cache.api/',
          tokenId // the query string
        );

        const cacheUrl = new URL(internalUrl);
        const cacheKey = new Request(cacheUrl.toString());
        const cache = caches.default;

        let response = new Response(tokenId);
        response.headers.append('Cache-Control', 's-maxage=86400'); // 24 hours

        await cache.put(cacheKey, response.clone());

I've configured Cache-Control header with 24 hours expiry. Then, I wrote another API in the same Cloudflare Workers to check the existence of the cache, it exists after 10 minutes but does not exist after 15 minutes.

        const internalUrl = ''.concat(
            'http://cache.api/',
            tokenId // the query string
        );

        const cacheUrl = new URL(internalUrl);
        const cacheKey = new Request(cacheUrl.toString());
        const cache = caches.default;

        let response = await cache.match(cacheKey);
        if (!response) {
            console.log(
              `Cache url for ${cacheUrl} is not present`
            );

            return unauthorised(`${pathName}: This user session has expired! cache url is ${cacheUrl}`);
        }
        else
        {
            let response = new Response(tokenId);
            response.headers.append('Cache-Control', 's-maxage=86400'); // in seconds
    
            await cache.put(cacheKey, response.clone());
        }

Did I miss anything?


Solution

  • What may be happening is a cache miss rather than an expiration. When using Cloudflare for caching, you shouldn't expect caching to be guaranteed, in particular using the cache API the docs mention it being data-center specific (not propagated globally) -

    https://developers.cloudflare.com/workers/runtime-apis/cache/#background

    Caching should be mechanism for improving performance, but not relied upon for guaranteed storage in other words. If your use-case requires this, it would be better to use the Workers Key Value -

    https://developers.cloudflare.com/workers/learning/how-kv-works/