FULL AI ANALYSIS

Next.js serverless API on Vercel returns intermittent 504s for long upstream requests when HTTP keep-alive sockets are exhausted

Generated Oct 27, 2026, 9:31:39 AM

Analysis summary

Root cause is connection pool exhaustion between the serverless function pool and upstream. Serverless functions can be short-lived and high-concurrency; using persistent keep-alive without bounding sockets causes too many idle/half-closed connections, and upstream may reach its max connections or hold sockets in CLOSE_WAIT. Short-term fixes (Connection: close) work but kill benefits of keep-alive. The correct approach is to use a connection agent configured with sensible maxSockets, idle socket timeout, and proper socket reuse, or to use a streaming response/edge function model so connections are not blocked for long durations.

Possible causes

Unbounded HTTP keep-alive agents letting serverless frontends exhaust upstream connection pools under concurrent long requests

85%

Upstream reverse proxy misconfiguration (low max connections, improper reuse) causing sockets to accumulate in CLOSE_WAIT

60%

Vercel platform execution/connect timeout triggers before upstream completes under bursts, unrelated to socket pools

45%

DNS resolution delays or ephemeral network blips causing fetch to hang until platform timeout

20%

Suggested fixes

1

Diagnostic step 1

Instrument and capture socket stats on upstream and proxy (ss -s, netstat -an | grep -E 'CLOSE_WAIT|TIME_WAIT') during a burst to confirm pool exhaustion.

2

Diagnostic step 2

Configure an HTTP agent for node-fetch/undici with limited maxSockets (e.g., 50) and a keepAliveMsecs reasonable (e.g., 10000), share that agent across invocations where possible; test under load.

3

Diagnostic step 3

Use Connection: close only for pathological long requests as a temporary mitigation. Prefer bounding keep-alive instead.

4

Diagnostic step 4

Consider moving truly long-held requests to a backend job queue or use streaming/edge functions to reduce time serverless instances hold upstream connections.

5

Diagnostic step 5

If using a reverse proxy, increase its max connections and reduce TIME_WAIT/CLOSE_WAIT retention via proper keepalive and tcp_tw_reuse settings cautiously; monitor after change.