Ömer Faruk YILDIRIM
tutorials

Node.js Production Failure Lab · part 4

Idle CPU, Fast Partner, Slow Checkout: DNS, the libuv Thread Pool and Keep-Alive in Node.js

The tax service answers in 30 ms and the API's CPU is idle, yet placing an order takes two seconds. We trace, step by step, how a new connection per request, dns.lookup and the libuv thread pool build an invisible queue.

28 min read90 min hands-oncode(opens in a new tab)

Node.js Production Failure Lab · Part 4 · Difficulty ★★☆ · Reading ~25 min · Lab ~45–90 min

In May 2023 the engineering blog of food-delivery company Wolt described an interesting bug hunt: latency on wolt.com’s Node.js servers showed sharp spikes at p99 and max, with no obvious pattern. Digging into the traces showed the spikes moved together with outliers in TCP connect and dns.lookup times. The team first tried a DNS cache, got ENOTFOUND errors in Kubernetes and rolled it back. The real improvement came from raising the libuv thread pool size (UV_THREADPOOL_SIZE) from 4 to 64 (Wolt, How we optimized wolt.com website latency by Node.js DNS resolution).

The moral of the story: “everything is asynchronous” is not quite true in Node.js. Behind JavaScript sits a small thread pool that runs the operating system’s blocking calls, and DNS resolution queues up in that pool. Even with an idle CPU and a fast remote service, your requests can sit in that queue for seconds.

In this article we’ll live through the same picture as a production incident. Yesterday a third-party tax service (TaxRate) was added to checkout. Since then placing an order takes a second or two, yet TaxRate’s dashboard says it answers quotes in ~30 ms, and the API’s CPU is idle. Unlike at Wolt, growing the pool here only buys time; the real question is why every order needs a DNS lookup at all.

In Part 3 a single orphaned promise killed the process; there were error waves, restarts and 502s. This time nothing crashes, nothing errors, no resource looks saturated. Things just wait.

What you’ll learn

  • The libuv thread pool: which Node.js APIs run there and why it defaults to 4 threads
  • Why dns.lookup() is a “synchronous call dressed up as asynchronous” and why at most 2 can run at once
  • The “working or waiting?” question: reading slowness when the CPU and event loop are idle
  • Measuring a dependency from both sides (client and server) and interpreting the gap
  • What GetAddrInfoReqWrap means in the Active libuv resources panel
  • HTTP keep-alive and connection pooling: the hidden cost of a new connection
  • The right fix for keep-alive-related ECONNRESET (not turning off connection reuse)

Prerequisites

You can read this article without the lab. These help:

TopicWhySource
Event loop and Worker PoolTo tell Node’s two kinds of threads apartDon’t Block the Event Loop (or the Worker Pool) (official guide)
dns.lookup vs dns.resolveThe theoretical core of this articleNode.js DNS: Implementation considerations
UV_THREADPOOL_SIZETo see which APIs share the poolNode.js CLI: UV_THREADPOOL_SIZE
http.Agent and keep-aliveTo see how connections are reusedNode.js HTTP: Class http.Agent
Earlier partsEdge vs in-service measurement, the event loop panelPart 1: Event loop blocking

1. Concept: the small pool behind the event loop

In Part 1 we saw that JavaScript runs on a single thread. But not everything Node.js does happens on that thread. Network sockets are truly asynchronous: the operating system says “data arrived” and nobody waits. Some work, however, has no asynchronous counterpart in the operating system. Node runs that work on libuv’s thread pool (called the Worker Pool in the official guide). According to the official docs, the pool is used by:

  • All fs APIs (except file watchers and the explicitly synchronous ones)
  • Asynchronous crypto calls such as crypto.pbkdf2(), crypto.scrypt(), crypto.randomBytes()
  • All of zlib (gzip compression included)
  • dns.lookup()

The pool has 4 threads by default (libuv: Thread pool work scheduling). Its size is set by the UV_THREADPOOL_SIZE environment variable when the process starts; changing it later from code is not guaranteed to work.

Why is dns.lookup() in the pool?

When you call http.request('http://api.taxrate.example/...'), Node first has to turn the host name into an IP address. By default it does this with dns.lookup(), which calls the operating system’s getaddrinfo(). That function knows about /etc/hosts, /etc/resolv.conf and all of the system’s resolver settings, but it is synchronous: it holds the calling thread until the answer arrives. Node’s docs say so plainly: it looks asynchronous from JavaScript, but it is a synchronous getaddrinfo call running on libuv’s pool, and it can have “surprising negative performance implications for some applications” (Node.js DNS: Implementation considerations).

There’s also a lesser-known detail. libuv does not want “slow I/O” work such as DNS to take over the whole pool and starve file and crypto work. So it gives slow work at most half the pool: (threads + 1) / 2, which with 4 threads means at most 2 concurrent DNS lookups (libuv source, slow_work_thread_threshold).

time ──────────────────────────────────────────────────────────►
pool (2 slots for DNS): [lookup 1: 0.5 s][lookup 3: 0.5 s][lookup 5: 0.5 s]
                        [lookup 2: 0.5 s][lookup 4: 0.5 s][lookup 6: 0.5 s]
order 5               ──┐ arrived  ...queued...          └─► got its address after 1.5 s

If the DNS server is slow (~0.5 s in this incident) and you need more than two lookups per second, lookups queue up. Meanwhile the CPU does nothing: everyone is waiting.

dns.resolve* functions such as dns.resolve4() are different: they don’t use getaddrinfo, they send the DNS packet over the network themselves (via c-ares) and never touch the pool. The price: they ignore /etc/hosts and the system’s resolver settings.

See it yourself: a 500 ms DNS server

A 40-line experiment is enough to see this on your own machine. The script starts a tiny DNS server on port 53 that answers every query after a 500 ms delay, then resolves 6 names at once: first with dns.lookup, then with dns.resolve4.

// slow-dns.mjs
import dgram from 'node:dgram';
import dns from 'node:dns';

// 1) Tiny DNS server (port 53) that answers 10.0.0.1 to every query after 500 ms
const server = dgram.createSocket('udp4');
server.on('message', (q, peer) => {
  let o = 12;
  while (q[o]) o += q[o] + 1;
  const type = q.readUInt16BE(o + 1);
  const question = q.subarray(12, o + 5);
  const header = Buffer.from(q.subarray(0, 12));
  header.writeUInt16BE(0x8180, 2);             // response, no error
  header.writeUInt16BE(type === 1 ? 1 : 0, 6); // 1 record for A, empty for AAAA
  header.writeUInt32BE(0, 8);
  const answer = Buffer.from([0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0, 30, 0, 4, 10, 0, 0, 1]);
  const reply = type === 1 ? Buffer.concat([header, question, answer]) : Buffer.concat([header, question]);
  setTimeout(() => server.send(reply, peer.port, peer.address), 500);
});
await new Promise((r) => server.bind(53, r));

// 2) 6 lookups at once: first dns.lookup (getaddrinfo, thread pool), then dns.resolve4 (c-ares, no pool)
async function run(label, fn) {
  const start = performance.now();
  const done = await Promise.all(
    Array.from({ length: 6 }, (_, i) =>
      new Promise((resolve) => fn(`api${i}.taxrate.example`, () => resolve(Math.round(performance.now() - start)))),
    ),
  );
  console.log(`${label.padEnd(14)} lookups finished at (ms): ${done.join(', ')}`);
}
console.log(`UV_THREADPOOL_SIZE=${process.env.UV_THREADPOOL_SIZE ?? '4 (default)'}`);
await run('dns.lookup', (h, cb) => dns.lookup(h, { family: 4 }, cb));
await run('dns.resolve4', (h, cb) => dns.resolve4(h, cb));
server.close();

To avoid messing with your system’s DNS settings, run the experiment in a container, with the container itself as its DNS server:

docker run --rm --dns 127.0.0.1 -v "$PWD":/demo node:24.22-trixie-slim node /demo/slow-dns.mjs
docker run --rm --dns 127.0.0.1 -e UV_THREADPOOL_SIZE=16 -v "$PWD":/demo node:24.22-trixie-slim node /demo/slow-dns.mjs

On my machine (Node.js 24, Debian-based image) the result is:

UV_THREADPOOL_SIZE=4 (default)
dns.lookup     lookups finished at (ms): 507, 507, 1009, 1009, 1512, 1512
dns.resolve4   lookups finished at (ms): 501, 501, 501, 501, 501, 501

UV_THREADPOOL_SIZE=16
dns.lookup     lookups finished at (ms): 508, 508, 508, 508, 508, 508
dns.resolve4   lookups finished at (ms): 503, 503, 503, 503, 503, 503

Notice three things:

  1. With the default pool, dns.lookup calls finish two at a time: 0.5 s, 1 s, 1.5 s. There are 4 threads, but only 2 are given to DNS. The sixth lookup waited 1.5 s even though its own work took 0.5 s.
  2. dns.resolve4 doesn’t use the pool, so all six finish together at 0.5 s.
  3. Raising the pool to 16 makes the queue disappear (8 slots for DNS), but every lookup still takes 0.5 s. A bigger pool removes the waiting; it doesn’t remove the cost of DNS itself.

So why does every request ask DNS?

Normally it doesn’t. If an HTTP client keeps the connection open and reuses it for later requests (keep-alive), the DNS lookup and the TCP handshake only happen when a new connection is needed. You can count this yourself too:

// reuse.mjs: 20 requests, two different agents; how many DNS lookups, how many TCP connections?
import http from 'node:http';
import dns from 'node:dns';

let connections = 0;
const server = http.createServer((req, res) => res.end('ok')).listen(3002);
server.on('connection', () => connections++);

let lookups = 0;
const countingLookup = (host, opts, cb) => { lookups++; dns.lookup(host, opts, cb); };

function get(agent) {
  return new Promise((resolve, reject) => {
    http.get('http://localhost:3002/', { agent, lookup: countingLookup }, (res) => {
      res.resume();
      res.on('end', resolve);
    }).on('error', reject);
  });
}

for (const [label, agent] of [
  ['agent: false', false],
  ['keepAlive agent', new http.Agent({ keepAlive: true })],
]) {
  lookups = 0; connections = 0;
  for (let i = 0; i < 20; i++) await get(agent);
  console.log(`${label.padEnd(16)} 20 requests → ${lookups} DNS lookups, ${connections} TCP connections`);
}
server.close();
process.exit(0);
agent: false     20 requests → 20 DNS lookups, 20 TCP connections
keepAlive agent  20 requests → 1 DNS lookups, 1 TCP connections

agent: false means, in the words of Node’s docs, “a one-time Agent for this request”, and it turns off connection reuse (http.Agent). Every request gets a new connection, every new connection gets a new dns.lookup. The whole mechanism of the incident is in these two experiments.


2. The incident: the day after tax calculation shipped

🔥 [FIRING] CheckoutSlow: p95 of POST /api/orders is above 1 s

You’re on call for the ShopFlow API. It’s early September. Yesterday evening checkout started fetching sales tax and VAT from a third-party service (TaxRate). Since then placing an order takes one to three seconds. Support passes it on: “The Place order button spins for a long time; the order does eventually go through.” What you know:

  • Traffic is normal (~38 req/s, ~3 orders/s). No errors.
  • Product pages are as fast as ever.
  • The API’s CPU usage is low; nothing on the dashboard looks overloaded.
  • TaxRate’s status page is green, and their dashboards say they answer quotes in ~30 ms.
  • Recent deploys:
VersionWhenChange
2.19.0yesterday 17:30checkout: sales tax / VAT from TaxRate on every order
2.18.34 days agoperformance: JSON responses are gzip-compressed
2.18.22 weeks agobackground confirmation emails handle their own errors (the fix from Part 3)

If you’ve set up the lab, start the incident:

git clone https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab.git
cd nodejs-production-failure-lab
./lab start 004

💡 Want to try it yourself first? Stop here, open Grafana (http://localhost:3000) and Jaeger (http://localhost:16686) and investigate on your own for 30 minutes. The results of the steps below are in collapsed boxes; open them when you get stuck. For the lab’s own hints: ./lab hint 004.


3. Investigation, step by step

Step 1: Working or waiting?

The first question is always the same: what is slow, and is the system busy? Open Latency measured by the API (p95 by route) and CPU side by side on the dashboard.

What do we see?
  • Only POST /api/orders is slow: p95 swings between 1 and 2.3 s. Product detail (/api/products/:id) p95 is ~8 ms. The finance report in the background (/api/reports/sales) is at its usual ~0.5 s.
  • CPU is ~0.15 cores. The API handles 38 requests per second with ease.

Grafana: on the left, p95 by route; POST /api/orders swings between 1 and 2.3 s, the other routes stay at the floor; on the right, CPU flat around 0.15 cores

The blue line is checkout. Every other route hugs zero, and CPU is below 0.2. The slowness is in a single endpoint and the process is not busy.

Compare with Part 1: there the slowness spread to all routes, because the event loop was blocked. Here only checkout is slow. That tells us the problem is somewhere on checkout’s path.

Step 2: Rule out the usual suspects

Two familiar suspects sit on checkout’s path: the event loop and the database.

Event loop or database?

Neither:

  • Event loop utilization (ELU) is ~16%. On a blocked loop this would be high (it was 55% in Part 1).
  • The p95 of the order queries (orders.insert, customers.by-id, products.prices …) is a few milliseconds. The yellow line at the top of the chart is the finance report’s query (reports.sales, ~240 ms); it has nothing to do with checkout.
  • No requests are waiting in the connection pool.

Grafana: on the left, event loop utilization between 15 and 20%; on the right, database query p95s, every query except reports.sales close to zero

The event loop is using less than a fifth of its capacity; order queries sit at the floor. Checkout’s two seconds are spent neither in JavaScript nor in the database.

Here’s what we have: one slow endpoint, an idle CPU, an idle event loop, a fast database. Checkout isn’t doing something, it’s waiting for something.

Lesson: “CPU is idle” does not mean healthy. A service can be slow without being busy: while it waits.

Step 3: Find the waiting span

In Jaeger, pick the shopflow-api service and the POST /api/orders operation, and open a trace that took more than a second.

Where does the time go?

Jaeger: a 1.1-second POST /api/orders trace; after two short database queries the POST call to TaxRate takes 1.0 s, then the order-insert queries finish within microseconds

A 1.1-second order. The customer and price queries take 2 ms, writing the order 2 ms; in between, the POST call to TaxRate alone takes 1.0 s. What happens inside that call is not visible in the trace.

Nearly all the time is in the http://api.taxrate.example/v1/quotes call. It’s tempting to say “TaxRate is slow”. But TaxRate’s dashboard says 30 ms. Who’s right?

Step 4: Measure the dependency from both sides

The span in the trace measures the call from our side: name resolution, connecting, sending the request, waiting for the response, all in one bar. TaxRate measures only the time from receiving the request to sending the response. Put the two side by side in Prometheus:

# What the API sees (client side)
histogram_quantile(0.95, sum by (le) (rate(http_client_request_duration_seconds_bucket{job="api",peer="taxrate"}[1m])))
# What TaxRate measures itself (server side)
histogram_quantile(0.95, sum by (le) (rate(taxrate_request_duration_seconds_bucket[1m])))
Where does the gap go?

Grafana Explore: the TaxRate call p95 measured by the API swings between 1 and 2.3 s; the p95 TaxRate measures itself is flat at the floor

Green: the TaxRate call as the API sees it, p95 ~2 s. Yellow: TaxRate’s own processing time, p95 ~48 ms (p50 ~32 ms). Both are measuring correctly.

Both sides are telling the truth. The gap is spent before the request reaches TaxRate. What happens before an HTTP request? The host name is resolved (dns.lookup), then a TCP connection is established. Those are the suspects.

Lesson: Measure a dependency’s latency from both ends. If client and server disagree, the time is going somewhere in between: name resolution, connection setup, a queue, the network.

Step 5: Ask libuv what it’s waiting for

The dashboard’s Node.js runtime row has an Active libuv resources, by type panel. It counts the list returned by process.getActiveResourcesInfo(): the in-flight work that keeps the event loop alive (process.getActiveResourcesInfo). Put the Latency of calls to other services panel next to it.

What is it waiting for?

Grafana: on the left, active libuv resources; TCPSocketWrap ~20, Timeout ~6, GetAddrInfoReqWrap constantly between 1 and 6; on the right, calls to external services, TaxRate p95 1–2.4 s, MailWave ~0.25 s

The light green GetAddrInfoReqWrap line almost never drops to zero: at any moment 1–6 DNS lookups are running or queued. On the right, over the same period, TaxRate calls take seconds.

GetAddrInfoReqWrap is libuv’s representation of a dns.lookup() request. In a healthy service this number is almost always zero: name resolution takes milliseconds and happens rarely. Here the 5-minute average is ~1.9 and the peak is 6. Since the pool can only run 2 lookups at a time, anything above 2 is a lookup waiting in the queue.

Step 6: Measure DNS yourself

Get into the API container with ./lab shell and resolve TaxRate’s name, and the database’s name for comparison.

How long does it take?

Terminal: in the API container, time getent hosts api.taxrate.example 1.258 s; getent ahostsv4 api.taxrate.example 0.525 s; getent hosts postgres 0.002 s

TaxRate’s name takes over half a second, postgres 2 ms. Docker’s own DNS resolves container names instantly; external names go to a slow upstream DNS server.

  • getent ahostsv4 api.taxrate.example: 0.53 s. This command makes the same getaddrinfo call Node uses. The dns.lookup times I measured from Node in the same container came out at ~0.6 s too.
  • getent hosts api.taxrate.example took 1.26 s: in this setup it makes two separate queries, so it waits twice.
  • getent hosts postgres: 2 ms.

Now do the math. One lookup is ~0.55 s, 2 lookups at a time: the pool can resolve at most ~3.6 names per second. ~2.9 orders arrive per second, each needing one lookup. Utilization is above ~80% and orders arrive at random intervals: the cruelest region of queueing theory. An order waits for several lookups to finish before its own half-second lookup even starts. That’s why checkout p95 is 2 seconds.

Step 7: Why does every order ask DNS?

You can’t fix TaxRate’s DNS; it isn’t yours. The right question is: you’re calling the same host three times a second, why look up its address every time? If connections were reused, DNS would only be asked on a new connection. TaxRate counts how many connections it accepts on its side (taxrate_connections_total); compare that with the number of quotes the API sends.

How many connections?

Grafana Explore: new TCP connections to TaxRate per second and tax quotes per second from the API; the two lines overlap between 2.7 and 3.3

The two lines are nearly identical: ~2.9 quotes per second, ~2.9 new TCP connections per second. Every quote opens a new connection.

Step 8: The latest code

Now you know what to look for: how the TaxRate client opens its connection.

// checkout/tax.ts (2.19.0)
/**
 * TaxRate closes idle keep-alive connections after 5 s, which gave us
 * ECONNRESET errors on reused sockets in staging (#596), so every quote
 * uses a fresh connection.
 */
export function quoteTax(request: { country: string; amountCents: number }): Promise<TaxQuote> {
  // ...
  const req = http.request(
    new URL('/v1/quotes', config.taxrateUrl),
    {
      method: 'POST',
      agent: false,                     // ← a new connection for every quote
      headers: { /* ... */ },
    },
    (res) => { /* ... */ },
  );
  // ...
}

The story is in the comment: ECONNRESET errors were seen on reused sockets in staging. Why? TaxRate closes idle keep-alive connections after 5 s. If the client sends a new request on the same socket at exactly that moment, the request lands on a connection that’s being closed and gets reset. This is a real, well-known race; Node’s docs describe it in the request.reusedSocket section (http.Agent).

The team “solved” the race by turning off connection reuse entirely. In staging, with low traffic and a fast DNS, the cost was invisible. In production, at three orders a second and with a slow DNS, the same line added a half-second lookup and a queue to every order. The fix for one connection-lifetime bug created another connection-lifetime bug.

A note on the red herring: the gzip compression in 2.18.3 also uses the thread pool and is a reasonable suspect for anyone who knows about the pool. But zlib work is not subject to the “slow I/O” limit, it doesn’t wait on anything, and compressed catalog responses come back in ~8 ms.

The lab’s diagnosis questions and answers (./lab submit 004)
QuestionAnswer
What is checkout spending its time waiting for?DNS lookups of TaxRate’s host name
Why do these waits pile up instead of running in parallel?They run on libuv’s thread pool, where only a couple can run at once
Why does the API need TaxRate’s address so often?Every quote opens a new connection instead of reusing one

4. Mitigation

A proper fix needs a code change and a review. In the meantime, to rescue customers:

  • UV_THREADPOOL_SIZE=16: as an environment variable (it’s read at process start; setting it from code is not reliable). DNS gets 8 slots and the queue disappears. But remember the third line of the demo: every lookup still takes ~0.5 s. According to the measurement in the lab’s solution notes, checkout p95 stays at ~1 s with this setting; still above the SLO (400 ms). It buys time; it doesn’t fix anything. In Wolt’s case growing the pool was the real improvement; here the root cause is that every order asks DNS, and the pool size doesn’t change that.
  • A fixed address in /etc/hosts (extra_hosts in Compose): lookups return instantly, but you’ve hard-coded a partner’s IP and you’ll miss their next move.
  • Don’t: open a “you’re slow” ticket with TaxRate and wait, grow the database pool, or add instances. Every new instance brings the same two-slot DNS queue.

5. The fix: reuse connections

Send quotes through the shared HTTP client (fetch, i.e. undici) that the MailWave client already uses:

// checkout/tax.ts
import { config } from '../platform/config.ts';
import { callService } from '../platform/http-client.ts';

/**
 * Uses the shared HTTP client, which keeps connections to TaxRate open and
 * reuses them: a DNS lookup and a TCP handshake only happen when a new
 * connection is needed, not on every quote. It also closes idle connections
 * before TaxRate does (it reads the server's Keep-Alive timeout), which is
 * what caused the ECONNRESET errors of #596.
 */
export async function quoteTax(request: { country: string; amountCents: number }): Promise<TaxQuote> {
  const response = await callService('taxrate', new URL('/v1/quotes', config.taxrateUrl).href, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(request),
  });
  if (!response.ok) throw new Error(`TaxRate responded ${response.status}: ${await response.text()}`);
  return (await response.json()) as TaxQuote;
}

What changed?

  • Connections stay open and get reused. The DNS lookup and TCP handshake only happen when a new connection is needed; they’re off the hot path.
  • The real cause of #596 goes away. undici reads the Keep-Alive: timeout=5 header the server sends and closes the idle connection before the server does. That was the right fix for the keep-alive race: the client’s idle timeout must be shorter than the server’s. Node’s own http.Agent does the same with the agentKeepAliveTimeoutBuffer option; by default it closes 1 s before the timeout the server announced (http.Agent).
  • Quotes are now visible. They show up in the same metrics and traces as other external calls.

The same idea also works with Node’s own agent: a single shared new http.Agent({ keepAlive: true }) for all quotes. Since Node 19, http.globalAgent already comes with keep-alive on and a 5 s timeout (http.globalAgent); agent: false was deliberately switching that default off.

In the lab, the fix is in spoilers/004-slow-checkout/fix.patch:

git apply spoilers/004-slow-checkout/fix.patch
./lab deploy

6. Verification

./lab verify 004

verify runs functional checks (does every order get its tax from TaxRate and send its confirmation email?), then applies the standard traffic (open model, ~38 req/s) for 60 seconds:

MeasurementTargetBeforeAfter
Checkout p95< 400 ms1.04 s57 ms
Catalog p95< 250 ms26 ms8 ms
Error rate< 0.5%0%0%
CPU0.21 cores0.15 cores
Event loop utilization25%16%

All functional checks passed: orders still get their tax from TaxRate and the confirmation email goes out.

On live traffic, here’s what I measured in Prometheus over 5-minute windows before and after the deploy:

MeasurementBeforeAfter
Traffic38 req/s38 req/s
Checkout p50 / p950.76 s / 1.95 s40 ms / 90 ms
Product detail p958 ms9 ms
TaxRate call p95 (as seen by the API)~2.1 s49 ms
TaxRate’s own p9548 ms48 ms
Pending DNS lookups (GetAddrInfoReqWrap, avg / max)1.9 / 4–60 / 0
New connections to TaxRate~2.9/s (every quote)1 in 5 minutes
CPU0.15 cores0.15 cores
Event loop utilization16%17%

The CPU didn’t budge. The problem was never work; it was waiting.

The charts say the same thing. The second dashed orange line is the moment of the deploy:

Before and after the fix: POST /api/orders p95 drops from 1–2.3 s to the floor; CPU stays at the same level

Checkout’s blue line drops down among the other routes at the second orange line (the deploy). The CPU line on the right stays at 0.15–0.2 cores: the fix didn’t reduce work, it removed the waiting.

Before and after the fix: GetAddrInfoReqWrap drops to zero, the TCPSocketWrap count falls; TaxRate call p95 drops from seconds to milliseconds

On the left, the light green GetAddrInfoReqWrap is flat at zero after the deploy; the number of open sockets (purple) drops from ~20 to ~15. On the right, the TaxRate call p95 drops from seconds to ~50 ms, below even MailWave (~250 ms).

Before and after the fix: the TaxRate p95 seen by the API converges with the p95 TaxRate measures itself

After the deploy (00:40:45) the green line drops onto the yellow one and merges with it: client and server now agree, and the seconds in between are gone.

Before and after the fix: tax quotes per second stay at ~3 while new connections to TaxRate drop to zero

The yellow line (quotes/s) stays at ~2.9; the green line (new connections/s) drops to zero after the deploy; the small blip at the right edge is the single new connection in 5 minutes. The same work, done over a handful of open connections.


7. Fixes that look right but aren’t

AttemptWhy it falls short
Raising UV_THREADPOOL_SIZERemoves the queue, but every order still pays ~0.5 s of DNS. Checkout stays above the SLO. A mitigation, not a fix.
Pinning the address with /etc/hosts or extra_hostsThe lookup goes away, but a partner’s IP now lives in your configuration. When they move, you silently connect to the wrong place.
An in-process DNS cache (e.g. cacheable-lookup)Removes most lookups, but now you own TTLs and failover. In Wolt’s attempt a dns.resolve-based cache led to ENOTFOUND errors in Kubernetes. Think of it as a complement, not a fix.
Using dns.resolve4 as lookupEscapes the pool, but ignores /etc/hosts and the system’s resolver settings (search domains, ndots). In containers it’s an easy way to shoot yourself in the foot.
Saying “TaxRate is slow” and opening a ticket with the partnerTheir dashboards are right: they answer in 30 ms. The slowness is on our side of the connection.
Turning off keep-alive to fix ECONNRESET (the first fix for #596)That’s this incident. The right fix is keeping the client’s idle timeout below the server’s and retrying idempotent requests that are reset on a reused socket.

8. In production: alternatives and prevention

Monitor dependencies from both ends. For every external service, put the client-side latency (what you measure) next to the server side where possible (the partner’s dashboard, or at least their SLA). When they diverge, the time is in between.

Alert on queued DNS lookups:

- alert: DnsLookupsQueueing
  expr: max_over_time(nodejs_active_resources{type="GetAddrInfoReqWrap"}[5m]) > 2
  for: 5m
  labels:
    severity: ticket
  annotations:
    summary: "dns.lookup() calls are queueing on the libuv thread pool"

More than two concurrent lookups on the default pool means lookups are already queuing. This metric comes from prom-client’s default Node.js metrics.

Code review checklist:

  • Is there an agent: false, keepAlive: false, Connection: close, or an HTTP client recreated on every request on the hot path? Red flag.
  • What does each external call cost before it sends a single byte? DNS, TCP, TLS. Is it paid per new connection, or once?
  • Is the client’s idle timeout shorter than the server’s keep-alive timeout?
  • Does the service lean on the thread pool (fs, dns.lookup, crypto.pbkdf2/scrypt, zlib)? If so, was UV_THREADPOOL_SIZE chosen deliberately?

At scale: a node-local DNS cache. With many services and pods, the standard answer lives in the infrastructure: Kubernetes’ NodeLocal DNSCache runs a DNS cache on every node and answers pods’ queries locally. It’s a platform decision, not application code; and it complements connection reuse rather than replacing it.

Think about production’s DNS and volume in staging. The fix for #596 was harmless in staging: DNS was fast there and orders were rare. If the cost of a change depends on the speed of the infrastructure around it, simulate that speed in testing too.


Key takeaways

  • Not everything “asynchronous” in Node.js is the same. Sockets are truly asynchronous; dns.lookup, fs, crypto and zlib queue up in a 4-thread pool.
  • On the default pool, at most 2 dns.lookup() calls run at once. A slow DNS plus frequent lookups builds a queue while the CPU is idle.
  • A slow but idle service is waiting for something. Measure a dependency from both ends; the gap is in between.
  • GetAddrInfoReqWrap is almost always zero in a healthy service.
  • New connection = DNS + TCP (+ TLS). Reuse connections.
  • The fix for keep-alive-related ECONNRESET is not turning off keep-alive but keeping the client’s idle timeout below the server’s.
  • UV_THREADPOOL_SIZE is a mitigation. At Wolt it was the real fix; here it isn’t. Measurement tells you which.

Test yourself

1. Checkout is slow, CPU is 0.15 cores, ELU is 16%. What does that combination tell you?

The service isn’t busy, it’s waiting. The slowness isn’t spent in JavaScript or on the CPU; it’s spent in requests waiting on an external resource (network, DNS, a pool, a lock). The next question should be “waiting for what?”: look at traces and libuv resources.

2. The pool has 4 threads. Why do only 2 DNS lookups run at once?

libuv limits “slow I/O” work such as DNS to at most half the pool ((threads + 1) / 2), so slow lookups don’t starve file system, crypto and zlib work. With 4 threads that’s 2. It’s also why gzip compression was unaffected in this incident.

3. UV_THREADPOOL_SIZE=16 removes the queue. Why is checkout still above the SLO?

With a bigger pool, lookups start without waiting, but each one still takes ~0.5 s. Since every order still opens a new connection, every order pays that half second. The queue goes away; the cost of DNS itself remains. The root cause is a DNS lookup per connection.

4. You see ECONNRESET on keep-alive sockets in staging. How do you fix it without turning off keep-alive?

The error comes from a race: the client sends a request on a socket at the moment the server closes it as idle. Keep the client’s idle timeout shorter than the server’s (undici does this itself from the Keep-Alive: timeout header; Node’s http.Agent has agentKeepAliveTimeoutBuffer). As an extra safeguard, retry once any idempotent request that’s reset on a reused socket (request.reusedSocket).

Further reading

Basics

Deep dives

Real-world incidents


Next up: Database overload. Postgres CPU is at 100%, every endpoint has slowed down, and the DBA is asking “what is the API sending us?”. We’ll learn to find out what the database is busy with using pg_stat_statements and EXPLAIN, and to safely add a missing index to a live table.

The full lab: https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab. If you’ve solved the lab, you can generate the postmortem template with ./lab report 004 and compare it with your own write-up.