Handling Stale Data with Cloudflare KV API After Updating Like Count in a Next.js Application

I'm currently working on a Next.js application where user 'likes' are handled through Cloudflare KV API. To enhance security, these updates are routed through Next.js API routes before directly updating the KV store. Although the updates are reflected correctly in the Cloudflare dashboard, fetching like counts immediately after an update seems to return outdated information. This leads to a less responsive user experience, as the UI doesn't show the updated like counts immediately. Has anyone experienced similar issues with Cloudflare KV's cache consistency? What strategies did you employ to ensure that your users see the most recent data after an update? Any insights or suggestions on how to handle this stale data problem would be greatly appreciated. Saving is done with this code.
const response = await fetch(API_URL, {
method: 'POST',
headers: headers,
body: JSON.stringify({
id: id, // Data necessary for the API
userId: userId,
action: action,
}),
cache: 'no-store',
});
const response = await fetch(API_URL, {
method: 'POST',
headers: headers,
body: JSON.stringify({
id: id, // Data necessary for the API
userId: userId,
action: action,
}),
cache: 'no-store',
});
Acquisition is done with this code
export async function getLikeCount(
request: Request,
likeCountsNamespace: KVNamespace,
): Promise<Response> {
try {
const url = new URL(request.url);
const id = url.searchParams.get('id');

if (!id) {
console.warn('Missing id:', { id });
return new Response(JSON.stringify({ error: 'Missing id' }), {
status: 400,
});
}

const countKey = `count-${id}`;
const likeCount = (await likeCountsNamespace.get(countKey)) || '0';

return new Response(JSON.stringify({ count: parseInt(likeCount, 10) }), {
headers: {
'Cache-Control': 'no-cache, no-store, must-revalidate',
},
});
} catch (error) {
console.error('Error in handleGetLikeCount:', error);
return new Response(JSON.stringify({ error: 'Internal Server Error' }), {
status: 500,
});
}
}
export async function getLikeCount(
request: Request,
likeCountsNamespace: KVNamespace,
): Promise<Response> {
try {
const url = new URL(request.url);
const id = url.searchParams.get('id');

if (!id) {
console.warn('Missing id:', { id });
return new Response(JSON.stringify({ error: 'Missing id' }), {
status: 400,
});
}

const countKey = `count-${id}`;
const likeCount = (await likeCountsNamespace.get(countKey)) || '0';

return new Response(JSON.stringify({ count: parseInt(likeCount, 10) }), {
headers: {
'Cache-Control': 'no-cache, no-store, must-revalidate',
},
});
} catch (error) {
console.error('Error in handleGetLikeCount:', error);
return new Response(JSON.stringify({ error: 'Internal Server Error' }), {
status: 500,
});
}
}
2 Replies
Hello, I’m Allie!
We generally recommend using something like Durable Objects for stuff that requires Atomicity, like tracking Likes As you have experienced with KV, there is not a guarantee that the value returned is the latest value
Watagori
WatagoriOP8mo ago
Thanks! I see what you mean...kv makes it difficult...got it!
Want results from more Discord servers?
Add your server