Full answer
Opening a connection costs a round trip for TCP and more for TLS. A service that calls other services should reuse connections and limit them.
undici concepts:
- Dispatcher: the object that sends requests. Client (one connection), Pool (several connections to one origin), Agent (a pool per origin), ProxyAgent, MockAgent.
- Agent options: connections (maximum sockets per origin), pipelining (requests sent on one connection before the response; the default is 1, which is safe), keepAliveTimeout, headersTimeout, bodyTimeout, connect options such as timeout.
- undici.request(url, { dispatcher }) is the fastest, lowest-level API. undici.fetch is the standard API. You must always consume or destroy the response body (await body.text()), or the connection stays blocked.
- setGlobalDispatcher(agent) changes the dispatcher used for requests. Check that your undici version matches the one inside Node when you pass a dispatcher from the npm package to the built-in global fetch, because a version mismatch can fail. Using undici.fetch from the same package avoids this.
- Close agents on shutdown: await agent.close().
Why limits matter: with no limit, a burst of 10,000 calls to one host opens thousands of sockets and can overload both sides. With connections: 10 the extra requests queue inside the agent.
Testing: MockAgent replaces the network.
- const mock = new MockAgent(); mock.disableNetConnect() makes any unmocked request fail, which catches accidental real calls.
- mock.get('https://api.example.com').intercept({ path: '/marks/1', method: 'GET' }).reply(200, { ... }, { headers }).
- Pass dispatcher: mock to the call (or set it as the global dispatcher).
- Use .times(n), .persist(), delay(), and replyWithError() to test retries and timeouts.
This keeps unit tests fast and independent from real services.
const http = require('node:http');
const { Agent, MockAgent, request, fetch: undiciFetch } = require('undici');
async function main() {
// A local server that counts how many TCP connections it receives.
let sockets = 0;
const server = http.createServer((req, res) => setTimeout(() => res.end('ok'), 10));
server.on('connection', () => sockets++);
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const url = 'http://127.0.0.1:' + server.address().port;
// 1. One connection is reused for sequential requests.
const oneConnection = new Agent({ connections: 1, keepAliveTimeout: 1000 });
for (let i = 0; i < 5; i++) {
const { body } = await request(url, { dispatcher: oneConnection });
await body.text(); // always read the body, so the connection is free again
}
console.log('5 sequential requests used', sockets, 'connection(s)');
// 2. The pool never opens more connections than the limit.
sockets = 0;
const twoConnections = new Agent({ connections: 2 });
await Promise.all(Array.from({ length: 6 }, async () => {
const { body } = await request(url, { dispatcher: twoConnections });
await body.text();
}));
console.log('6 parallel requests with connections: 2 used', sockets, 'connections');
await oneConnection.close();
await twoConnections.close();
server.close();
// 3. MockAgent: no network at all.
const mock = new MockAgent();
mock.disableNetConnect();
mock.get('https://api.example.com')
.intercept({ path: '/marks/1', method: 'GET' })
.reply(200, { id: 1, marks: 78 }, { headers: { 'content-type': 'application/json' } });
mock.get('https://api.example.com')
.intercept({ path: '/flaky', method: 'GET' })
.replyWithError(new Error('socket hang up'));
const ok = await undiciFetch('https://api.example.com/marks/1', { dispatcher: mock });
console.log('mocked response:', ok.status, await ok.json());
await undiciFetch('https://api.example.com/flaky', { dispatcher: mock }).catch((err) => console.log('mocked failure:', err.cause.message));
await undiciFetch('https://api.example.com/not-mocked', { dispatcher: mock }).catch((err) => console.log('unmocked call is blocked:', err.cause.code));
await mock.close();
}
main();On the versions used here (undici 8.14.0 on Node 24.22.1), passing the npm Agent to the built-in global fetch failed with an invalid argument error, so the example uses undici's own fetch and request. Install first with npm install undici (run here with undici 8.14.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 5 sequential requests used 1 connection(s) 6 parallel requests with connections: 2 used 2 connections mocked response: 200 { id: 1, marks: 78 } mocked failure: socket hang up unmocked call is blocked: UND_MOCK_ERR_MOCK_NOT_MATCHED
Key points
- Agent keeps pools per origin. connections limits the sockets.
- Always consume the response body.
- Reusing connections saves TCP and TLS set-up.
- MockAgent plus disableNetConnect gives network-free tests.
- Close agents on shutdown.
Common mistakes
- Not reading the response body, so the connection never returns to the pool.
- Creating a new Agent for every request.
- Passing a dispatcher from a different undici version to the global fetch.
- Running tests that call real services.
Follow-ups
- What does pipelining change, and why is it risky?
- How would you set different limits for different origins?
- How do you test a retry with MockAgent?
Tips
- Explain the cost of new connections in one sentence.
- Say 'consume the body'.
- Mention disableNetConnect for tests.