AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Socket Rewrites Connection Reuse Can Lead To A Race Condition And Intermittent 500S

Next.js 16.3.x uses httpxy for rewrites with a shared keep-alive agent, which can reuse an idle socket at the same moment the upstream closes it, causing a race condition that intermittently returns 500 on the second socket connection.

highConfidence 72%Next.jsAffected V16.3.0-Canary.98Affected V16.3.6

Origin Analysis

httpxy by default uses a shared keep-alive agent for proxy requests; when an upstream service closes an idle connection, the agent may still resurrect the socket for a new request, leading to an ECONNRESET/IPE and a 500 response.
1. Clone https://github.com/aleksi-abr/nextjs-external-rewrite-socket-reuse-repro; 2. Run `pnpm install`; 3. Run `pnpm upstream` to start mock upstream; 4. Run `pnpm dev` to start Next; 5. Run `pnpm probe` to make two socket connections; 6. Observe first connection returns 200, second returns 500.

Fixing Code Block

Edge Case Audit

Disabling keep-alive increases the per-request latency and connection establishment overhead, especially for high-throughput proxying. In multi-process/cluster deployments, ensure agent instances are created per worker to avoid cross-thread sharing issues; in serverless environments, module-level agents may keep connections from being properly released after function termination. If this patch is applied to a future Next.js version where the internal structure changes, it may conflict; rollback by reverting the agent changes and rebuilding. A more flexible solution would expose a configuration option (e.g., `experimental.proxyClientKeepAlive`) to allow users to choose the trade-off.

Ecosystem Topology