Next.js serverless API on Vercel returns intermittent 504s for long upstream requests when HTTP keep-alive sockets are exhausted
Environment
Next.js 13 API routes deployed as serverless functions on Vercel (Platform timeout ~60s), backend microservice hosted on internal cluster behind an HTTP reverse proxy (keep-alive enabled), upstream service uses Node.js with HTTP/1.1 keep-alive; client code uses node-fetch in Next.js functions.
Symptoms
Occasional long-running API calls (30–55s) return HTTP 504 from Vercel while quick requests succeed. Logs show Vercel returned timeout without upstream response. Reproducible when many concurrent long requests run; fewer concurrent clients succeed.
Observations
Upstream reports many sockets in CLOSE_WAIT and TIME_WAIT; proxy's connection pool reaches max open connections. The Next.js function uses a shared HTTP agent with keepAlive: true but without limit on maxSockets, or in some deployments uses the default global agent which reuses sockets. Increasing the Vercel function timeout did not eliminate 504s. When instrumenting upstream with a 'Connection: close' response, the 504 rate drops.
Already attempted
Tried increasing function timeout and concurrency on upstream; configured fetch to set 'Connection: close' header (reduced 504s). Replaced global agent with a new agent per request (fixed but increased CPU). Implemented upstream keep-alive timeout reductions — helped but didn't fully eliminate failures under peak concurrency.
Question
How can I prevent intermittent 504 errors for long-running requests from Next.js serverless functions without disabling keep-alive entirely or dramatically increasing resource usage?
Verified community troubleshooting
No answers yet..
Incident analysis
Most likely causes
Summary
Suggested Fixes
Continue troubleshooting
Related troubles
Matched from the title, description and tags
- Web Development33% match
Next.js serverless API returns 502 for large Transfer-Encoding: chunked uploads only when behind NGINX reverse proxy
Open0 answers - Web Development29% match
Nginx returns 504 Gateway Timeout only for backend requests over ~45s to my Node API
Open1 answer - Web Development29% match
NGINX HTTP/2 proxy drops chunked Transfer-Encoding uploads to Next.js API routes — request body never reaches Node
Solved1 answer - Web Development28% match
NGINX returns 504 Gateway Timeout for long-running uploads through a Node backend — how to diagnose?
Open1 answer - Web Development27% match
Next.js API behind Vercel Edge intermittently returns 403 due to cached edge responses dropping Cookie headers
Open0 answers