diff --git a/lib/_http_agent.js b/lib/_http_agent.js index c47c7f0c597448..eff456cf38b089 100644 --- a/lib/_http_agent.js +++ b/lib/_http_agent.js @@ -112,11 +112,12 @@ function Agent(options) { if (this.sockets[name]) count += this.sockets[name].length; - if (count > this.maxSockets) { - socket.destroy(); - } else if (this.keepSocketAlive(socket)) { + if (this.keepSocketAlive(socket) && + this.maxFreeSockets > 0 && + count <= this.maxSockets) { if (freeLen >= this.maxFreeSockets) { - this.freeSockets[name].shift().destroy(); + const oldest = this.freeSockets[name].shift(); + oldest.destroy(); } else { freeSockets = freeSockets || []; this.freeSockets[name] = freeSockets;