Skip to content

Node.js ECONNRESET behind ALB: Fixing Keep-Alive Mismatches

Intermittent 502 Bad Gateway and ECONNRESET behind AWS ALB or Nginx? Fix keep-alive race conditions by aligning server.keepAliveTimeout with headersTimeout.

Node.js ECONNRESET behind ALB: Fixing Keep-Alive Mismatches

You inspect your production error dashboard after a high-traffic deployment, and a sporadic trickle of HTTP 502 Bad Gateway errors appears. The failures occur at random intervals, affect fast endpoints, and leave behind no uncaught exception traces in your application logs.

In Node.js applications deployed behind reverse proxies like AWS Application Load Balancer (ALB), Nginx, or Cloudflare, sporadic 502 errors and ECONNRESET (socket hang up) failures stem from a keep-alive timeout race condition. When an upstream load balancer attempts to reuse an idle TCP socket at the exact millisecond the backend Node.js runtime closes it, the connection resets mid-flight.

Here is the immediate triage checklist to eliminate 502 keep-alive race conditions:

  1. Audit Load Balancer Idle Timeout: Check the connection idle timeout configured on your load balancer (AWS ALB defaults to 60 seconds; Nginx defaults to 65 or 75 seconds).
  2. Increase Node.js keepAliveTimeout: Set server.keepAliveTimeout = 65000 (65 seconds), guaranteeing that the backend socket outlives the load balancer’s 60-second idle window.
  3. Set headersTimeout Higher than keepAliveTimeout: In Node.js 18 and newer, configure server.headersTimeout = 66000 (66 seconds) to prevent HPE_HEADER_OVERFLOW and socket drop warnings.
  4. Configure Outbound Client Keep-Alive: When calling downstream internal microservices via fetch or undici, instantiate an explicit HTTP Agent pool with keep-alive enabled to eliminate outbound connection resets.

Illustrative AWS CloudWatch ALB access log entry capturing a keep-alive race failure:

https 2026-11-27T10:14:22.109281Z app/prod-alb/50dc6c495c0c9188 198.51.100.24:51204 10.0.4.12:3000 
-1 -1 -1 502 - 142 412 "POST /v1/checkout HTTP/1.1" 
"Mozilla/5.0" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 
arn:aws:elasticloadbalancing:... "Root=1-6746f32e-4b2a881902..." "-" "-" -1 
2026-11-27T10:14:22.049000Z "forward" "-" "-" "10.0.4.12:3000" "-" "-" "-"

Notice the timing values -1 -1 -1 and status 502. The ALB could not dispatch the request to the target because the underlying socket closed prematurely. Adhering to official Node.js HTTP Server Keep-Alive specifications and AWS ALB Connection Idle Timeout rules resolves the discrepancy.


Anatomy of the Race Condition: The 5-Second Default Trap

To understand why this error strikes production systems, we must analyze the lifecycle of an HTTP persistent connection (Keep-Alive).

Establishing a new TCP connection requires a three-way handshake (SYN -> SYN-ACK -> ACK), followed by a TLS cryptographic negotiation handshake. Under heavy traffic, creating a fresh TCP connection for every single HTTP request introduces massive latency and CPU overhead.

HTTP/1.1 Keep-Alive solves this by keeping the underlying TCP socket open across multiple consecutive requests.

+-------------------------------------------------------------------------+
|                  The Keep-Alive Timeout Race Condition                  |
|                                                                         |
| AWS ALB (Idle Timeout: 60s)               Node.js (keepAliveTimeout: 5s)|
| ---------------------------               ----------------------------- |
| Time: 0.0s  Request 1 arrives -----------> Processes and returns 200 OK |
|             Socket remains IDLE in pool                                 |
|                                                                         |
| Time: 5.0s  ALB believes socket is warm   Node.js timer fires! (5s idle)|
|             and ready for reuse...        Node.js sends TCP FIN packet! |
|                                                    |                    |
| Time: 5.001s ALB receives Request 2                |                    |
|              ALB sends HTTP data into socket ----> | (Packet in flight) |
|                                                    v                    |
|                                           Node.js kernel receives data  |
|                                           on a HALF-CLOSED socket!      |
|                                           Kernel replies with TCP RST!  |
|                                                    |                    |
| Time: 5.002s ALB receives TCP RST <----------------+                    |
|              ALB marks request failed: 502 Bad Gateway                  |
+-------------------------------------------------------------------------+

The Conflict in Default Values

The race condition is born out of incompatible default settings between cloud infrastructure and runtime defaults:

  • AWS Application Load Balancer: Defaults to an idle timeout of 60 seconds. The ALB holds an open TCP socket to the backend target for up to 60 seconds of inactivity before terminating it.
  • Node.js (HTTP Server): Historically and up through modern releases, server.keepAliveTimeout defaults to 5,000 milliseconds (5 seconds).

Now observe what occurs at second 5.0:

  1. The client finishes Request 1. The socket sits idle in the ALB’s backend connection pool.
  2. At the 5.000-second mark, Node.js decides the socket has been idle too long. Node.js initiates a clean TCP close by transmitting a FIN packet to the load balancer.
  3. At the exact same microsecond (second 5.001), a new user request arrives at the ALB. The ALB checks its pool, sees the open socket, and immediately writes the incoming HTTP request bytes into the connection.
  4. The ALB’s data packets cross paths on the physical network cable with Node.js’s FIN packet.
  5. The Linux kernel hosting Node.js receives incoming HTTP payload data on a socket that application space has already commanded to close.
  6. The kernel responds according to standard TCP specifications: it sends a TCP Reset (RST) packet back to the ALB.
  7. The ALB receives the RST, concludes that the backend application crashed or rejected the connection, and emits an immediate 502 Bad Gateway.

Because the request was dropped before reaching Node.js application space, your Express, Fastify, or NestJS application logs record zero errors.


The Node.js 18+ Prerequisite: headersTimeout

When developers discover this issue, their first instinct is to simply update server.keepAliveTimeout = 65000. In modern Node.js versions, doing so without adjusting server.headersTimeout introduces a secondary bug.

In Node.js 18, 20, and 22, the HTTP server includes server.headersTimeout. This parameter defines the maximum time the server allows for receiving complete HTTP request headers from the client.

Node.js enforces an internal invariant:

server.headersTimeout > server.keepAliveTimeout

If keepAliveTimeout is increased to 65 seconds while headersTimeout remains at its default (60 seconds), Node.js drops connections immediately or throws runtime warnings because the header timeout expires before the keep-alive window closes.

The golden rule for Node.js behind any load balancer is:

headersTimeout = keepAliveTimeout + 1000ms
keepAliveTimeout > LoadBalancerIdleTimeout

Production Remediation in Code

Here is how to configure HTTP servers correctly across Express, Fastify, NestJS, and native Node.js.

1. Express & Native HTTP Server

// server.ts (Express / Native Node.js)
import express from "express";
import http from "http";

const app = express();
const server = http.createServer(app);

// ALB connection idle timeout is 60 seconds.
// 1. Ensure backend socket outlives the load balancer (65 seconds)
server.keepAliveTimeout = 65000;

// 2. Ensure headersTimeout is strictly greater than keepAliveTimeout (66 seconds)
server.headersTimeout = 66000;

// 3. Optional: Configure maxRequestsPerSocket (Node 16.10+) to recycle long-lived sockets
server.maxRequestsPerSocket = 1000;

server.listen(3000, () => {
  console.log("Server listening on port 3000 with hardened keep-alive settings.");
});

2. NestJS Framework Configuration

In NestJS, extract the underlying HTTP adapter server instance after initialization:

// main.ts (NestJS)
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  
  const server = app.getHttpServer();
  // Align keep-alive with AWS ALB (65s and 66s)
  server.keepAliveTimeout = 65000;
  server.headersTimeout = 66000;

  await app.listen(3000);
}
bootstrap();

Hardening Nginx as a Reverse Proxy

If your architecture places Nginx between your public edge and Node.js backend services, Nginx’s keepalive_timeout must be calibrated with the exact same discipline.

# /etc/nginx/conf.d/upstream.conf

upstream node_backend {
    server 127.0.0.1:3000;
    
    # Maintain an active pool of 64 idle keep-alive connections
    keepalive 64;
}

server {
    listen 80;
    server_name api.example.internal;

    # Nginx closes idle client connections after 60 seconds
    keepalive_timeout 60s;

    location / {
        proxy_pass http://127.0.0.1:3000;
        
        # Mandatory: Enable HTTP/1.1 for upstream proxying (default is 1.0)
        proxy_http_version 1.1;
        
        # Clear the Connection header to allow persistent keep-alive upstream
        proxy_set_header Connection "";
        
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Important: By default, Nginx proxies upstream requests using HTTP/1.0, which sends Connection: close on every request. Setting proxy_http_version 1.1; and proxy_set_header Connection ""; is mandatory to enable persistent connection reuse between Nginx and Node.js. In this configuration, Node.js must set keepAliveTimeout to 65000 so it outlives Nginx’s 60s timeout.


Outbound HTTP Requests: Fixing ECONNRESET in Client Pools

A complementary failure mode occurs when your Node.js application issues outbound HTTP requests to internal microservices or third-party APIs using persistent sockets.

If the remote API closes its idle socket after 15 seconds, and your Node.js client attempts to reuse that socket at second 15.001, your application throws:

Error: read ECONNRESET
    at TLSWrap.onStreamRead (node:internal/js_stream_socket:190:27)
    errno: -104, code: 'ECONNRESET', syscall: 'read'

Remediation with Undici / Node.js native fetch

Node.js 18+ native fetch is powered by undici. Configure an explicit global dispatcher with conservative idle timeouts:

// outbound-client.ts
import { setGlobalDispatcher, Agent } from "undici";

// Configure outbound connection pooling
const dispatcher = new Agent({
  // Maximum idle time for an outbound socket before client actively closes it
  keepAliveTimeout: 10000, // 10 seconds (safely below remote server ceilings)
  // Maximum duration an outbound socket can be reused
  keepAliveMaxTimeout: 30000, // 30 seconds
  // Enable connection reuse
  pipelining: 1,
});

setGlobalDispatcher(dispatcher);

By ensuring that the sender of requests actively terminates idle sockets before the receiver does, you eliminate ECONNRESET across inter-service communication channels.


Verification: Reproducing the Race Condition

Because keep-alive collisions depend on millisecond timing, reproducing them manually with a browser or standard cURL command is virtually impossible.

To verify whether your configuration resolves the bug, use a specialized load-testing probe that deliberately pauses between requests to hit the idle boundary:

# Execute two sequential requests on a single reused persistent connection
# with an exact 60-second idle pause in between
curl -v --keepalive-time 120 \
  127.0.0.1:3000/health \
  --next \
  --sleep 60 \
  127.0.0.1:3000/health

If your server runs the default 5-second keepAliveTimeout, the second request fails with 502 Bad Gateway or Empty reply from server. With server.keepAliveTimeout = 65000, the second request succeeds with 200 OK across the existing TLS connection.


Comparison: Keep-Alive Timeouts Across Infrastructure Layers

The following table summarizes recommended timeout alignments across modern cloud stacks:

ComponentRoleRecommended TimeoutRequirement Relative to Upstream
Cloudflare CDNEdge Proxy100 secondsEdge tier
AWS Application Load BalancerLayer 7 Ingress60 secondsLower than backend target
Nginx Reverse ProxyHost Gateway60 secondsLower than backend target
Node.js keepAliveTimeoutApplication Runtime65 secondsMust be strictly greater than ALB
Node.js headersTimeoutApplication Runtime66 secondsMust be strictly greater than keepAlive
Node.js Outbound AgentClient Fetch Pool10 secondsMust be lower than remote server

Frequently Asked Questions

Why does this issue only happen under moderate traffic and disappear under heavy load?

Under saturated continuous load, connections are reused every few milliseconds and never sit idle long enough to cross the timeout boundary. The race condition occurs primarily during low to moderate traffic or when requests arrive in periodic bursts.

Does raising keepAliveTimeout consume more memory on the Node.js server?

An idle TCP socket in the Linux kernel consumes negligible memory (approximately 3KB for socket buffers). Holding sockets open for 65 seconds rather than 5 seconds creates minimal RAM footprint while eliminating CPU-intensive TLS re-handshakes.

What happens if headersTimeout is smaller than keepAliveTimeout?

Node.js throws an error upon startup or drops incoming connections after the keep-alive timeout expires, as the HTTP parser aborts connections when header evaluation windows are smaller than socket reuse windows.

Is it safe to retry requests that fail with ECONNRESET?

Yes, for idempotent HTTP methods (GET, PUT, DELETE, HEAD). If an idempotent request fails with ECONNRESET before response headers are received, client libraries can safely retry the request immediately over a fresh connection.


Written By

Elena Rostova

Product Strategy Lead

Product and operations lead dedicated to helping non-technical founders navigate technical scale and architectural decisions. Advises founders on technical debt triage, cloud unit economics, and rapid pre-launch risk evaluation.

Practice: Vexn • Focus: Founder Strategy, Operational Risk & Scale
Frequently Asked Questions
Why does AWS Application Load Balancer (ALB) return intermittent 502 Bad Gateway errors with Node.js?
AWS ALB defaults to a 60-second connection idle timeout, while Node.js defaults to a 5-second keepAliveTimeout. When the ALB transmits a reused HTTP request on a socket that Node.js has just initiated closing with a TCP FIN packet, the ALB receives a TCP RST and logs a 502 Bad Gateway.
What is the correct relationship between keepAliveTimeout and headersTimeout in Node.js?
In Node.js 18+, server.headersTimeout must always be set strictly greater than server.keepAliveTimeout. If keepAliveTimeout is set to 65 seconds, headersTimeout should be set to 66 seconds to prevent premature socket termination before header parsing completes.
What should server.keepAliveTimeout be set to behind an AWS ALB?
The Node.js server.keepAliveTimeout must be set to a duration greater than the load balancer's idle timeout. For an ALB configured with the default 60-second idle timeout, set keepAliveTimeout to 65000 milliseconds (65 seconds).
Why is ECONNRESET impossible to reproduce in local development environments?
Locally, browser clients connect directly to Node.js without an intermediate reverse proxy maintaining pooled persistent TCP connections. The race condition requires an upstream load balancer multiplexing concurrent requests over idle persistent sockets.
Need an Architectural Audit?

Have our team inspect your AI-generated codebase.

48-hour turnaround with direct pull requests fixing security and scale bottlenecks.

Request Audit