'Getting a 504/502 error on api requests in Nextjs deployed on Vercel

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.



Solution 1:[1]

Try and isolate the source of the issue first, so you know what steps to take next.

For example, try returning some dummy data without using or connecting to the DB.


export default async function handler(req, res) {

    console.log('Entered the serverless function')

    return { "dummy": "data"}
}

If you still have timeout issues, you now know it's probably because of your Vercel NextJS setup.

If your NextJS setup is not the problem, then you know the issue is caused by your DB. Either the problem is in the query itself, or in the connection.

I'm not sure what DB you're using (I assume it's MongoDB from the syntax).

Most likely possible solutions:

  • It's not very clear what db() does or what it is. I assume it handles connection to the MongoDB instance. Either way, make sure to check if the db() function is asynchronous or not. It's a common mistake; If the function is async and you don't call it properly, then it's possible that the timeout is caused by this asynchronous issue.
  • Do you create new connections for each request or do you reuse existing open connections? Creating a new connection every time can be expensive; It's possible that that's what causes your timeout issue.

If these don't work, try the below:

  • How is your DB hosted? Is it managed by Vercel? Try using another manager to see if that is where the issue resides.
  • Is everything setup correctly in your Vercel dashboard? Make sure you have the correct MongoDB connection string, and that your MongoDB instance is set up to accept connections from your app.

Solution 2:[2]

What I did as a result of constant research was that I posted the API on Heroku and the frontend on Vercel. I read this suggestion in one stackoverflow post from a guy who said that he worked in Vercel and this was the most suitable solution for this.

I think this is a problem with the serverless architecture itself. I tried deploying Nextjs on netlify and faced a similar situation.

Solution 3:[3]

I faced the same issue of

Task timed out after 10.01 seconds

with Next.js API endpoints that connect to MongoDB(atlas). The root cause for me is actually that the network access in MongoDB was set to my own IP address and hence disallowed from my deployed application. For those who are facing the same issues with Next.js functions, please also check that MongoDB is configured correctly to accept connections from IP addresses other than your own IP.

See below for context:

NOTE: Vercel uses dynamic IP addresses so you'll need to add an exception to access from any IP address in your MongoDB Atlas dashboard. To do this simplify navigate to the Network Access tab, hit the Add IP Address button, and then hit the Allow Access From Anywhere button or for the Access List Entry enter 0.0.0/0.

Solution 4:[4]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 yaken
Solution 2 Usman Abdur Rehman
Solution 3
Solution 4 Saif Ullah