Skip to main content
Back to Community & Earn Hub

Vercel Serverless Functions + MCP Streamable HTTP: How to prevent 504 FUNCTION_INVOCATION_TIMEOUT on multi-step agent tool calls?

@pooja_nair4 days ago 1536 views

We deployed our Next.js App Router agent backend on Vercel (Pro plan), orchestrating multi-step tool calls against remote MCP Streamable HTTP servers.

The 504 Crash

For 1–2 tool calls (~12s), everything works. When a user triggers a deep research or multi-file audit workflow requiring 6 sequential tool iterations (~75 seconds total):

  • Vercel terminates the serverless function at the hard timeout ceiling with 504: GATEWAY_TIMEOUT (FUNCTION_INVOCATION_TIMEOUT).
  • Even worse, the client UI just shows a generic network error while the half-finished MCP run vanishes with no partial state saved!

How do teams run multi-minute autonomous agent loops on serverless stacks without hitting 504 walls?

1 Answers

Community Answers

@ishaan_malhotra Accepted Answer4 days ago

You cannot safely run unbounded multi-minute agent loops inside a synchronous HTTP request on serverless platforms—even with Fluid Compute (maxDuration = 300 / 800), a client mobile network drop or 5-minute ceiling still risks losing state.

The production pattern is 202 Asynchronous Job Handoff + Redis Stream / SSE Subscription:


1. Immediate 202 Accepted Enqueue on Vercel (<50ms)

In your Next.js POST /api/agent/run route, do not run the LLM loop inline. Generate a runId, push the job to an external durable queue (Upstash QStash, Trigger.dev, Inngest, or a dedicated FastAPI worker on Railway/Fly.io), and return { runId } immediately:

ts
// app/api/agent/run/route.ts (returns in <40ms, zero 504s!)
import { NextResponse } from "next/server";
import { Client } from "@upstash/qstash";

const qstash = new Client({ token: process.env.QSTASH_TOKEN! });

export async function POST(req: Request) {
  const { prompt, userId } = await req.json();
  const runId = crypto.randomUUID();

  // Hand off to long-running worker (Railway/Fly/Trigger.dev with no 60s cap)
  await qstash.publishJSON({
    url: `${process.env.AGENT_WORKER_URL}/jobs/execute`,
    body: { runId, prompt, userId },
  });

  return NextResponse.json({ runId }, { status: 202 });
}

2. Stream Live Progress via Redis Pub/Sub (GET /api/agent/stream?runId=...)

  1. The long-running worker publishes each MCP tool step and token delta to a Redis Stream (agent:run:{runId}).
  2. Your frontend subscribes to a lightweight SSE endpoint (or polls /status?runId=...) that reads from Redis with Last-Event-ID.
  3. Even if the user refreshes the tab or Vercel recycles the SSE connection at 60s, the browser EventSource reconnects automatically and replays missed steps from Redis without ever interrupting the worker!

(Quick interim band-aid if you just need 3–5 minutes on Vercel Pro: enable Fluid Compute in vercel.json and export export const maxDuration = 300; in your route.ts, plus send SSE : keepalive chunks every 10s.)

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.