← Back to Node.js, page 10

nodejs-0182 · Medium mid

What causes ECONNRESET and 'socket hang up' in Node.js HTTP clients, and how do you handle them safely, including keep-alive races?

ECONNRESET means the other side closed or reset the TCP connection while you were using it. Common causes: the server crashed or restarted, a proxy or load balancer idle timeout closed a keep-alive connection that the client then reused, or the server destroyed the socket. Handle it by keeping server keep-alive timeouts longer than proxy idle timeouts, retrying only idempotent requests with backoff, and using timeouts and a limited agent pool.

Full answer

What it means

  • 'socket hang up' with code ECONNRESET: the connection ended before a full response arrived. The peer sent a TCP reset or closed the socket.

Common causes

  • Keep-alive race: the client reuses an idle pooled connection at the same moment the server (or a load balancer) closes it. The request is lost. Fix by making the idle timeout of the server larger than that of the proxy in front of it (for example server.keepAliveTimeout above the load balancer timeout), and the client idle timeout smaller than the server one.
  • The server process crashed, restarted during a deploy, or ran out of memory.
  • A proxy, firewall or NAT dropped long idle connections.
  • The server destroyed the socket on purpose (request too large, protocol error, rate limiting).
  • A client abort. Check whether you aborted the request yourself.

Handling

  • Always attach an error handler, set request timeouts (AbortSignal.timeout), and use an Agent with keepAlive and a maximum number of sockets.
  • Retry only when it is safe: GET, HEAD, PUT and DELETE are idempotent by definition. A POST that reset may or may not have been processed, so retry it only with an idempotency key.
  • Use exponential backoff with jitter and a retry limit, and do not retry on every error code.
  • Graceful shutdown on the server (stop accepting, finish in-flight requests, then exit) prevents resets during deploys.
  • Log the code, syscall, target host and whether the connection was reused, to find patterns.
javascript
const http = require('node:http');

let resetsLeft = 0;
const server = http.createServer((req, res) => {
  if (resetsLeft > 0) { resetsLeft--; req.socket.destroy(); return; }       // the server drops the connection
  res.end(`${req.method} handled`);
}).listen(0, '127.0.0.1', main);

const agent = new http.Agent({ keepAlive: true, maxSockets: 4 });
const send = (method) => new Promise((resolve, reject) => {
  const req = http.request({ port: server.address().port, host: '127.0.0.1', method, agent, timeout: 2000 }, (res) => {
    let text = '';
    res.on('data', (c) => (text += c));
    res.on('end', () => resolve(text));
  });
  req.on('error', reject);
  req.end();
});

const IDEMPOTENT = new Set(['GET', 'HEAD', 'PUT', 'DELETE']);
async function sendWithRetry(method, attempts = 3) {
  for (let attempt = 1; ; attempt++) {
    try { return `${await send(method)} after ${attempt} attempt(s)`; }
    catch (err) {
      const retryable = err.code === 'ECONNRESET' && IDEMPOTENT.has(method) && attempt < attempts;
      if (!retryable) throw err;
      await new Promise((r) => setTimeout(r, 10 * 2 ** attempt));          // backoff (add jitter in real code)
    }
  }
}

async function main() {
  console.log('server.keepAliveTimeout default:', server.keepAliveTimeout, 'ms');

  resetsLeft = 1;
  await send('GET').catch((err) => console.log('1. plain GET     :', err.code, '-', err.message));

  resetsLeft = 1;
  console.log('2. GET with retry:', await sendWithRetry('GET'));

  resetsLeft = 1;
  await sendWithRetry('POST').catch((err) => console.log('3. POST          : not retried,', err.code));

  agent.destroy();
  server.close();
}

A server that destroys one socket makes the reset predictable. Real keep-alive races depend on timing and cannot be reproduced reliably in a short script, so that cause is described in the text only. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): server.keepAliveTimeout default: 5000 ms 1. plain GET : ECONNRESET - socket hang up 2. GET with retry: GET handled after 2 attempt(s) 3. POST : not retried, ECONNRESET

Key points

  • ECONNRESET means the peer closed or reset the connection.
  • Keep-alive reuse races with idle timeouts are a classic cause.
  • The server idle timeout should be longer than the proxy idle timeout.
  • Retry only idempotent requests, with backoff and a limit.
  • Graceful shutdown avoids resets during deploys.

Common mistakes

  • Retrying every failed POST and creating duplicate orders.
  • Retrying immediately in a tight loop with no backoff.
  • No timeouts, so a half-open socket waits for minutes.
  • A proxy idle timeout that is longer than the server keep-alive timeout.
  • Exiting the server process on deploy without draining requests.

Follow-ups

  • How does an idempotency key make a POST retry safe?
  • What is the difference between ECONNRESET and ECONNREFUSED?
  • How should keepAliveTimeout relate to a load balancer idle timeout?

Tips

  • Name the keep-alive race.
  • Say 'retry only when safe'.
  • Mention graceful shutdown.