# Error: read ECONNRESET (Node.js)

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.

1. Log err.code, the target URL and req.reusedSocket for every failed outbound request.
2. Look up the upstream idle timeout (nginx keepalive_timeout, load balancer idle timeout).
3. Set the client keep-alive timeout a few seconds below that (undici keepAliveTimeout, agent settings).
4. Retry idempotent requests once on ECONNRESET with a short, jittered delay.
5. Attach an 'error' listener to raw sockets and streams so a reset can't crash the process.

```ts
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);
      }
    });
  });
}
```

## 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`

## Sources

- [Node.js errors: common system errors](https://nodejs.org/api/errors.html)
- [Node.js HTTP module (Agent, keepAliveTimeout, reusedSocket)](https://nodejs.org/api/http.html)

---

To see this error the next time it happens in production, with the stack trace and the steps before it: Runheed records it and serves it to your coding agent over MCP. Setup instructions an agent can follow: https://runheed.com/SETUP.txt

Human-readable version: https://runheed.com/errors/econnreset
