I have a simple Next.js app which has a route structure like this:
/contentA/
- Static - First load: 103 kB/contentA/[paramA]/groups
- SSG - First load: 120 kB/contentB/[paramA]/[paramB]/[paramC]
- SSR (returns a client component) - First load: 103 kB
I deploy the app to Vercel on a Hobby plan. When I access the route /contentB/[paramA]/[paramB]/[paramC]
directly or try to refresh the page, I can get the "This Serverless Function has timed out" error, because the corresponding serverless function exceeds the default 10s limit. It doesn't happen every time, but still occurs quite consistently.
I tried to optimize the first load time by using dynamic imports to reduce the JS file size and while I've managed to get down by roughly 50%, it still doesn't seem to help.
There is one fetch request executed when I visit the route, but it cannot be the bottleneck. It returns the response almost immediately.
However, when I try to access the page using Next.js navigation's links, i.e. /contentA/
-> /contentA/[paramA]/groups
-> /contentB/[paramA]/[paramB]/[paramC]
, the loading time of that page is very fast and the overall experience is very snappy.
Can someone help me understand why the loading time of that route takes so much time when reloading the page or accessing it for the first time? Is there any way to improve it or to make it more stable?
I'm using Next.js 13.5.5.
This sounds like the Cold start of the Serverless of Vercel, that probably delays the first run of the calls each time. This is the time needed to start the application again, after not being used for a while, saving up some costs from Vercel's side.
Here are some official guidelines from Vercel to reduce the cold start performance: https://vercel.com/guides/how-can-i-improve-serverless-function-lambda-cold-start-performance-on-vercel
Also, in the following blog post of AWS you can find some architectural designs of the AWS Lambda and why the cold starts are happening: https://aws.amazon.com/blogs/compute/operating-lambda-performance-optimization-part-1/