Next.js Discord

Discord Forum

Does cache / unstable_cache work during build process?

Unanswered
Maremmano-Abruzzese Sheepdog posted this in #help-forum
Open in Discord
Maremmano-Abruzzese SheepdogOP
Hi, I am doing some data fetching in a server component Layout.tsx, which seems to work fine in production, but during the actual building (on Vercel) it seems to make new calls for every page where this cached data fetching function is called.

Am I doing something wrong or is that how it's supposed to work?

9 Replies

Maremmano-Abruzzese SheepdogOP
The problem here being that those pages are generated in parallel, meaning the data fetching call gets called simultaneously multiple times leading to hitting API rate limits.
Maremmano-Abruzzese SheepdogOP
bump
cache !== unstable_cache, be super mindful that they are not the same thing at all
cache will deduplicate calls for 1 request/response roundtrip, so it will prevent multiple calls to the same underlying API for a single page => you can shove user specific values here without any problem
unstable_cache is a shared cache, it will deduplicate calls for multiple requests => be careful when handling user specific values here!
also, in a distributed system, there might still be multiple instances of unstable_cache, so it's not a guarantee that you get one call, more a guarantee that you get one call per process that is building your code
so if there is a parallel build you can observe multiple calls$
given that this is internal to Vercel and this cache is, well, unstable, it's sometimes hard to infer the expected behaviour
Maremmano-Abruzzese SheepdogOP
Thanks @Eric Burel that clears up a lot. unstable_cache is the behavior I'm looking for then. I have no user-specific data, just general data from an API that I want to refetch hourly to have the most up to date version. I want to cache this data fetching request just to prevent hitting API limits (and the data does not change that much, so caching hourly is fine).

Given that use case, do you think unstable_cache wrapping the api call and being called in Layout.tsx (the same data is used in a few different subroutes) is the right approach?