diff --git a/lib/_http_agent.js b/lib/_http_agent.js index 5e3298b594d949..eff456cf38b089 100644 --- a/lib/_http_agent.js +++ b/lib/_http_agent.js @@ -112,11 +112,16 @@ function Agent(options) { if (this.sockets[name]) count += this.sockets[name].length; - if (count > this.maxSockets || freeLen >= this.maxFreeSockets) { - socket.destroy(); - } else if (this.keepSocketAlive(socket)) { - freeSockets = freeSockets || []; - this.freeSockets[name] = freeSockets; + if (this.keepSocketAlive(socket) && + this.maxFreeSockets > 0 && + count <= this.maxSockets) { + if (freeLen >= this.maxFreeSockets) { + const oldest = this.freeSockets[name].shift(); + oldest.destroy(); + } else { + freeSockets = freeSockets || []; + this.freeSockets[name] = freeSockets; + } socket[async_id_symbol] = -1; socket._httpMessage = null; this.removeSocket(socket, options); @@ -207,7 +212,7 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */, if (freeLen) { // We have a free socket, so use that. - const socket = this.freeSockets[name].shift(); + const socket = this.freeSockets[name].pop(); // Guard against an uninitialized or user supplied Socket. const handle = socket._handle; if (handle && typeof handle.asyncReset === 'function') {