Skip to content

What can I do about Vercel Serverless Functions timing out?

Serverless Functions are best used as lightweight backend helpers that respond quickly to clients. Sometimes you may find that your Functions are exceeding the execution limits and returning a timeout error. Read on to learn what you can do when that happens.

Check the Response

Your Serverless Functions need to return an HTTP Response even if it's a response that indicates an error. If a response isn't returned from the function, a timeout error will occur.

module.exports = (req, res) => {
    // res.send("Hello, World!")
    // res.status(500).json({message: "Something went wrong!"}) 
    res.json({message: "Hello, World!"})
}

A Serverless Function responding with a JSON message via Vercel Node.js helpers.

Check for Upstream Errors

If you're connecting to an external database or dependending on a third-party API before responding, check to make sure there are no errors upstream. Make sure you have all the right environment variables set for talking to third party services successfully.

In the event of an error upstream, it is still good practice to return something informative to the client. If the upstream service hasn't responded to you successfully within a certain time, return a response indicating the error.

module.exports = async (req, res) => {
    await within(getUsers, res, 7000)
}

async function within(fn, res, duration) {
    const id = setTimeout(() => res.json({
        message: "There was an error with the upstream service!"
    }, duration)
    
    try {
        let data = await fn()
        clearTimeout(id)
        res.json(data)
    } catch(e) {
      res.status(500).json({message: e.message})
    }
}

async function getUsers() {
    return (await db.getUsers())
}

A Serverless Function that sets a timeout limit on an upstream API call.

Couldn't find the guide you need?