Vercel 504 FUNCTION_INVOCATION_TIMEOUT on an AI route: make the function finish in time
By AI App Medic · Updated · Vercel · Next.js · OpenAI · Cursor
The chat, summary or "generate" button works on your machine. On Vercel it spins for a while and then fails. Depending on where you look, you see one of these:
504: GATEWAY_TIMEOUT
Code: FUNCTION_INVOCATION_TIMEOUT
Vercel Runtime Timeout Error: Task timed out after 60 seconds
Unhandled Runtime Error
SyntaxError: Unexpected token 'A', "An error o"... is not valid JSON
The last one is the front end trying to parse Vercel's plain text error page as JSON. All three mean the same thing: the function was still running when it hit its maximum duration, and Vercel stopped it. Model calls are slow and uneven, a long answer from a large model can take a minute or more, and code generated by Cursor, v0 or Bolt rarely sets any limits of its own. Locally the dev server waits forever, so you never see it.
Step 1: read how long the requests ran
Open the project in Vercel, go to Logs, filter on the route (for example /api/chat) and look at the duration of the failed requests. The number tells you which limit you hit:
- About 10, 15 or 60 seconds: the project runs without Fluid compute, on the older limits. Hobby defaulted to 10 seconds with a maximum of 60, Pro to 15 with a maximum of 300.
- About 25 seconds: the route runs on the Edge runtime, which must start sending a response within 25 seconds.
- Exactly your
maxDuration: you set a limit and the work does not fit in it. - About 300 seconds: the default with Fluid compute. A request that takes five full minutes is almost never a slow model. It is a handler that never returns a response, a promise that never settles, or retries stacking up. See Step 4 and Step 6.
To see the configured limit of a deployment, run vercel inspect <deployment-url> --json and look at timeout for each function.
Step 2: check Fluid compute and the runtime
Vercel turned Fluid compute on by default for new projects in April 2025. Older projects, and projects created from old templates, may still have it off. In the project, open Settings, then Functions, and check the Fluid compute setting. With it on, every plan gets a 300 second default. Turning it on and redeploying fixes the 10 and 15 second cases by itself.
Then search the code for the Edge runtime:
grep -rnE "runtime\s*=\s*['\"]edge['\"]|runtime:\s*['\"]edge['\"]|maxDuration" app pages src
AI templates used to put export const runtime = "edge" on chat routes. On Edge, a route that waits for the full model answer before sending anything fails at 25 seconds. Unless you need Edge for a specific reason, delete that line so the route runs on Node.js, which has the full duration and supports every npm package.
Step 3: set maxDuration on the AI route
In the App Router, export it from the route file. The value is in seconds and must be within your plan's maximum:
// app/api/chat/route.ts
export const maxDuration = 120;
In the Pages Router, use the config object:
// pages/api/chat.ts
export const config = { maxDuration: 120 };
If the AI call runs inside a Server Action rather than a route handler, the limit comes from the page that uses the action, so export maxDuration from that page.tsx. Only raise it where it is needed. A high limit on every function means a hung request keeps running, and billing, for the whole time.
Step 4: give the OpenAI call a deadline and always answer
The official OpenAI Node client waits up to 10 minutes per request by default and retries failed and timed out requests twice. One slow call can easily outlast the function, and when Vercel stops the function your code never reaches its catch, so you get a 504 and no useful log line. Set a deadline shorter than maxDuration and keep retries low:
// app/api/summary/route.ts
import OpenAI from "openai";
export const maxDuration = 60;
const openai = new OpenAI({
timeout: 45_000, // ms, leaves time to answer before Vercel's 60 s
maxRetries: 0,
});
export async function POST(req: Request) {
try {
const { text } = await req.json();
const completion = await openai.chat.completions.create({
model: process.env.OPENAI_MODEL!,
messages: [{ role: "user", content: `Summarise:\n\n${text}` }],
});
return Response.json({ summary: completion.choices[0].message.content });
} catch (err) {
console.error("summary failed", err);
const timedOut = err instanceof OpenAI.APIConnectionTimeoutError;
return Response.json(
{ error: timedOut ? "The AI took too long. Try a shorter text." : "The AI request failed." },
{ status: timedOut ? 504 : 502 }
);
}
}
Now a slow model gives the user a clear message and gives you a log line that says what happened. Make sure the front end can read it. Check the status before parsing, because a platform error page is not JSON:
const res = await fetch("/api/summary", { method: "POST", body: JSON.stringify({ text }) });
const data = res.headers.get("content-type")?.includes("application/json")
? await res.json()
: { error: `Server error ${res.status}` };
if (!res.ok) showError(data.error);
Step 5: stream the answer
For chat and long text, stream. The user sees words within a second or two, and on the Edge runtime streaming is the only way past the 25 second first-response rule. With the OpenAI client and a plain ReadableStream:
// app/api/chat/route.ts
import OpenAI from "openai";
export const maxDuration = 120;
const openai = new OpenAI({ timeout: 100_000, maxRetries: 1 });
export async function POST(req: Request) {
const { messages } = await req.json();
let stream;
try {
stream = await openai.chat.completions.create({
model: process.env.OPENAI_MODEL!,
messages,
stream: true,
});
} catch (err) {
console.error("chat start failed", err);
return Response.json({ error: "The AI service did not answer." }, { status: 502 });
}
const encoder = new TextEncoder();
const body = new ReadableStream({
async start(controller) {
try {
for await (const chunk of stream) {
const text = chunk.choices[0]?.delta?.content;
if (text) controller.enqueue(encoder.encode(text));
}
} catch (err) {
console.error("chat stream broke", err);
controller.enqueue(encoder.encode("\n[The answer was cut off. Please try again.]"));
} finally {
controller.close();
}
},
});
return new Response(body, {
headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" },
});
}
If the project already uses the Vercel AI SDK, keep its streaming helpers instead and only add maxDuration and the timeout. Streaming does not lift the limit: the maximum duration includes the time spent streaming, so a very long answer still needs a maxDuration that covers it.
Step 6: return a response on every path
A function that finishes without sending a response is kept open until it times out. In generated code this hides in error branches:
// pages/api/generate.ts: times out when the call fails
export default async function handler(req, res) {
try {
const result = await generate(req.body);
res.status(200).json(result);
} catch (err) {
console.error(err); // no response sent, the request hangs
}
}
Add res.status(500).json({ error: "Generation failed" }) in the catch, and check every early return in the handler. The same applies to promises that never resolve, for example a wrapper around a callback API that forgets to call reject on errors. If the logs show the function starting and nothing else until the timeout, look here first.
Step 7: move long jobs out of the request
If an upload fails with 413 FUNCTION_PAYLOAD_TOO_LARGE before your code even runs, that is the request body limit, not a timeout. See Vercel 413 FUNCTION_PAYLOAD_TOO_LARGE on file uploads.
Some work is too long for a request a user waits on: generating a 40 page report, processing an uploaded PDF, running many model calls in a loop. Raising maxDuration to the maximum only moves the wall. Split it instead:
- The route validates the input, inserts a row in a
jobstable with statusqueued, and returns the job id right away. - A worker does the work: a queue consumer, a scheduled function that picks up queued jobs, or a separate long-running service. It writes the result and sets status
doneorfailed. - The page polls
/api/jobs/IDevery few seconds, or subscribes to changes on that row, and shows the result when it is ready.
The after() function in Next.js and waitUntil() from @vercel/functions let work continue after the response is sent, which is right for logging or sending an email. They still count toward the function's maximum duration, so they are not a way to run a ten minute job.
If the job loops over model calls, run independent calls in parallel with Promise.all in small batches instead of one after another, and cache results that do not change.
Step 8: put the function near your database
An AI route often reads context from the database before calling the model, and writes the answer back afterwards. New Vercel projects run functions in Washington, D.C. (iad1) unless you change it. If your Supabase project is in Frankfurt, every query crosses the Atlantic, and a route that makes twenty queries spends seconds just waiting on the network. Set the function region in Project Settings, Functions, to the one closest to the database, or in vercel.json:
{
"regions": ["fra1"]
}
If the database queries themselves are slow, the timeout is only where it shows up. Fix the queries first; canceling statement due to statement timeout covers missing indexes and slow RLS policies.
Do not "fix" it by calling OpenAI from the browser
A common suggestion from AI assistants is to call the model directly from the client, where there is no function limit. That ships your API key in the JavaScript bundle, and anyone can copy it from DevTools. Keep model calls on the server. If you already did this, rotate the key and read API key exposed in your Vite or React bundle. Also confirm the server actually has the key: a missing OPENAI_API_KEY in the Production environment fails fast with a 401, not a timeout, and is covered in Next.js environment variables undefined on Vercel.
Prevention
Give every external call a timeout and a retry budget that fit inside the function's maxDuration, and write both down next to each other in the route file. Stream anything a user reads. Return a response from every branch, including errors, and have the front end check res.ok before parsing. Decide early which work is a request and which is a background job, and keep the second kind out of route handlers. Before launch, test the slowest prompt you expect with the largest input on a preview deployment, not only locally, and watch the function duration in the logs. Set a log alert or check the logs weekly for requests that come within 20 percent of their limit.
FAQ
What causes FUNCTION_INVOCATION_TIMEOUT on Vercel?
The function ran longer than its maximum duration and Vercel stopped it. With AI routes the usual causes are a slow model call, the OpenAI client retrying a slow request, a handler that never returns a response on an error path, an Edge runtime route that did not start responding within 25 seconds, or an old project still on the lower limits without Fluid compute.
What is the Vercel function timeout limit in 2026?
With Fluid compute, which is on by default for new projects, the default and the maximum are 300 seconds on Hobby, and the default is 300 seconds with a maximum of 800 seconds on Pro and Enterprise. Projects without Fluid compute keep the older limits: 10 seconds by default and 60 at most on Hobby, 15 by default and 300 at most on Pro.
Why does my AI route work locally but time out on Vercel?
Locally there is no function limit, the dev server waits as long as the model takes. On Vercel the function has a fixed maximum, may run in a region far from your database, and the request may wait on retries you never see locally. Check the duration in the logs and set maxDuration and a client timeout.
Why do I get Unexpected token 'A', An error o... is not valid JSON?
When Vercel stops a function it returns a plain text error page that starts with An error occurred. Your front end calls res.json() on it and fails. The JSON error is a symptom; the real problem is the 504. Check res.ok before parsing, and fix the timeout.
Does streaming avoid the Vercel timeout?
Streaming gets the first words to the user quickly and is required on the Edge runtime, which must start the response within 25 seconds. It does not give the function unlimited time: the maximum duration still includes the time spent streaming.
Should I call OpenAI from the browser to avoid the timeout?
No. That puts your OpenAI API key in the JavaScript bundle where anyone can copy it and run up your bill. Keep the call on the server and fix the duration instead.
Related guides
- Supabase "canceling statement due to statement timeout": why queries die after 3 or 8 seconds
- Next.js environment variables undefined on Vercel: NEXT_PUBLIC_, redeploys and "supabaseUrl is required"
- Exposed API keys in a Vite / React bundle: why VITE_ variables are public and how to fix it
- Vercel 413 FUNCTION_PAYLOAD_TOO_LARGE on file uploads (and "Body exceeded 1 MB limit")
- Supabase "Edge Function returned a non-2xx status code": find the real error and fix it