Error: read ECONNRESET
Node.js · updated 2026-11-05
Shows up in production logs as a socket 'error' event or a rejected HTTP call, most often on outbound requests to APIs, databases and proxies. The peer tore down the TCP connection while Node was still reading from it.
Error: read ECONNRESET
at TLSWrap.onStreamRead (node:internal/stream_base_commons:218:20)
at TLSWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
errno: -104,
code: 'ECONNRESET',
syscall: 'read'
}Quick fix
Retry the request once when the socket came from the keep-alive pool, and set your client's keep-alive timeout lower than the upstream server's idle timeout. A frequent source is Node writing to a pooled socket the server already closed. Retry idempotent calls with backoff, and never blindly retry POSTs.
- Log err.code, the target URL and req.reusedSocket for every failed outbound request.
- Look up the upstream idle timeout (nginx keepalive_timeout, load balancer idle timeout).
- Set the client keep-alive timeout a few seconds below that (undici keepAliveTimeout, agent settings).
- Retry idempotent requests once on ECONNRESET with a short, jittered delay.
- Attach an 'error' listener to raw sockets and streams so a reset can't crash the process.
import http from 'node:http';
const agent = new http.Agent({ keepAlive: true });
function get(url: string, retried = false): Promise<string> {
return new Promise((resolve, reject) => {
const req = http.get(url, { agent }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => (body += chunk));
res.on('end', () => resolve(body));
res.on('error', reject);
});
req.on('error', (err: NodeJS.ErrnoException) => {
// The server closed an idle pooled socket just as we reused it: safe to retry a GET once.
if (!retried && req.reusedSocket && err.code === 'ECONNRESET') {
resolve(get(url, true));
} else {
reject(err);
}
});
});
}Paste this into Claude Code, Cursor or Codex in the project that throws it. The agent reads this guide in plain text and applies the fix that matches your stack.
Read https://runheed.com/errors/econnreset.md and fix this error in this project.Why it happens
Keep-alive socket reused after the server closed it
Node pulls an idle connection from the pool at the same moment the server's idle timer shuts it. The request goes out on a dead socket and the read fails. Node 19 turned keep-alive on for the default HTTP agent, and fetch (undici) pools connections too, so idle races are common.
Upstream restarted or crashed mid-request
A deploy, an OOM kill, a pod being rescheduled or a database failover drops every open connection. Requests in flight at that moment see a reset instead of a response. Errors that cluster around deploy times point here.
Load balancer or proxy timeout
Proxies cut connections that exceed their limits: AWS ALB defaults to a 60 second idle timeout, nginx proxy_read_timeout is 60 seconds by default. Slow endpoints, long polling and big uploads get cut off by the proxy, not by your app: usually a 504 if no response has started, a reset or truncated body if one has.
Your server's keepAliveTimeout is shorter than the balancer's
Node's http.Server closes idle connections after 5 seconds by default. A load balancer that keeps connections open longer will reuse one Node already closed, and the balancer logs resets or returns 502s. Set server.keepAliveTimeout above the balancer's idle timeout.
NAT gateway or firewall dropped an idle connection
Middleboxes forget idle TCP flows (the AWS NAT gateway drops them after 350 seconds). Pooled database or Redis connections sitting idle longer than that get reset on next use, typically the first query after a quiet period.
Other fixes
- Behind a load balancer, set server.keepAliveTimeout and server.headersTimeout higher than the balancer's idle timeout.
- For Postgres pools, set pg's keepAlive: true and an idleTimeoutMillis below any NAT or firewall idle limit.
- If resets cluster around deploys, drain traffic and call server.close() before the old process exits.
- Add error handlers on long-lived WebSocket and net.Socket connections so a reset is logged and reconnected.
Same error, other wording
- Error: socket hang up (code: 'ECONNRESET')
- Error: read ECONNRESET at TCP.onStreamRead
- TypeError: fetch failed [cause]: SocketError: other side closed
Let your coding agent catch the next one
Runheed records this error in production with the stack trace, the breadcrumbs before it and, when you set it, the agent session that shipped the code, and serves it to Claude Code, Cursor or any MCP client. With it connected, you can ask:
> Find the latest ECONNRESET errors in production, trace each stack to the outbound call that made it, and add a single retry with backoff for idempotent requests to that host.
Setup for Node.js and Express or Vercel Functions, then have your agent fix and resolve it.
Related errors
- TypeError: fetch failed
- Error: connect ECONNREFUSED 127.0.0.1:5432
- [UnhandledPromiseRejection: This error originated either by throwing inside of an async...
More in Network and HTTP
- Error: connect ETIMEDOUT 10.0.4.12:5432Node.js
- Error: self-signed certificate in certificate chainNode.js
- Error: getaddrinfo ENOTFOUND api.example.comNode.js
- Error: write EPIPENode.js
- Access to fetch at 'https://api.example.com/orders' from origin 'https://app.example.com'...Node.js
- AxiosError: Request failed with status code 401Node.js
- FunctionsHttpError: Edge Function returned a non-2xx status codeSupabase
- requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.example.com'...Python
- httpx.ReadTimeout: The read operation timed outPython
- ConnectionResetError: [Errno 104] Connection reset by peerPython
- BrokenPipeError: [Errno 32] Broken pipePython
- [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer...Python
- Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the clientNode.js
- 422 Unprocessable Entity: {"detail":[{"type":"missing","loc":["body","email"],"msg":"Field...Python
- No signatures found matching the expected signature for payload. Are you passing the raw...Node.js
- TokenExpiredError: jwt expiredNode.js
- Error: 429 You exceeded your current quota, please check your plan and billing details.Node.js
Other error topics
- PrismaClientInitializationError: Can't reach database server at `db.example.com:5432`Databases
- error: relation "todo" does not existDatabases
- sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due...Databases
- TypeError: 'module' object is not callableImports and modules
- Error: Cannot find module 'x'Imports and modules
- ImportError: cannot import name 'x' from partially initialized module 'y' (most likely...Imports and modules
- Element type is invalid: expected a string (for built-in components) or a class/function...React and Next.js rendering
- ReferenceError: window is not definedReact and Next.js rendering
- TypeError: Failed to parse URL from /api/ordersReact and Next.js rendering
- System.InvalidOperationException: Sequence contains no elementsUndefined, None and type errors
- TypeError: Client is not a constructorUndefined, None and type errors
- TypeError: unsupported operand type(s) for +: 'int' and 'str'Undefined, None and type errors
- SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSONJSON, parsing and validation
- ZodError: [ { "expected": "string", "code": "invalid_type", "path": [ "email" ]...JSON, parsing and validation
- TypeError: Object of type datetime is not JSON serializableJSON, parsing and validation
- Error: EACCES: permission denied, open '/app/data/cache.json'Memory, async and the process
- FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memoryMemory, async and the process
- OSError: [Errno 98] Address already in useMemory, async and the process
- Error executing tool get_orderMCP servers and clients
- McpError: MCP error -32001: Request timed outMCP servers and clients
- Bad Request: No valid session ID providedMCP servers and clients
Free tools: Source map stack trace decoder · Uptime and SLA downtime calculator · Error budget calculator · Stack trace formatter · JSON log viewer · HTTP status code reference.
References: Node.js errors: common system errors, Node.js HTTP module (Agent, keepAliveTimeout, reusedSocket)
Spotted a mistake? Email hello@greatwork.company. About Runheed.