Undici Connection Pooling With Custom Agent

Create an undici Agent with per-origin connection limits and pipelining depth, then dispatch pooled HTTP requests with explicit abort timeouts.

JavascriptNodeData Fetching

Code

javascriptsnippet
20 lines
import { Agent, fetch } from 'undici';

const agent = new Agent({
  connections: 128,
  pipelining: 10,
  keepAliveTimeout: 60_000,
  keepAliveMaxTimeout: 300_000,
});

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5000);

const res = await fetch('https://api.example.com/users', {
  dispatcher: agent,
  signal: controller.signal,
});
const users = await res.json();
clearTimeout(timer);

agent.close();

How the snippet works

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Everything borrowed from undici is visible in one line: Agent, fetch.

Everything operates on top-level bindings: agent, controller, timer, res.

Watch out for

  • Plan for an install step: undici is a real dependency, resolved by the package manager.
  • fetch exist only in browsers — a Node runtime has no shims for them out of the box.

Statements that matter

const res = await fetch('https://api.example.com/users', {
  dispatcher: agent,
  signal: controller.signal,
});
const timer = setTimeout(() => controller.abort(), 5000);
const controller = new AbortController();

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `undici`, which the package manager must provide.