DEV3 Technologies home

DEV3 Developer Forum

Why does my Next.js route time out on Vercel while it works locally?

Next.js helpSolved0 views
dev3 ·

A route handler that imports 3000 rows and calls an external API takes 20 seconds locally. On Vercel I get FUNCTION_INVOCATION_TIMEOUT (504). How do I fix or raise the limit?

#nextjs#vercel#serverless

0

1 reply

dev3 · Accepted answer

Serverless functions have a maximum duration that depends on your plan and configuration. Locally there is no limit, which hides the problem.

Raise the limit for the route

// app/api/import/route.ts
export const maxDuration = 60; // seconds, capped by your plan
export const runtime = "nodejs";

Limits differ by plan and with Fluid compute settings; check the current Vercel docs for your plan's cap rather than assuming a number.

Better: do not hold the request open

  1. Respond fast, work in the background. Return 202 with a job id and process using a queue (Inngest, QStash, Trigger.dev, BullMQ) or a worker on a VPS.
  2. Use after() (stable in Next.js 15.1+) to run work after the response is sent:
import { after } from "next/server";
export async function POST() {
  after(async () => { await sendEmails(); });
  return Response.json({ queued: true }, { status: 202 });
}

It still counts against the function duration, so it is for short tasks. 3. Stream progress with a ReadableStream so the connection stays alive, within the max duration. 4. Batch the import: process 200 rows per invocation and let the client or a cron call the next batch.

Other causes of slow cold requests

  • Opening a new database connection each call (cache it, see the Mongoose pattern).
  • A database in a different region from the function. Set the function region near the DB in vercel.json or project settings.
  • Large bundles from server imports. Check the build's function size.

Pitfall: memory limits give different symptoms (out of memory or a crash with no body). Process large files as streams instead of loading everything.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.