skip to content

In Node.js, why can slow name resolution stall unrelated fs and crypto calls, and how do dns.lookup() and dns.resolve4() differ?

level: seniorimportance: must knowfreq 55%

answer

  1. two functions, two mechanisms
  2. getaddrinfo is a blocking call
  3. a shared pool of four threads
  4. network queries skip /etc/hosts
  5. custom lookup on connect

basics

~20 s

dns.lookup() runs the OS resolver getaddrinfo(3) on libuv's threadpool, shared with fs, crypto and zlib, so slow lookups queue that work. dns.resolve4() sends DNS queries over the network asynchronously, never uses the threadpool, and ignores /etc/hosts.

solid answer

~40 s

`dns.lookup()` is the default resolver behind `net.connect()`, `http.request()` and `dgram` sends to a host name. It wraps the operating system's `getaddrinfo(3)`, a blocking call, so Node runs it on libuv's threadpool: the same pool, four threads unless `UV_THREADPOOL_SIZE` says otherwise, that serves async `fs`, `crypto.pbkdf2()`, `crypto.scrypt()` and `zlib`. When the resolver is slow, a handful of outbound connections occupy every thread and file reads and password hashing wait behind them, while the event loop itself looks idle. `dns.resolve4()` and the other `dns.resolve*()` functions send DNS queries on the network asynchronously and never touch the threadpool, but they skip `/etc/hosts` and the OS name-service configuration, and `dns.setServers()` affects only them. Fixes: reuse connections, cache addresses, pass a custom `lookup` function to the connecting API, or raise the pool size at startup.

code

javascript · 30 lines
javascript
import net from 'node:net';
import dns from 'node:dns';

const cache = new Map();

function cachedLookup(hostname, options, callback) {
  const reply = (address) => (options.all
    ? callback(null, [{ address, family: 4 }])
    : callback(null, address, 4));

  const hit = cache.get(hostname);
  if (hit && hit.expires > Date.now()) {
    process.nextTick(reply, hit.address);
    return;
  }
  dns.resolve4(hostname, { ttl: true }, (err, records) => {
    if (err) return callback(err);
    const [{ address, ttl }] = records;
    cache.set(hostname, { address, expires: Date.now() + ttl * 1000 });
    reply(address);
  });
}

const socket = net.connect({
  host: 'collector.example.com',
  port: 7070,
  family: 4,
  lookup: cachedLookup,
});
socket.on('error', (err) => console.error(err.code));

go deeper

for a junior

Recall that Node has two ways to resolve a name: dns.lookup() asks the operating system, dns.resolve4() asks DNS servers directly.

for a middle

Explain why dns.lookup() runs on libuv's threadpool, which other APIs share that pool, and which configuration each function honours or ignores.

for a senior

Diagnose the stall from slow fs and crypto callbacks with a healthy event loop, then pick a fix: connection reuse, a cached custom lookup, or a larger pool set at startup.

for a principal

Weigh resolving through the OS against resolving in-process for a whole fleet: consistency with host configuration versus threadpool isolation, and who owns DNS caching.

## Two functions, two mechanisms The `node:dns` module offers two families of name resolution that look alike and behave very differently. | | `dns.lookup()` | `dns.resolve4()`, `dns.resolve*()`, `dns.reverse()` | |---|---|---| | How it resolves | Calls the operating system's `getaddrinfo(3)` | Sends DNS queries to DNS servers on the network | | Where it runs | libuv's **threadpool**, as a blocking call | Asynchronously on the network, **no threadpool** | | Reads `/etc/hosts` and OS name-service config | Yes, like `ping` and other programs on the host | No | | Affected by `dns.setServers()` | No | Yes | | Used by default by | `net.connect()`, `http.request()`, `dgram` `send()` to a host name | Only code that calls it | `dns.lookup()` resolves names the way the rest of the machine does, which is why Node uses it by default. The price is that `getaddrinfo(3)` is a synchronous system call, so Node can only make it asynchronous by running it on a worker thread. ## How a slow resolver stalls unrelated work libuv's threadpool has a fixed size, **4 threads by default**, and it serves every async `fs` call (except the file watchers), the async crypto functions such as `crypto.pbkdf2()`, `crypto.scrypt()` and `crypto.randomBytes()`, all async `zlib` work, and `dns.lookup()`. The stall unfolds like this: 1. The DNS server behind the host's resolver starts answering slowly, or a name times out. 2. Every new outbound connection to a host name queues a `dns.lookup()` on the pool. 3. Four slow lookups occupy all four threads. 4. A `fs.promises.readFile()` or a password hash queues behind them and waits for a thread. 5. Request latency climbs for endpoints that never touch the network. How the threadpool is scheduled and sized is covered with the event loop's phases; what matters here is that `dns.lookup()` is one of its customers. ## Diagnosing it - **Event-loop delay looks healthy.** The JavaScript thread is idle while work waits in the pool, so loop-delay metrics stay low even as callbacks slow down. - **Unrelated latency correlates with outbound connection churn**, for example a client that opens a new connection per request instead of reusing them. - **Errors are coarse.** `dns.lookup()` reports `ENOTFOUND` not only for names that do not exist but also for other failures, such as running out of file descriptors. - **Node keeps no cache of its own.** Every `dns.lookup()` asks the operating system again; any caching depends on how the host's resolver is set up. ## Fixes and their costs - **Make fewer lookups.** Reusing connections with a keep-alive agent removes most of them; the HTTP client material covers agents. - **Cache addresses.** The connecting APIs accept a `lookup` option (`net.connect()`, `http.request()`, `dgram.createSocket()`), so you can supply a function that serves cached results. `dns.resolve4(hostname, { ttl: true }, ...)` returns each record's TTL in seconds, which tells the cache when to refresh. - **Use `dns.resolve*()` for names that live in DNS.** It never occupies a pool thread, but it ignores `/etc/hosts` and the OS resolver configuration, so names defined only there stop resolving. - **Raise `UV_THREADPOOL_SIZE`.** It must be set in the environment before the process starts; setting `process.env.UV_THREADPOOL_SIZE` from code is not guaranteed to work because the pool is created during startup. More threads add headroom but still block on a slow resolver. - **Use a dedicated `dns.Resolver`** when one subsystem needs its own servers: `new Resolver({ timeout, tries })` with `resolver.setServers()` does not change other resolvers. ## Details that bite - `dns.lookup()` returns addresses in the order the resolver gave them (`order: 'verbatim'` is the default); `dns.setDefaultResultOrder()` or `--dns-result-order` changes that. - `dns.setServers()` must not be called while a query is in progress, and it never changes `dns.lookup()`. - Passing an IP literal skips resolution entirely in `dgram` and avoids the lookup cost wherever an address is accepted. - `net.connect()` enables `autoSelectFamily` by default: it calls the lookup function with `all: true` and tries the returned IPv6 and IPv4 addresses in turn, 250 ms per attempt by default. A custom `lookup` must therefore answer with an array of `{ address, family }` objects when `options.all` is set. - With `all: true`, `dns.lookup()` itself returns every address it found, which is what a connection-level cache usually wants to store.

  • Why doesn't event-loop delay reveal a saturated threadpool?
    Because the main thread is not busy. The JavaScript thread hands lookups, file reads and hashing to libuv's threadpool and sits idle while they wait in its queue, so event-loop delay stays low while the latency of `fs` and crypto callbacks climbs. Slow callbacks with a healthy loop point at the pool, not at blocking JavaScript.
  • Is raising UV_THREADPOOL_SIZE the right fix?
    It adds headroom but treats the symptom: extra threads still block on a slow resolver. It must be set in the environment before Node starts, since assigning `process.env.UV_THREADPOOL_SIZE` from code is not guaranteed to work once the pool exists. Cutting the number of lookups, by reusing connections or caching addresses, removes the cause.
  • When should a service keep dns.lookup()?
    When names must resolve exactly as they do for every other program on the host: entries in `/etc/hosts`, the OS name-service order, local resolver features. `dns.resolve*()` bypasses all of that and asks DNS servers directly, so switching to it can break names that exist only in local configuration.

  • dns.lookup() is asynchronous, so it cannot slow down anything else in the process.
  • dns.setServers() changes which servers dns.lookup() and http.request() use.
  • dns.resolve4() reads /etc/hosts first, just like the operating system resolver.
  • Node caches dns.lookup() results for each record's TTL.
  • An ENOTFOUND from dns.lookup() always means the host name does not exist.