Improving Serverless Function response time on Vercel
vatana7
Posted on August 17, 2023
Introduction & Problem
So I have built a side project in my free time to expand my knowledge on NextJs, the problem that I have found is that when I navigate to my website the first time, I have noticed that the loading time to load data from MongoDB was incredibly slow. Knowing that MongoDb query is fast, I understand that the problem itself was not with MongoDB but it definitely has something to do from my side of development.
The Reason
There is a guide on Vercel's webpage explaining why the initial load take time ranging from under 100ms to over 1 seconds because of the fact that every time you load your webpage that isn't visited often (no traffic, only visit by you), your serverless function cease to exist and has to be newly created every time you visit the webpage once in a while.
This process also known as (Cold Boot). Any subsequence request after the Cold Boot are going to be much faster and quicker.
As you can see in the diagram, the first two step (Cold Boot) will involve taking time to firing up at the cost of delayed response.
Solutions
-
So what should be the solution to the problem? Well the first answer should be obvious to you already.
Your webpage should have moderate traffic to keep the serverless function alive and avoid Cold Boot
Another solution to change the region that is used to deploy your serverless function in near your database region. In default deployment, your serverless function is deployed in
iad1
which is US, Washington DC.
So in this case, for example if I have my MongoDb instance deployed at Singapore I wouldn't want my serverless function to be deployed at US, the answer should be obvious, of course it has to be the same as Singapore too.
- Another available solution which is newly introduced into the world of Web Development is Vercel's Edge Runtime. They claimed that it's very fast in the Response time department. I have tried to connect to MongoDB with Edge Runtime but because my app use MongoDB and Mongoose doesn't support Edge yet I have to rely on the region solution as of now.
I hope you learn something new from this article and thank you for reading.
Posted on August 17, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 9, 2023