skip to content

A Node.js 24 client's net.connect to localhost on a closed port fails with an AggregateError rather than one ECONNREFUSED; why, and how should retry and logging code read it?

level: seniorimportance: should knowfreq 30%

answer

  1. more than one address
  2. family autoselection by default
  3. an array of attempts
  4. whose code sits on top
  5. fs close failures too

basics

~20 s

Since Node 20, net.connect defaults to autoSelectFamily: true and tries every resolved address in turn. When all attempts fail it emits one AggregateError whose errors array holds each attempt, with the first attempt's code copied onto it.

solid answer

~40 s

`localhost` usually resolves to both `::1` and `127.0.0.1`. With `autoSelectFamily`, the default since Node 20.0.0, the socket looks up every address and tries them in sequence, giving each but the last 250 ms by default; if every attempt fails, it emits a single `AggregateError` holding all of them. Node copies the first attempt's `code` onto it and leaves its `message` empty, so `err.code === 'ECONNREFUSED'` still matches when every attempt was refused. Robust code reads `err.errors`: each entry is an ordinary system error with `code`, `address` and `port`, and entries can differ, such as `ETIMEDOUT` on IPv6 and `ECONNREFUSED` on IPv4. Logging should print the whole array, and retry logic should classify every entry. Global `fetch` surfaces the same error as its `err.cause`.

code

javascript · 14 lines
javascript
import net from 'node:net';

const socket = net.connect({ host: 'localhost', port: 59999 });
socket.on('error', (err) => {
  console.log(err.name, JSON.stringify(err.code), JSON.stringify(err.message));
  // AggregateError "ECONNREFUSED" ""
  for (const attempt of err.errors ?? [err]) {
    console.log(attempt.code, attempt.address, attempt.port);
  }
  // ECONNREFUSED ::1 59999
  // ECONNREFUSED 127.0.0.1 59999
  console.log(socket.autoSelectFamilyAttemptedAddresses);
  // [ '::1:59999', '127.0.0.1:59999' ]
});

go deeper

for a junior

Recall that an AggregateError carries an errors array, and that a Node connect to a host with several addresses can report one when every attempt fails.

for a middle

Explain family autoselection: lookup of all addresses, attempts in sequence with a 250 ms default per attempt, and one AggregateError when all of them fail.

for a senior

Show the diagnosis: the outer code copied from the first attempt, an empty message, mixed codes across families, and the same shape hidden inside fetch's cause.

for a principal

Decide whether classifiers and log serializers across services understand nested errors before anyone reaches for flags that disable autoselection.

## Where Node produces an AggregateError `AggregateError` is a standard JavaScript error that holds several errors in an **`errors` array**. The language uses it for `Promise.any`; Node's own APIs use it in a few places where **more than one thing failed at once**, and a classifier written for single errors misreads them. | Source | When | `code` on the outer error | Where the detail is | |---|---|---|---| | `net.connect` / `net.createConnection` with family autoselection | every resolved address failed | the first attempt's code | `err.errors`, one system error per attempt | | clients on `node:net`, such as global `fetch` | the same connect failure | on `fetch`, `undefined`: the `AggregateError` is `err.cause` | `err.cause.errors` | | `fs.readFile`, `fs.writeFile`, `fs.truncate` callbacks | the operation failed and closing the descriptor failed too | the operation's code | `err.errors`: operation error, then close error | The `fs` behaviour is in each method's history: "The error returned may be an `AggregateError` if more than one error is returned", added in v16.0.0. ## How family autoselection works `autoSelectFamily` is Node's loose implementation of section 5 of RFC 8305, often called Happy Eyeballs. Its default has been **`true` since v20.0.0** (and v18.18.0); `net.getDefaultAutoSelectFamily()` reports the current default. 1. The lookup runs with `all: true`, so every address comes back, for `localhost` typically `::1` and `127.0.0.1`. 2. The socket tries them **in sequence**, alternating families: first AAAA, first A, second AAAA, and so on. 3. Each attempt except the last gets `autoSelectFamilyAttemptTimeout` milliseconds, **250** by default, before the next starts. 4. If any attempt connects, earlier failures are not emitted. 5. If all fail, the socket emits **one** `AggregateError` with all the failed attempts. If attempts only timed out and no error was collected, it emits `ERR_SOCKET_CONNECTION_TIMEOUT` instead. Autoselection is skipped when `family` is `4` or `6`, or when `localAddress` is set. ## Reading it correctly - **The outer `code` is a shortcut, not the whole story.** Node sets it to the first attempt's code, so `err.code === 'ECONNREFUSED'` matches when every attempt was refused. When attempts fail differently, say `ETIMEDOUT` over IPv6 and `ECONNREFUSED` over IPv4, the outer code reports only the first. - **The outer `message` is empty** for the connect case, so a log line built from `err.message` alone says nothing. Print the error with `util.inspect` or iterate the array. - **Each entry is an ordinary system error** with `code`, `syscall`, `address` and `port`: classify every one, and treat the whole failure as retryable only if the entries justify it. - **`socket.autoSelectFamilyAttemptedAddresses`** lists what was tried as `address:port` strings, useful when the error has already been flattened. ## Retry logic on top of the array A retry classifier has to accept both shapes, because a host with a single address still produces a plain system error. Normalise first with `err.errors ?? [err]`, then decide on the set: - **Every entry `ECONNREFUSED`**: nothing is listening on any address; retry with backoff, as you would a single refusal. - **Every entry `ETIMEDOUT`**, or `ERR_SOCKET_CONNECTION_TIMEOUT`: the host is unreachable or overloaded; retry fewer times and alert sooner. - **Mixed codes**, such as `ETIMEDOUT` on `::1` and `ECONNREFUSED` on `127.0.0.1`: two problems at once, typically a server bound to only one family plus an address that cannot be reached. Log the whole array; the outer code alone would hide half of it. ## Turning it off, and why you usually should not You can disable autoselection with `--no-network-family-autoselection`, `net.setDefaultAutoSelectFamily(false)`, or per connection with `autoSelectFamily: false` or a fixed `family`. That restores single errors, but it also brings back the problem the feature solves: on a host whose IPv6 route is broken, a connection can wait on the unreachable address instead of falling back. The better fix is a classifier that understands the array. ## Mistakes to avoid - Logging only `err.message`, which is empty for the connect `AggregateError`. - Assuming `err.code` describes every attempt. - Reading the `fs` close error as the primary failure; the operation's error comes first. - Disabling autoselection fleet-wide to make logs look familiar.

  • When does fs.writeFile pass an AggregateError to its callback, and which error should you treat as primary?
    When the write, an `fsync` requested with `flush`, or an abort fails and closing the file descriptor then fails too. Node combines the two: the operation's error first in `errors`, the close error second, and the outer `code` and `message` taken from the operation's error. The operation's failure is the primary one; the close error is secondary.
  • Why not simply disable autoselection so errors look the way they used to?
    Because autoselection is what lets a connection fall back from a broken IPv6 route to IPv4 after 250 ms per attempt. Turning it off with `--no-network-family-autoselection` or `net.setDefaultAutoSelectFamily(false)` restores single errors but can leave connections waiting on an unreachable address. Fix the classifier to read `err.errors` instead.

  • An AggregateError from net.connect means many sockets were opened in parallel.
  • The outer err.code describes every attempt in the errors array.
  • Logging err.message is enough to see why the connect failed.
  • AggregateError comes only from Promise.any, never from Node's own APIs.
  • Disabling autoSelectFamily everywhere is the standard fix.

Assumes Node.js 24; autoSelectFamily has defaulted to true since v20.0.0 (and v18.18.0), which is why a connect to a multi-address host now fails with an AggregateError.