cache data between serverless calls in nextjs api in vercel deployment
Unanswered
Mottled Petrel posted this in #help-forum
Mottled PetrelOP
Hi, it's unclear whether this is possible and how to achieve it.
We have a route like
For example, we fetch the
We implemented a simple in-memory cache with a
It's been hard to figure out what happens in production, because I couldn't find any networking logs on vercel, and dev mode behaves differently from production mode, but I don't expect the in-memory solution to work so I didn't spend a lot of time trying to set it up so I can see it work.
In theory there is a solution of setting up an
Any solutions here? Is there some function/object vercel exposes that persists data? Should I use the file system?
We have a route like
/api/credits, that computes the amount of credits the user has left, and returns it. The computation should be done every time this is called, and that's ok, but some parts of the computation should be cached.For example, we fetch the
plan_id from the current user from database, and fetch the plan data from database in a separate call, based on that plan_id. The plan data is static and won't change over the course of a week, so this fetching of plan data from plan_id could benefit from caching.We implemented a simple in-memory cache with a
Map, but looking around online it sounds like this might not work because these are serverless and shouldn't retain memory between calls. Any idea if there's a way to manage that in vercel?It's been hard to figure out what happens in production, because I couldn't find any networking logs on vercel, and dev mode behaves differently from production mode, but I don't expect the in-memory solution to work so I didn't spend a lot of time trying to set it up so I can see it work.
In theory there is a solution of setting up an
/api/_plan_info_by_id/:id route and getting vercel to cache that, then calling this instead of our database, but that feels hacky and needs a security layer not to leak data.Any solutions here? Is there some function/object vercel exposes that persists data? Should I use the file system?
1 Reply
@Mottled Petrel in general, people use Redis cache. but Vercel KV is still beta, or you can use Upstash Redis directly. a map in global variable could work under heavy traffic situation so lambda is so hot.