I have developed an application in Next.js. For the backend I have used the api endpoints configured in Nextjs which rest inside pages/api
. The api end points quite often return 502(Gateway timeout error) or 504(There is a problem with our deployment).
With some research I found out that it was happening because the server was timing out. For Vercel where I have deployed my Nextjs application, the timeout max period for serverless functions is 10s.
The code for one of endpoints(https://bulkbays.com/api/fetchSections) is
import db from "../../config/db";
import Section from "../../Models/Section";
db();
export default async function handler(req, res) {
console.log('Entered the serverless function')
Section.find()
.lean()
.then((sections) => {
console.log('Fetched Sections',sections)
return res.json(sections);
})
.catch((err) => {
console.log('Error in fetching sessions',err)
return res.json({
status: false,
msg: "An unexpected problem occured",
err,
});
});
}
Please someone tell me how could it take more than 10 seconds. Its the simplest of queries one could make. Also the result of this query is just an array of length 9 with objects as items which has strings as its values. It looks sth like this
[
{
"_id":"6092a55478ccc2092c5e41b0",
"images":["http://res.cloudinary.com/bulkbays97/image/upload/v1620223428/eysvsch2hf4ymajizzcn.jpg","http://res.cloudinary.com/bulkbays97/image/upload/v1620223429/qiwa2idfrntiygsfmnx2.jpg","http://res.cloudinary.com/bulkbays97/image/upload/v1620223429/elwhjk7abwcde7ccqcxf.jpg","http://res.cloudinary.com/bulkbays97/image/upload/v1620223428/yuzhe8iehcyj1rmfyr09.jpg"],
"title":"P-Caps",
"createdAt":"2021-05-05T14:01:56.626Z",
"updatedAt":"2021-05-05T14:01:56.626Z","__v":0
},
....
]
This is the log for one of the requests which sent a 502 or 504 response
[GET] /api/fetchSections
14:36:34:38
Status:-1
Duration:10010.32 ms
Init Duration: N/A
Memory Used:60 MB
ID:x7lh8-1620552994128-a44f049a01ae
User Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0
2021-05-09T09:36:44.511Z 62c16977-9c5c-42f5-961f-a63083638a9c Task timed out after 10.01 seconds
Please guide me regarding this. What should I do? Should I use something like Heroku(not serverless) for this or what?
I made this website for a client and now I do not know what is the problem thats causing this.
When using Vercel with a Hobby plan
, your serverless API routes can only be processed for 5 seconds
. This means that after 5 seconds, the route responds with a 504 GATEWAY TIMEOUT
error.
To resolve this, you would need to reduce the amount of time your API route takes to respond, or upgrade your Vercel plan.