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.

Introduction & Quick Summary
An HTTP client or an idle socket reports:
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, ornode-fetchcall that surfacessocket hang upwith 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:
// 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"));// 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 ECONNRESETThe 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:
| Setting | Default | Where it is set | Effect |
|---|---|---|---|
server.keepAliveTimeout | 5000 ms | Node HTTP server | idle time before the server closes a keep-alive socket |
server.headersTimeout | 60000 ms | Node HTTP server | time allowed to receive complete headers |
server.requestTimeout | 300000 ms | Node HTTP server | total time to receive the request |
http.globalAgent.keepAlive | true since Node 19 | Node client | pooling on by default |
Agent({ timeout }) | none | Node client | socket inactivity timeout |
| ALB idle timeout | 60 s | load balancer | closes idle connections regardless of Node |
Key Comparison Table
Telling the socket errors apart decides the fix:
| Error | Kernel meaning | Typical cause | Fix direction |
|---|---|---|---|
ECONNRESET | peer sent RST | idle timeout race, crash, proxy reset | align timeouts, retry, handle error |
EPIPE | write to closed socket | writing after the peer closed | stop writing, check writableEnded |
ETIMEDOUT | no response in time | firewall silently dropping, dead host | raise timeout, fix network |
ECONNREFUSED | RST on connect | nothing listening on the port | start the service, fix the port |
EHOSTUNREACH | no route | wrong subnet or interface | routing config |
Which layer is closing the socket, and what evidence proves it:
| Evidence | Layer | Check |
|---|---|---|
| errors cluster at 60 s or 5 s intervals | timeout mismatch | compare keepAliveTimeout with the LB idle timeout |
| errors only after a deploy | server restart | graceful shutdown and connection draining |
| errors only through the proxy | proxy | proxy keepalive_timeout, proxy_read_timeout |
| errors with large uploads | body size limits | proxy client_max_body_size resetting early |
| errors on one route only | handler | synchronous 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:
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:
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:
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:
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' | headCommon 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 documentationThe Node.js documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesNode.js: ERR_DLOPEN_FAILED invalid ELF header
Invalid ELF header means a native addon was built for another OS or architecture. Rebuild it inside the target image instead of copying node_modules.
Node.js ERR_INVALID_ARG_TYPE: the argument must be of type
ERR_INVALID_ARG_TYPE is Node's validator naming a wrong argument. Read the quoted argument, validate at the boundary and default env values.
ERR_MODULE_NOT_FOUND: Cannot find module imported from an ESM file
ESM resolves specifiers literally: extensions are required, directories do not resolve to index files, and exports maps block deep imports.
Node.js 26 upgrade: rmdir, native addons and removed flags
Three breaks stop a deploy: rmdir with recursive throws, the transform-types flag is gone, and the module ABI moved to 147.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.