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:
// 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=...)
- The long-running worker publishes each MCP tool step and token delta to a Redis Stream (
agent:run:{runId}).
- Your frontend subscribes to a lightweight SSE endpoint (or polls
/status?runId=...) that reads from Redis with Last-Event-ID.
- 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.)