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.

1
module.exports = (req, res) => {
2
// res.send("Hello, World!")
3
// res.status(500).json({message: "Something went wrong!"})
4
res.json({message: "Hello, World!"})
5
}
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.

1
module.exports = async (req, res) => {
2
await within(getUsers, res, 7000)
3
}
4
5
async function within(fn, res, duration) {
6
const id = setTimeout(() => res.json({
7
message: "There was an error with the upstream service!"
8
}), duration)
9
10
try {
11
let data = await fn()
12
clearTimeout(id)
13
res.json(data)
14
} catch(e) {
15
res.status(500).json({message: e.message})
16
}
17
}
18
19
async function getUsers() {
20
return (await db.getUsers())
21
}
A Serverless Function that sets a timeout limit on an upstream API call.

Couldn't find the guide you need?