Debugging

ECONNRESET, ETIMEDOUT, ECONNREFUSED: what each means in your Node logs

Three error codes, three different parties that hung up, and the fix for each one in a Node API.

ECONNRESET, ETIMEDOUT, ECONNREFUSED: headline 'Three error codes, three different parties that hung up' with each code, its syscall and meaning, and the note that a stale keep-alive socket is the usual ECONNRESET cause in an API.
Error: read ECONNRESET
    at TCP.onStreamRead (node:internal/stream_base_commons)
  errno: -104,
  code: 'ECONNRESET',
  syscall: 'read'

That line says a socket was closed by the other end while Node was reading from it. It doesn’t say which socket. It could be your server’s connection to a client, or one of your outbound calls to a database, a payment API or a model provider. Three error codes tend to show up together in these incidents, and each one points at a different party.

ECONNREFUSED: nothing was listening

The Node.js errors docs define it as “No connection could be made because the target machine actively refused it.” The connection never opened, so no request was sent.

The usual causes in an API:

  • Wrong host or port. Inside a container, localhost is the container itself, not the database next to it.
  • The service you’re calling is restarting.
  • Your container started before its dependency was ready.

Fix the config first. For startup ordering, wait for the dependency’s health check or retry the connection with backoff. Because nothing was sent, ECONNREFUSED is the one code that’s always safe to retry.

ETIMEDOUT: no answer in time

The docs: “A connect or send request failed because the connected party did not properly respond after a period of time.” Common causes are a firewall that drops packets instead of rejecting them, a host that’s down, or an upstream so overloaded it stops answering.

Set an explicit timeout on every outbound call, so the wait is a number you picked:

js
const res = await fetch(url, { signal: AbortSignal.timeout(5_000) });

When that fires, fetch rejects with a TimeoutError (check err.name), not with an ETIMEDOUT code. Log both under the same field so one search finds them. There’s more on this in timeouts for fetch in Node.

ECONNRESET: the other side closed an open connection

The docs: “A connection was forcibly closed by a peer. This normally results from a loss of the connection on the remote socket due to a timeout or reboot.”

In a Node API the most common cause is a stale keep-alive socket. Your HTTP client keeps idle connections open to reuse them. If the upstream closes idle connections sooner than your client gives up on them, the upstream closes the socket while it sits in your pool, and the next request that picks it up fails. A Node server closes idle keep-alive connections after server.keepAliveTimeout, which is 5 seconds by default.

With the built-in fetch, the code sits on err.cause, under a generic TypeError: fetch failed, and a reset socket often shows up as UND_ERR_SOCKET (“other side closed”) rather than ECONNRESET. With node:http you get ECONNRESET or “socket hang up”.

The fix is to keep your client’s idle timeout below the server’s:

js
import { Agent, setGlobalDispatcher } from 'undici';

// The upstream drops idle connections after 5s, so drop ours after 4s.
setGlobalDispatcher(new Agent({ keepAliveTimeout: 4_000 }));

The same mismatch happens on the inbound side, between your load balancer and your Node server. That’s covered in Node.js server timeouts.

Inbound or outbound?

Check syscall first. connect means you were opening the connection, so it’s outbound. read and write can go either way, so look at the stack: frames in undici or node:_http_client mean an outbound call.

On the inbound side, a client that hangs up mid-request shows up in Express as request aborted with code ECONNABORTED when the body parser is still reading. The client left, so log it at info level.

Retry only what’s safe to repeat

An ECONNRESET on a POST can mean the upstream received the request, processed it, and then the connection died before you saw the response. Retrying a bare POST to a payment API is how a customer gets charged twice.

Retry ECONNRESET and timeouts only on idempotent calls: GET, PUT, DELETE, or a POST with an idempotency key. Cap the attempts, back off between them, and log each one:

js
const RETRYABLE = new Set(['ECONNRESET', 'ETIMEDOUT', 'ECONNREFUSED', 'UND_ERR_SOCKET', 'TimeoutError']);

async function callUpstream(url, { method = 'GET', idempotent = method === 'GET', ...init } = {}) {
  for (let attempt = 1; ; attempt++) {
    const started = performance.now();
    try {
      return await fetch(url, { method, ...init, signal: AbortSignal.timeout(5_000) });
    } catch (err) {
      const code = err.name === 'TimeoutError' ? 'TimeoutError' : (err.cause?.code ?? err.code);
      logger.warn({
        code, syscall: err.cause?.syscall, host: new URL(url).host, method, attempt,
        durationMs: Math.round(performance.now() - started),
      }, 'outbound call failed');
      const safe = code === 'ECONNREFUSED' || idempotent;
      if (!RETRYABLE.has(code) || !safe || attempt === 3) throw err;
      await new Promise((r) => setTimeout(r, 200 * 2 ** attempt));
    }
  }
}

We ran this on Node 22: a closed port retries three times as ECONNREFUSED, a server that never answers retries as TimeoutError, and a POST to a server that resets the socket fails once with UND_ERR_SOCKET and isn’t retried.

What to log on every outbound failure

  • code, taken from err.cause.code for fetch
  • syscall
  • host
  • method
  • attempt number
  • duration in milliseconds

With those six fields, a jump in resets on one host right after a deploy reads as a keep-alive mismatch in a single query, and a run of refusals at startup reads as a container that came up too early.

See what’s hitting your API: apitraffic.io

Keep reading