4 solutions to Vercel function timeouts
Solving Vercel timeout issues isn't only about increasing the timeout but also using the right tools for the job.
Charly Poly· 10/30/2024 · 6 min read
Vercel is a great platform for TypeScript developers, especially those creating globally distributed applications using React and the serverless approach.
Many Vercel first users face limitations linked to the nature of serverless. Vercel Functions are meant to serve direct user interactions or API calls and, by design, should be completed quickly.
Still, many developers want to leverage Vercel Functions to build integrations, AI workflows, or data import, which may cause requests to last longer than the default 10s max duration.
Hitting the limitations of Vercel Functions duration does not mean that Vercel Functions are unfit for your use case. Sometimes, you just need to take a different approach to writing such long-running code — to avoid timeouts and guarantee a sensible application architecture. This article will cover four free and paid approaches to solving your Vercel Functions timeout issues.
Bump your Vercel Function max duration
This first solution applies if you need to keep your piece of long-running code user or API-facing (in short, in a Vercel Function that returns data synchronously).
A first quick-win that most people miss is the ability to bump your Vercel Function max duration from 10s to 60s by updating the vercel.json
file:
{"functions": {"app/api/mySlowFunction/route.ts": {"maxDuration": 60}}}
However, we recommend avoiding enabling a 60-second timeout for all your functions. Longer timeouts make it harder to pinpoint Vercel Functions that are not behaving correctly (and consume your free tier allowance faster).
Still, if you'd like to enable a higher max duration for all your functions and projects, follow these steps:
- From your dashboard, select your project and go to the Settings tab.
- From the left side, select the Functions tab and scroll to the Function Max Duration section. Finally, update the Default Max Duration field value and select Save.
Leverage Edge Function's infinite duration
Is increasing your Vercel Function max duration to 60 seconds not enough?
Then, you might want to consider transforming your long-running piece of code into a streamed response.
The perfect use case for streaming is code that relies on an external API offering streamed endpoints. The most famous AI APIs are OpenAI and Gemini, but other services, such as Twitter or YouTube, offer streamed endpoints.
If you are developing AI features, consider using the AI SDK. This will help you maximize the model's streaming capabilities and leverage the Edge Function's longer max duration.
If your code is not relying on streamed endpoints, you might experiment with the Stream API by wrapping your code as a “fake stream” (technique currently used by Vercel AI with o1-preview
):
export const config = {runtime: 'edge',};export default async function handler(req: Request): Promise<Response> {// Create a ReadableStream to stream the dataconst stream = new ReadableStream({async start(controller) {// Simulate long-running task with multiple stepsconst startSync = async () => {controller.enqueue(`Sync started.`);// perform time-consuming data-syncconst data = await getDataFromExternalSource();await db.syncs.insertMany(data);controller.enqueue(`Sync completed.`);// Close the stream when donecontroller.close();};// Execute the taskstartSync();},});// Return the stream as a response with appropriate headersreturn new Response(stream, {headers: { 'Content-Type': 'text/plain; charset=utf-8' },});}
This hack will solve your duration limits but require the consumer (front-end or another API) to consume the stream until the Edge Function is completed. Any closing of the stream will terminate the Edge Function execution.
Going with a “fake streaming” approach indicates that your consumer doesn't need a sync response from your Function. In that case, you might consider running your code asynchronously using a Durable Function.
Move your code into a Durable Function
A piece of code running for a long time without returning a response synchronously is a good candidate for Durable Functions.
Durable Functions are the asynchronous alter ego of Vercel Functions, enabling you to run code asynchronously for extended periods.
You can transform your existing Vercel Function into Durable Functions by leveraging Inngest's similar developer experience.
First, you'll need to move your existing code into an Inngest Function:
inngest.createFunction({id: "long-running-code",},// A Function is triggered by events{ event: "sync/start" },async ({ step }) => {// step is retried if it throws an errorconst data = await step.run("get-data", async () => {return getDataFromExternalSource();});// Steps can reuse data from previous onesawait step.run("save-data", async () => {return db.syncs.insertMany(data);});});
And finally, replace your Vercel Function code with the following Inngest Function invocation:
import { inngest } from '@lib/inngest/client'export const dynamic = 'force-dynamic';export function POST(request: Request) {await inngest.send({name: "sync/start",data: {// The event's data (params)},});return new Response(`Sync triggered!`);}
Running code for an extended period is only the tip of the iceberg of Inngest Functions benefits.
Inngest Functions also brings:
- Automatic retries: handy when exchanging with external APIs.
- Throttling and Concurrency: to avoid hitting 3rd party rate limits.
- Sleeps: useful when implementing user onboarding workflows or email drip campaigns.
Do you still want to keep your long-running code in a Vercel Function? There is one solution left.
Still hitting the limits? Move to a Vercel Pro or Enterprise plan
All the solutions mentioned above relying on the Vercel free tier will still run against the total 100 hours offered per month.
If your long-running piece of code must return a synchronous response and cannot be streamed, the only solution is to move to a Vercel paid plan.
The Vercel Pro plan increases your default max duration to 15 seconds, configurable for up to 5 minutes:
Default | Configurable up to | Using Edge Functions | |
---|---|---|---|
Hobby plan | 10s | 60s | Unlimited |
Pro plan | 15s | 300s | Unlimited |
Enterprise plan | 15s | 900s | Unlimited |
Takeaways
We discussed four ways to solve Vercel function timeouts:
- You can bump the max duration to 60 seconds (although this has downsides).
- You can wrap your code in a “fake stream” and use Edge Functions (not a very good architectural decision, but it will work).
- You can use a Durable Function in combination with your Vercel function—architecturally, this is a smart option, even though it takes some work to set up.
- You can upgrade to the Pro or Enterprise tier on Vercel to get a 300s or 900s timeout, respectively.
Chat with a solutions expert
Connect with us to see if Inngest fits your queuing and orchestration needs.
Contact us