Object 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
    );

    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
    );

    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?

Cloudflare does not guarantee that cached resources will be stored for the entire duration of the max age that’s set. Seldom-used resources will get cleared from cache much faster than resources that are frequently accessed.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.