Skip to content

Commit

Permalink
http: Change free sockets behavior to LIFO from FIFO.
Browse files Browse the repository at this point in the history
Sockets are added to the free list with .push() but they were
being removed with .shift().  This meant the sockets where being
removed in FIFO order, but this changes it to LIFO.  Since older
sockets may be closed based due to inactivity on the server it is
more likely that a socket that is recently used will be able to
successfully process the next request.

Rather than destroying the last used socket destroy
the oldest socket in the free list in push() on the
last recently used socket.
  • Loading branch information
rustyconover committed Feb 17, 2020
1 parent d6f1e39 commit 5af8b39
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions lib/_http_agent.js
Expand Up @@ -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);
Expand Down Expand Up @@ -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') {
Expand Down

0 comments on commit 5af8b39

Please sign in to comment.