Nov 18, 20268 min read

Vercel Function Timeout: How to Fix FUNCTION_INVOCATION_TIMEOUT

The duration limits by plan and runtime, how to find out why a function runs long, the fixes that work inside Vercel, and what to do with work that will never fit in a request.

Illustration for Vercel Function Timeout: How to Fix FUNCTION_INVOCATION_TIMEOUT

A Vercel Function that runs past its limit is stopped and the caller gets a 504 with the error code FUNCTION_INVOCATION_TIMEOUT. Sometimes the fix is one line of configuration. More often the timeout is a symptom: a database connection that takes seconds to open, a third-party API with no timeout of its own, or a job that was never going to fit in one request.

This guide covers the current limits, a short process for finding the cause, the fixes that work inside Vercel, and where long-running work should go instead.

The Limits

With fluid compute, enabled by default for new projects, the duration limits for the Node.js, Bun and Python runtimes are:

PlanDefaultMaximumExtended maximum
Hobby300s300sNot available
Pro300s800s1800s (beta)
Enterprise300s800s1800s (beta)

The Edge runtime works differently: a function must begin sending a response within 25 seconds, then can keep streaming for up to 300 seconds. Request and response bodies are capped at 4.5 MB, apart from streamed responses, which hits upload and export endpoints at the same time as the duration limit.

Cron jobs and functions triggered from queues use the same duration limits, since every invocation is a function invocation.

Find Out Why It Runs Long

Raising the limit hides the problem without fixing it, and with fluid compute a longer duration means more billed provisioned memory for the time the instance is busy. Before changing anything, work out where the time goes.

  1. Check the runtime logs for the slow invocation. The function's log in the Vercel dashboard shows the duration and any output before the timeout. A timeout right at the limit with no log lines after the first query suggests something is hanging, rather than running slowly.
  2. Time each external call. Wrap database queries and outbound fetch calls with timestamps. One unbounded call is the usual culprit.
  3. Look at connection setup. A function that opens a new Postgres connection per invocation can spend seconds on TLS and authentication under load, and run out of connections on the database side.
  4. Compare cold and warm runs. If only the first request after a deploy is slow, the cost is in module initialization, such as loading large SDKs or reading files at import time.

Fixes Inside Vercel

Raise maxDuration Where It Is Justified

For a route that legitimately needs longer, such as generating a report, set the limit on that route only. In Next.js 13.5 or later, export it from the route file:

// app/api/reports/route.ts export const maxDuration = 120; // seconds, up to your plan's maximum export async function POST(request: Request): Promise<Response> { // generate the report... return Response.json({ ok: true }); }

For other frameworks, or for a pattern of files, use vercel.json:

{ "$schema": "https://openapi.vercel.sh/vercel.json", "functions": { "api/reports/*.js": { "maxDuration": 120 } } }

Setting a lower limit on routes that should be fast is equally useful, since a hung request then fails in seconds instead of holding an instance for five minutes.

Put Timeouts on Everything You Call

A function timeout is the last line of defense. Give every outbound call its own, shorter, deadline so a slow dependency becomes a handled error with a useful message:

// lib/fetch-with-timeout.ts export async function fetchJSON<T>(url: string, ms = 8000): Promise<T> { const res = await fetch(url, { signal: AbortSignal.timeout(ms) }); if (!res.ok) throw new Error(`${url} returned ${res.status}`); return (await res.json()) as T; }

For Postgres, set statement_timeout on the connection or role so a missing index fails a query after a few seconds rather than running into the function limit.

Reuse Database Connections

Create the pool at module scope so warm invocations reuse it, and use a pooler such as PgBouncer or your provider's pooled endpoint. Vercel's @vercel/functions package includes attachDatabasePool for releasing idle pool connections before an instance is suspended.

Stream the Response

If the user is waiting on something that is produced incrementally, such as LLM output, streaming sends the first bytes early. On the Edge runtime that is required within 25 seconds. On Node.js it does not extend maxDuration, but it turns a long blank wait into visible progress.

Do Not Count on waitUntil or after()

waitUntil from @vercel/functions, and after() in Next.js 15.1 and later, run work after the response has gone out. They are good for logging and analytics. They are not a way around the limit: Vercel's docs state that promises passed to waitUntil have the same timeout as the function. A ten-minute job started in after() is still stopped at maxDuration.

When the Work Does Not Fit in a Request

Some work is long by nature: a CSV import with 200,000 rows, a video transcode, an export of a year of data, an agent that calls tools for several minutes. Raising the limit to 800 seconds only moves the cliff. The pattern that holds up is the same everywhere:

  1. The request validates input, records a job row, enqueues a message and returns a job ID within a second.
  2. A worker picks up the message and does the work, in chunks if possible, with retries for transient failures.
  3. The client polls a status endpoint or gets a webhook when the job finishes.

On Vercel itself, this means Vercel Queues or Vercel Workflows, which run multi-step work with retries, with each function invocation still under the duration limit. Outside Vercel, it means a queue and a worker process that has no per-request ceiling.

How Encore Runs Long Jobs

Encore is a backend framework for TypeScript and Go with built-in infrastructure. API endpoints, Pub/Sub topics and object storage buckets are declared in code, and the services run as long-lived containers instead of per-request functions. The export below follows the three steps above, with the subscriber's ackDeadline set for a job that takes minutes.

// exports/exports.ts import { api, APIError } from "encore.dev/api"; import { Topic, Subscription } from "encore.dev/pubsub"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { Bucket } from "encore.dev/storage/objects"; import { randomUUID } from "node:crypto"; const db = new SQLDatabase("exports", { migrations: "./migrations" }); const files = new Bucket("export-files"); interface ExportRequested { jobId: string; accountId: string; } const exportRequested = new Topic<ExportRequested>("export-requested", { deliveryGuarantee: "at-least-once", }); // 1. Accept the request and return immediately. export const startExport = api( { expose: true, method: "POST", path: "/exports" }, async ({ accountId }: { accountId: string }): Promise<{ jobId: string }> => { const jobId = randomUUID(); await db.exec`INSERT INTO export_jobs (id, account_id, status) VALUES (${jobId}, ${accountId}, 'queued')`; await exportRequested.publish({ jobId, accountId }); return { jobId }; }, ); // 2. Do the long work in a subscriber, not in the request. const _ = new Subscription(exportRequested, "build-export", { ackDeadline: "10m", retryPolicy: { minBackoff: "30s", maxBackoff: "10m", maxRetries: 5 }, handler: async ({ jobId, accountId }) => { await db.exec`UPDATE export_jobs SET status = 'running' WHERE id = ${jobId}`; const lines: string[] = ["id,amount,created_at"]; const rows = db.query<{ id: string; amount: number; created_at: Date }>` SELECT id, amount, created_at FROM transactions WHERE account_id = ${accountId} ORDER BY created_at`; for await (const r of rows) { lines.push(`${r.id},${r.amount},${r.created_at.toISOString()}`); } await files.upload(`${jobId}.csv`, Buffer.from(lines.join("\n")), { contentType: "text/csv" }); await db.exec`UPDATE export_jobs SET status = 'done' WHERE id = ${jobId}`; }, }); // 3. The client polls for the result. export const getExport = api( { expose: true, method: "GET", path: "/exports/:jobId" }, async ({ jobId }: { jobId: string }): Promise<{ status: string; url?: string }> => { const job = await db.queryRow<{ status: string }>`SELECT status FROM export_jobs WHERE id = ${jobId}`; if (!job) throw APIError.notFound("no such export"); if (job.status !== "done") return { status: job.status }; const { url } = await files.signedDownloadUrl(`${jobId}.csv`, { ttl: 900 }); return { status: "done", url }; }, );

The download goes straight from the bucket through a signed URL, which also sidesteps any response size limit. Add an auth handler and scope getExport to the caller's account before shipping. encore run starts Postgres, an in-memory Pub/Sub and local object storage. A deploy to your own cloud creates SNS with SQS, S3 and RDS on AWS, or Pub/Sub, Cloud Storage and Cloud SQL on GCP.

The subscriber still has a deadline: if a message is not acknowledged within ackDeadline, it is delivered again. For jobs that can run longer than that, process in chunks and publish a follow-up message for the next chunk, which keeps every unit of work short and retryable.

Which Fix to Use

SymptomFix
One slow query or API callPer-call timeouts, an index, statement_timeout
Many connections, slow under loadPool at module scope, use a pooler
Legitimately slow, under a few minutesRaise maxDuration on that route only
User waits for incremental outputStream the response
Minutes of work, or unbounded sizeQueue plus worker, poll for status

Frequently asked questions

What is the Vercel function timeout?

With fluid compute, which is on by default, Vercel Functions on Node.js, Bun and Python default to 300 seconds. Hobby cannot go higher. Pro and Enterprise can raise maxDuration to 800 seconds, and to 1800 seconds in the extended duration beta. A function that runs past its limit returns a 504 FUNCTION_INVOCATION_TIMEOUT.

How do I increase the timeout of a Vercel function?

In Next.js 13.5 or later, export const maxDuration = 120 from the route or page file. For other frameworks and runtimes, set maxDuration for a path pattern under functions in vercel.json. The project default can also be changed under Functions in the project settings.

Does waitUntil or after() avoid the Vercel timeout?

No. Both let work continue after the response is sent, but Vercel's docs state that promises passed to waitUntil have the same timeout as the function. The work still has to finish within maxDuration.

What is the timeout for Vercel Edge Functions?

Functions on the Edge runtime must begin sending a response within 25 seconds, and can then continue streaming for up to 300 seconds.

How do I run long jobs that exceed the Vercel function timeout?

Return quickly from the request and hand the work to a queue or a durable workflow that runs it in steps, or to a long-running service. With Encore, an API endpoint publishes a Pub/Sub message and a subscription processes it in a container on AWS or GCP in your own account, with its own ack deadline and retries, while the client polls a status endpoint.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders