Next.js Discord

Discord Forum

Data revalidation race

Unanswered
Turkish Van posted this in #help-forum
Open in Discord
Turkish VanOP
I encountered some interesting behaviour when it comes to data caching and revalidating it.

I've built a simple blog app with simple functions like create post, like post and comment a post.
What I am doing is am caching the getPosts function data that retrieves all the posts with its comments and likes.

Once user creates/deletes a post, likes/unlikes any of the posts, or creates a comment, data is revalidated.
Everything works well and as expected but there is one edge case which results in unexepected, but explainable, behaviour.

Once user likes multiple posts, it triggers as many database requests as it's supposed to, and revalidates data on each request.

But, there is a case where not the latest database request gets executed last and, following that, not the latest ones data gets stored in cache last.
By that, not the latest updated data gets stored in a cache and represents the latest updated data.

Is there a way to handle it?

9 Replies

@joulev I don’t really get what you mean. Do you mean that, when say a user likes five comments in quick succession, the order might not be as expected and hence the last cache revalidation doesn’t necessarily reflect the newest data?
Turkish VanOP
So when a user likes a post, it creates a post request to database, revalidates the getPosts function data and stores it in a cache.

And yes, if user likes 5 posts in quick succession, getPosts function data gets revalidated 5 times and the order of it being executed might not be as expected which results in not the newest data being stored inside of cache.
Netherland Dwarf
Im not sure if this helps but
Are you using tan stack
I just recently learned that tanstack react query solves this race conditions
@Netherland Dwarf Are you using tan stack
Turkish VanOP
Nope.

Here is a likePost code snippet:
export const likePost = async (postId: string) => {
    const supabase = createClient();

    const { error } = await supabase
        .from("posts_likes")
        .insert<TablesInsert<"posts_likes">>({ post_id: postId });

    if (error) return { error };
    revalidatePath("/");
};
@joulev If you are using server actions, shouldn’t they be queued so they always run in the same order? Though I’d recommend writing your queries in such a way that doesn’t rely on the order being correct
Turkish VanOP
I am not sure what would that way be, since it is just a function that creates a database request, and revalidates data after it, on user interaction.

Maybe there is something that I'm missing out.

And yes, likePost function is a Server Action.
Turkish VanOP
Same behaviour happens if user writes multiple comments in quick succession.