Skip to content

Commit 5af8b39

Browse files
committed
http: Change free sockets behavior to LIFO from FIFO.
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.
1 parent d6f1e39 commit 5af8b39

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

lib/_http_agent.js

+11-6
Original file line numberDiff line numberDiff line change
@@ -112,11 +112,16 @@ function Agent(options) {
112112
if (this.sockets[name])
113113
count += this.sockets[name].length;
114114

115-
if (count > this.maxSockets || freeLen >= this.maxFreeSockets) {
116-
socket.destroy();
117-
} else if (this.keepSocketAlive(socket)) {
118-
freeSockets = freeSockets || [];
119-
this.freeSockets[name] = freeSockets;
115+
if (this.keepSocketAlive(socket) &&
116+
this.maxFreeSockets > 0 &&
117+
count <= this.maxSockets) {
118+
if (freeLen >= this.maxFreeSockets) {
119+
const oldest = this.freeSockets[name].shift();
120+
oldest.destroy();
121+
} else {
122+
freeSockets = freeSockets || [];
123+
this.freeSockets[name] = freeSockets;
124+
}
120125
socket[async_id_symbol] = -1;
121126
socket._httpMessage = null;
122127
this.removeSocket(socket, options);
@@ -207,7 +212,7 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */,
207212

208213
if (freeLen) {
209214
// We have a free socket, so use that.
210-
const socket = this.freeSockets[name].shift();
215+
const socket = this.freeSockets[name].pop();
211216
// Guard against an uninitialized or user supplied Socket.
212217
const handle = socket._handle;
213218
if (handle && typeof handle.asyncReset === 'function') {

0 commit comments

Comments
 (0)