An Agent is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on the
keepAlive option.
Pooled connections have TCP Keep-Alive enabled for them, but servers may
still close idle connections, in which case they will be removed from the
pool and a new connection will be made when a new HTTP request is made for
that host and port. Servers may also refuse to allow multiple requests
over the same connection, in which case the connection will have to be
remade for every request and cannot be pooled. The Agent will still make
the requests to that server, but each one will occur over a new connection.
On a reused HTTP/1.1 keep-alive connection, responses are associated with
requests by their order on that connection. HTTP/1.1 keep-alive does not provide
per-request response attribution beyond that ordering. Applications that require
per-request connection isolation can use a separate Agent, disable keep-alive,
or pass agent: false.
When a connection is closed by the client or the server, it is removed
from the pool. Any unused sockets in the pool will be unrefed so as not
to keep the Node.js process running when there are no outstanding requests.
(see socket.unref()).
It is good practice, to destroy() an Agent instance when it is no
longer in use, because unused sockets consume OS resources.
Sockets are removed from an agent when the socket emits either
a 'close' event or an 'agentRemove' event. When intending to keep one
HTTP request open for a long time without keeping it in the agent, something
like the following may be done:
http.get(options, (res) => { // Do stuff }).on('socket', (socket) => { socket.emit('agentRemove'); });
An agent may also be used for an individual request. By providing
{agent: false} as an option to the http.get() or http.request()
functions, a one-time use Agent with default options will be used
for the client connection.
agent:false:
http.get({ hostname: 'localhost', port: 80, path: '/', agent: false, // Create a new agent just for this one request }, (res) => { // Do stuff with response });
Use agent: false to avoid connection reuse for a request.
Agent Constructor
History
agentKeepAliveTimeoutBuffer.proxyEnv.defaultPort and protocol.maxTotalSockets option to agent constructor.scheduling option to specify the free socket scheduling strategy.new Agent(options?): Agent
Objectbooleankeep-alive value of the Connection header. The Connection: keep-alive
header is always sent when using an agent except when the Connection
header is explicitly specified or when the keepAlive and maxSockets
options are respectively set to false and Infinity, in which case
Connection: close will be used. Default: false.numberkeepAlive option, specifies
the initial delay
for TCP Keep-Alive packets. Ignored when the
keepAlive option is false or undefined. Default: 1000.numberkeep-alive: timeout=... hint when determining socket
expiration time. This buffer helps ensure the agent closes the socket
slightly before the server does, reducing the chance of sending a request
on a socket that’s about to be closed by the server.
Default: 1000.numbermaxSockets value is reached.
If the host attempts to open more connections than maxSockets,
the additional requests will enter into a pending request queue, and
will enter active connection state when an existing connection terminates.
This makes sure there are at most maxSockets active connections at
any point in time, from a given host.
Default: Infinity.numberInfinity.numberkeepAlive is set to true.
Default: 256.string'fifo' or 'lifo'.
The main difference between the two scheduling strategies is that 'lifo'
selects the most recently used socket, while 'fifo' selects
the least recently used socket.
In case of a low rate of request per second, the 'lifo' scheduling
will lower the risk of picking a socket that might have been closed
by the server due to inactivity.
In case of a high rate of request per second,
the 'fifo' scheduling will maximize the number of open sockets,
while the 'lifo' scheduling will keep it as low as possible.
Default: 'lifo'.numberundefinednumber80.string'http:'.options in socket.connect() are also supported.
To configure any of them, a custom http.Agent instance must be created.
import { Agent, request } from 'node:http'; const keepAliveAgent = new Agent({ keepAlive: true }); options.agent = keepAliveAgent; request(options, onResponseCallback);
const http = require('node:http'); const keepAliveAgent = new http.Agent({ keepAlive: true }); options.agent = keepAliveAgent; http.request(options, onResponseCallback);
agent.createConnection(options, callback?): stream.Duplex
Objectnet.createConnection() for the format of the options. For custom agents,
this object is passed to the custom createConnection function.FunctioncreateConnection implementation when the socket is
created, especially for asynchronous operations.stream.Duplexstream.DuplexcreateConnection implementation.
If a custom createConnection uses the callback for asynchronous
operation, this return value might not be the primary way to obtain the socket.Produces a socket/stream to be used for HTTP requests.
By default, this function behaves identically to net.createConnection(),
synchronously returning the created socket. The optional callback parameter in the
signature is not used by this default implementation.
However, custom agents may override this method to provide greater flexibility,
for example, to create sockets asynchronously. When overriding createConnection:
- Synchronous socket creation: The overriding method can return the socket/stream directly.
- Asynchronous socket creation: The overriding method can accept the
callbackand pass the created socket/stream to it (e.g.,callback(null, newSocket)). If an error occurs during socket creation, it should be passed as the first argument to thecallback(e.g.,callback(err)).
The agent will call the provided createConnection function with options and
this internal callback. The callback provided by the agent has a signature
of (err, stream).
agent.keepSocketAlive(socket): void
stream.DuplexCalled when socket is detached from a request and could be persisted by the
Agent. Default behavior is to:
socket.setKeepAlive(true, this.keepAliveMsecs); socket.unref(); return true;
This method can be overridden by a particular Agent subclass. If this
method returns a falsy value, the socket will be destroyed instead of persisting
it for use with the next request.
The socket argument can be an instance of net.Socket, a subclass of
stream.Duplex.
agent.reuseSocket(socket, request): void
stream.Duplexhttp.ClientRequestCalled when socket is attached to request after being persisted because of
the keep-alive options. Default behavior is to:
socket.ref();
This method can be overridden by a particular Agent subclass.
The socket argument can be an instance of net.Socket, a subclass of
stream.Duplex.
agent.destroy(): void
Destroy any sockets that are currently in use by the agent.
It is usually not necessary to do this. However, if using an
agent with keepAlive enabled, then it is best to explicitly shut down
the agent when it is no longer needed. Otherwise,
sockets might stay open for quite a long time before the server
terminates them.
ObjectAn object which contains arrays of sockets currently awaiting use by
the agent when keepAlive is enabled. Do not modify.
Sockets in the freeSockets list will be automatically destroyed and
removed from the array on 'timeout'.
agent.getName
History
options parameter is now optional.agent.getName(options?): string
Get a unique name for a set of request options, to determine whether a
connection can be reused. For an HTTP agent, this returns
host:port:localAddress or host:port:localAddress:family. For an HTTPS agent,
the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options
that determine socket reusability.
numberBy default set to 256. For agents with keepAlive enabled, this
sets the maximum number of sockets that will be left open in the free
state.
numberBy default set to Infinity. Determines how many concurrent sockets the agent
can have open per origin. Origin is the returned value of agent.getName().
numberBy default set to Infinity. Determines how many concurrent sockets the agent
can have open. Unlike maxSockets, this parameter applies across all origins.
ObjectAn object which contains queues of requests that have not yet been assigned to sockets. Do not modify.
ObjectAn object which contains arrays of sockets currently in use by the agent. Do not modify.