tezvyn:

http.Agent and connection pooling

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

reusing TCP connections for outbound requests.

OUTLINE

the agent pools and keeps sockets alive, avoiding repeated TCP and TLS handshakes, controlled by keepAlive and maxSockets.

RED FLAG

thinking each request always needs a fresh connection.

WHAT THIS TESTS This probes understanding of the cost of establishing connections and how connection pooling improves throughput and latency for services that call the same upstream repeatedly.

A GOOD ANSWER COVERS http.Agent is responsible for managing the sockets used by outgoing HTTP requests. It maintains pools of sockets keyed by host, port, and other connection attributes. Establishing a new connection is expensive: a TCP three-way handshake, and for HTTPS an additional TLS handshake, both adding round trips. When keepAlive is enabled, the agent does not close a socket after a response completes; instead it returns the idle socket to the pool so the next request to the same host can reuse it, eliminating those handshakes. The maxSockets option caps how many concurrent sockets the agent opens per host; requests beyond that limit queue until a socket frees up, preventing you from overwhelming the upstream or exhausting local file descriptors. Tuning keepAlive, maxSockets, and maxFreeSockets lets you balance reuse against resource consumption.

COMMON WRONG ANSWERS Believing each request inherently needs a fresh connection. Forgetting that the default global agent historically did not enable keepAlive in older Node versions. Setting maxSockets to Infinity and exhausting descriptors or hammering the upstream.

LIKELY FOLLOW-UPS How does HTTP keep-alive at the protocol level relate to the agent. What happens when maxSockets is reached. How do libraries like undici improve on the classic agent.

ONE CONCRETE EXAMPLE A service makes thousands of HTTPS calls per second to one payment API. Without keepAlive each call pays a full TCP and TLS handshake, adding tens of milliseconds and CPU. Creating an agent with keepAlive true and a sensible maxSockets reuses warm sockets, so most requests skip the handshakes entirely, sharply cutting latency and connection churn.

Read the original → nodejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.