❯ehsan.blog
~/blog/your-back-to-back-fetch-calls-open-two-connections — zsh
❯cat your-back-to-back-fetch-calls-open-two-connections.md

Back-to-back fetch() calls open two connections, not one

·8 min read

Back-to-back fetch() calls open two connections, not one — article card for a post by Ehsan Shahid

I expected a simple thing. If I call fetch() to the same server ten times in a row, waiting for each one to finish before starting the next, Node should open one connection and reuse it ten times. That is what keep-alive is for.

Node opens two. Not one. Not ten. Exactly two, every single time, no matter how many requests I make.

I found this while looking at the outbound calls api-client makes — the HTTP client I wrote to stop rewriting the same lib/api.ts in every project — got confused, and spent an afternoon with a packet counter until the number made sense. Here is the measurement, the reason, and the fix — which is one line, if you even want it.

First, the thing you can run yourself

No libraries. Just Node. Save this as two.mjs and run it:

js
import http from 'node:http'

// Each trial gets its own server on its own port, so it also gets its own
// fresh connection pool. Nothing carries over from the trial before it.
async function trial (requests, pauseBetween = false) {
  let sockets = 0
  const server = http.createServer((req, res) => res.end('ok'))
  server.keepAliveTimeout = 60_000           // keep the server out of the story
  server.on('connection', () => sockets++)
  await new Promise(r => server.listen(0, r))
  const url = `http://127.0.0.1:${server.address().port}/`

  for (let i = 0; i < requests; i++) {
    await (await fetch(url)).text()
    if (pauseBetween) await new Promise(setImmediate)
  }

  server.close()
  return sockets
}

for (const n of [1, 2, 3, 10, 50]) {
  console.log(`${String(n).padStart(2)} fetches, back to back        -> ${await trial(n)} TCP connection(s)`)
}
console.log(`10 fetches, setImmediate between -> ${await trial(10, true)} TCP connection(s)`)

The server counts connection events, which fire once per real TCP connection. I set keepAliveTimeout high so the server never hangs up on us — any extra connection we see is the client’s doing, not the server’s.

On Node 22.16.0, every run gives me the same thing:

plaintext
 1 fetches, back to back        -> 1 TCP connection(s)
 2 fetches, back to back        -> 2 TCP connection(s)
 3 fetches, back to back        -> 2 TCP connection(s)
10 fetches, back to back        -> 2 TCP connection(s)
50 fetches, back to back        -> 2 TCP connection(s)
10 fetches, setImmediate between -> 1 TCP connection(s)

One request: one connection. Two requests: two connections. Fifty requests: still two. And then that last line — the same ten requests, with one tiny pause added between them, uses one connection.

So this is not a leak. Nothing is growing. But it is also not what anyone would guess, and the last line says the cause is about timing, not about load.

Who is actually opening these sockets

fetch in Node is not something Node wrote from scratch. It is undici, bundled into Node itself. You never import it, you never see it, and it is the thing holding your sockets.

undici keeps a Pool per host. A pool holds a list of Client objects, and each client owns one socket. When a request comes in, the pool looks down its list for a client that is free and hands the request to it. If every client is marked busy, the pool makes a new one.

That is the whole mechanism. The surprise is hiding in the word busy.

The part that explains everything

A client can only have one request in flight at a time (undici does not pipeline by default). So the moment the pool hands a request to a client, it marks that client busy, right there in the same breath:

js
// undici, lib/pool-base.js
} else if (!dispatcher.dispatch(opts, handler)) {
  dispatcher[kNeedDrain] = true
  this[kNeedDrain] = !this[kGetDispatcher]()
}

kNeedDrain is undici’s word for busy. Setting it is instant. Clearing it is not. The client only becomes free again when it emits a drain event, and that event arrives on a later turn of the event loop — after your await has already resumed.

That gap is the whole bug-that-isn’t-a-bug. Line it up:

  1. You await (await fetch(url)).text(). The body is fully read. Your code continues.
  2. The client that served it is still marked busy. Its drain has not fired yet.
  3. You immediately call fetch() again. The pool looks for a free client, sees none, and makes a second one.
  4. Now the first client drains and goes free — one tick too late.

From then on there are two clients, one is always free when you ask, and the number never grows again. Two forever.

I checked step 2 directly rather than guessing, by reading the pool’s internal list after each call:

plaintext
before fetch 1: clients=[]
  body read    : clients=[busy,free]        sockets=1
before fetch 2: clients=[busy,free]
  body read    : clients=[free,busy,free]   sockets=2
before fetch 3: clients=[free,busy,free]
  body read    : clients=[busy,free,free]   sockets=2

Look at before fetch 2. The first request is completely done — I read its whole body — and its client still says busy. That is the moment the second socket gets created.

(You also see undici keeping one extra idle client around. That costs nothing: a client does not open a socket until a request actually lands on it. Three clients, two sockets.)

Proof it is timing, not load

If my explanation is right, giving the first client one spare turn of the event loop should fix it. The script above already tests that, and it does — ten requests, one socket.

But which kind of pause matters, and the answer is a nice little JavaScript lesson:

plaintext
10 sequential fetches, gap=none         -> sockets: 2, 2, 2
10 sequential fetches, gap=microtask    -> sockets: 2, 2, 2
10 sequential fetches, gap=setImmediate -> sockets: 1, 1, 1

await Promise.resolve() is a microtask. It does not help. Microtasks run before the event loop moves on, so the drain event has still not been delivered. setImmediate yields a real turn of the loop, the drain lands, and the next request finds a free client.

How short is that window? I timed it, from the moment text() resolved to the moment the client fired drain, over 30 requests on a loopback server: a median of 0.031 ms, with a worst case of 0.62 ms. So the second socket exists because the pool was asked a question roughly 31 microseconds before the correct answer was written down.

Should you care?

Honestly, usually no. Two warm sockets instead of one is cheap, nothing grows, and the second connection makes your loop slightly more resilient if one socket dies.

Care when:

  • Something upstream counts connections. Some APIs, proxies, and database-ish HTTP services cap connections per client. If you sized your limit as “one worker, one connection,” you are using double.
  • You are staring at a connection graph and the number is wrong. You expect one, you see two, and you go hunting for a leak that is not there. That is the hour this post exists to give you back.
  • You are running many concurrent requests, which is the knob that actually matters — see below.

The knob worth setting

The sequential case is a curiosity. The concurrent case is the real one, because undici’s default connection limit per host is no limit:

plaintext
default agent,           20 concurrent fetches -> 20 sockets
Agent({ connections: 5 }), 20 concurrent fetches ->  5 sockets

Twenty parallel fetch calls open twenty sockets, and each one pays a fresh TCP handshake — plus a TLS handshake on HTTPS. Over the public internet that is real latency, repeated twenty times, for requests that would have been perfectly happy sharing four or five warm connections.

You set the cap with a custom agent:

js
import { Agent, setGlobalDispatcher } from 'undici'

setGlobalDispatcher(new Agent({ connections: 10 }))

Now every fetch in your process uses at most ten sockets per host, and request eleven waits for a free one instead of opening a new socket. The same option also pins the sequential case to one:

plaintext
Agent({ connections: 1 }), 6 sequential fetches -> 1 socket

Pick a number that matches what the other end is happy to accept. There is no universally right value, but “unlimited” is rarely it in production, and the default is unlimited.

What I actually took away

I used to think of fetch as stateless: call it, get a response, nothing persists. The API really does look like that. Underneath, there is a pool of live sockets with their own bookkeeping, and that bookkeeping is updated on the event loop’s schedule, not yours.

Almost all the time that is invisible and fine. But when a number in a dashboard does not match the number in your head, this is the layer the difference is hiding in — and now you have a fifteen-line script that shows it to you in under a second.

If you want more of the same kind of surprise, consuming SSE and NDJSON streams from fetch without a library is another place where fetch’s simple surface sits on top of machinery worth knowing about.

Measured on Node 22.16.0 (bundled undici 5.28.4), Linux. The internal clients=[...] trace used undici 5.29.0 directly, since Node’s copy is internal and cannot be inspected from userland.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.