Vercel: FUNCTION_INVOCATION_TIMEOUT / 504 on AI requests
504: GATEWAY_TIMEOUT Code: FUNCTION_INVOCATION_TIMEOUT
In short: Your serverless function ran longer than its maximum duration, which is common when waiting for a long LLM response.
Why it happens
Serverless functions have a max duration set by your plan and config. Waiting for a full non-streamed LLM completion, slow database queries, or chained API calls can exceed it, especially on cold starts.
How to fix it
- Stream LLM responses to the client instead of waiting for the full completion.
- Raise the function's max duration within your plan's limit (in Next.js:
export const maxDuration = 60;in the route; check Vercel's current docs for your plan's ceiling). - Move long jobs to a background queue or cron and poll for the result.
- Add timing logs to find which step is slow.
Copy-paste fix prompt
I'm getting this error in my app: 504: GATEWAY_TIMEOUT Code: FUNCTION_INVOCATION_TIMEOUT [Paste the full error, stack trace, and the file it points to here] Likely cause: Your serverless function ran longer than its maximum duration, which is common when waiting for a long LLM response. Task: Find the slow server route, add timing logs, switch the LLM call to streaming, and set an appropriate maxDuration. Suggest a background job if it would still be too slow. Rules: - First explain the root cause in 2 sentences and list the files you'll change. - Make the smallest change that fixes it. Don't refactor unrelated code. - Don't disable security or checks (RLS, auth, signature verification, type checking, CORS allow-all) to make the error disappear. - Never print or hard-code secret keys. - Finish by telling me exactly how to verify the fix.
Common with: v0, Cursor, Bolt. Last reviewed 2026-11-13.