Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Node.js: read ECONNRESET on keep-alive sockets

ECONNRESET means the peer closed the socket first. Align keepAliveTimeout with load balancer idle limits, handle socket errors, and retry idempotent calls.

~5 min readNode.js
#nodejs#econnreset#keep-alive#networking
Bold white headline reading SOCKET RESET with a Node.js client crate cut off from a cyan server pipe on the right.

Introduction & Quick Summary

An HTTP client or an idle socket reports:

code
Error: read ECONNRESET at TLSWrap.onStreamRead (node:internal/stream_base_commons:217:20) { errno: -104, code: 'ECONNRESET', syscall: 'read' }

The peer closed the connection while your side was reading from it. Nothing is wrong with the request body or the URL: the socket died between the moment the client wrote and the moment it expected a response. ECONNRESET (errno -104, "connection reset by peer") is the kernel telling Node that the remote end sent a TCP reset instead of an orderly FIN.

Where it appears:

  • A keep-alive connection reused seconds after the server or load balancer decided to close it.
  • Behind an AWS ALB, GCP load balancer, or nginx with a 60-second idle timeout while Node keeps sockets for 5 seconds by default — or the reverse.
  • A proxy or TLS terminator that resets connections it considers too old.
  • A server that crashes or is redeployed while clients hold pooled sockets.
  • An axios, undici, or node-fetch call that surfaces socket hang up with the same cause.

Quick answer: make the idle timeouts line up so the client's pool discards sockets before the server does, retry only idempotent requests, and attach an error listener to long-lived sockets so a reset becomes a handled event instead of an uncaught exception.

Core Mechanics, Signatures & Reproducible Setup

HTTP/1.1 keep-alive means one TCP connection serves several requests. Both ends run an idle timer and both can close at any time. When the server's timer fires first, it sends FIN; a client that had just written a new request on that socket may see the request discarded or a reset, depending on where the packet lands relative to the FIN. That race is the entire bug class.

Reproduce it with a server that closes connections quickly:

js
// server.js -- node server.js import { createServer } from "node:http"; const server = createServer((req, res) => { res.end("ok"); }); server.keepAliveTimeout = 500; // close idle sockets after 0.5s server.headersTimeout = 1000; server.listen(3000, () => console.log("listening on 3000"));
js
// client.js -- node client.js import { Agent, request } from "node:http"; const agent = new Agent({ keepAlive: true, maxSockets: 1 }); const call = () => new Promise((resolve, reject) => { const req = request({ host: "127.0.0.1", port: 3000, path: "/", agent }, (res) => { res.resume(); res.on("end", resolve); }); req.on("error", reject); req.end(); }); await call(); // socket is now idle in the pool await new Promise((r) => setTimeout(r, 800)); // server closes it at 500ms await call(); // Error: read ECONNRESET

The second call fails because the pool handed out a socket the server had already closed. In production the same thing happens on a random request every few minutes, which is why the error looks intermittent.

The knobs that decide who closes first:

SettingDefaultWhere it is setEffect
server.keepAliveTimeout5000 msNode HTTP serveridle time before the server closes a keep-alive socket
server.headersTimeout60000 msNode HTTP servertime allowed to receive complete headers
server.requestTimeout300000 msNode HTTP servertotal time to receive the request
http.globalAgent.keepAlivetrue since Node 19Node clientpooling on by default
Agent({ timeout })noneNode clientsocket inactivity timeout
ALB idle timeout60 sload balancercloses idle connections regardless of Node

Key Comparison Table

Telling the socket errors apart decides the fix:

ErrorKernel meaningTypical causeFix direction
ECONNRESETpeer sent RSTidle timeout race, crash, proxy resetalign timeouts, retry, handle error
EPIPEwrite to closed socketwriting after the peer closedstop writing, check writableEnded
ETIMEDOUTno response in timefirewall silently dropping, dead hostraise timeout, fix network
ECONNREFUSEDRST on connectnothing listening on the portstart the service, fix the port
EHOSTUNREACHno routewrong subnet or interfacerouting config

Which layer is closing the socket, and what evidence proves it:

EvidenceLayerCheck
errors cluster at 60 s or 5 s intervalstimeout mismatchcompare keepAliveTimeout with the LB idle timeout
errors only after a deployserver restartgraceful shutdown and connection draining
errors only through the proxyproxyproxy keepalive_timeout, proxy_read_timeout
errors with large uploadsbody size limitsproxy client_max_body_size resetting early
errors on one route onlyhandlersynchronous crash inside the request

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. The 60-second rule behind a load balancer

Most managed load balancers close idle connections at 60 seconds. Node's default keepAliveTimeout is 5 seconds, so the balancer usually wins the race to keep connections alive and the client pool reuses a socket the balancer has just dropped. Set the server slightly above the balancer and the client slightly below the server:

js
import { createServer } from "node:http"; const server = createServer(app); server.keepAliveTimeout = 65_000; // ALB idle timeout is 60s server.headersTimeout = 66_000; // must exceed keepAliveTimeout server.listen(8080);

headersTimeout must be greater than keepAliveTimeout, otherwise Node closes a socket while headers are still arriving and the client sees a reset. Clients should then reuse sockets for less than 65 seconds, which the Agent does by default when timeout is unset but the OS and the pool prune idle sockets.

2. Node 19 turned keep-alive on by default

Before Node 19, http.globalAgent used keepAlive: false, so every request opened a new socket and timeouts never mattered. From Node 19 onward keepAlive: true is the default, and workloads using raw http.request or older libraries began reporting resets after a runtime upgrade with no code change. Two sane responses:

js
import { Agent, setGlobalDispatcher } from "undici"; // explicit pool limits for fetch-based code setGlobalDispatcher(new Agent({ keepAliveTimeout: 10_000, keepAliveMaxTimeout: 60_000, connections: 50 }));

or disable pooling where a fresh socket per request is acceptable: new http.Agent({ keepAlive: false }). The point is to choose, rather than inherit a default that changed under you.

3. Retry only what is safe to retry

A reset does not mean the request was not processed. For GET, HEAD, PUT, and DELETE, a retry is idempotent; for POST it can duplicate an order or a payment. Retry on the error code, not on the message, and cap the attempts:

js
async function retrying(url, init = {}, attempts = 3) { for (let i = 0; i < attempts; i++) { try { return await fetch(url, init); } catch (error) { const code = error?.cause?.code; const retryable = code === "ECONNRESET" || code === "EPIPE"; if (!retryable || i === attempts - 1) throw error; await new Promise((r) => setTimeout(r, 100 * 2 ** i)); } } }

Never retry a request whose body was a stream that has already been consumed: the second attempt sends an empty body. Buffer the body or rebuild the stream before retrying.

4. Servers must handle the reset on their own sockets

The client sees the reset; the server sees req.on("aborted"), a clientError event, or an error on the socket. Without listeners, Node throws an uncaught exception and the process exits:

js
import { createServer } from "node:http"; const server = createServer((req, res) => { req.on("aborted", () => { console.warn("client aborted", req.method, req.url); }); res.on("error", (error) => { if (error.code !== "ECONNRESET") throw error; }); // ... }); server.on("clientError", (error, socket) => { if (error.code === "ECONNRESET" || !socket.writable) return socket.destroy(); socket.end("HTTP/1.1 400 Bad Request\r\n\r\n"); });

clientError fires for malformed requests and for resets on a socket that never produced a request, which is where a process most often dies unexpectedly.

5. Confirm where the socket died

Before changing timeouts, prove which hop closed the connection. ss -tanp shows sockets in CLOSE-WAIT (peer closed, app has not read the FIN) and FIN-WAIT-2 (local side closed, waiting on the peer), and curl -v prints Connection #0 to host left intact when the server keeps the socket. A reset appears as Recv failure: Connection reset by peer, which pins the failure to the network path rather than to application logic.

curl -sv https://api.example.com/health -o /dev/null ss -tanp | grep ':443' | head

Common Compilation/Runtime Mistakes & Version Gotchas

Catching the error without the code. Returning null from try/catch hides the difference between a timeout, a refusal, and a reset. Log error.code or error.cause.code with the URL and attempt number.

Version differences worth knowing. Node 18 and earlier default keepAlive: false; Node 19 and later default to true, and Node 20 raised the default connections behaviour in undici pools. Node 18 also entered end-of-life in April 2025, so libraries installed today assume a newer undici: keepAliveTimeout on fetch and UND_ERR_SOCKET handling differ between the Node 18 and Node 22 lines. Pin the runtime and the HTTP library together, and check node -p "process.versions.undici" when the error objects look unfamiliar.

Verifying upstream behaviour. Send the request with cURL using -v to see whether the server advertises Connection: keep-alive and how long it holds the socket, and confirm the expected response code with the HTTP status reference before blaming the client.

Reference material: Node.js server.keepAliveTimeout and Node.js common system errors.

Official references

primary documentation

The Node.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.