diff --git a/lib/connection/pool.js b/lib/connection/pool.js index 6cd1a9e3c..76b4fb171 100644 --- a/lib/connection/pool.js +++ b/lib/connection/pool.js @@ -141,8 +141,6 @@ var Pool = function(topology, options) { // Number of consecutive timeouts caught this.numberOfConsecutiveTimeouts = 0; - // Current pool Index - this.connectionIndex = 0; // event handlers const pool = this; @@ -1069,15 +1067,30 @@ function _execute(self) { break; } - var connection = null; - const connections = self.availableConnections.filter(conn => conn.workItems.length === 0); + // Load balance our pool connections, sending next workItem to connection with least number of already-pending workItems + var tmpConn = null; + var workItemsLen = 0; + var min = Number.POSITIVE_INFINITY; + var connections = []; + + for (var i = 0; i < self.availableConnections.length; i++) { + tmpConn = self.availableConnections[i]; + workItemsLen = tmpConn.workItems.length; + + if (workItemsLen < min) { + min = workItemsLen; + connections = [tmpConn]; + } else if (workItemsLen === min) { + connections.push(tmpConn); + } + } - // No connection found that has no work on it, just pick one for pipelining - if (connections.length === 0) { - connection = - self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; + var connection = null; + if (connections.length === 1) { + connection = connections[0]; } else { - connection = connections[self.connectionIndex++ % connections.length]; + // We have multiple connections with an equal low-number of workItems, pick a random one + connection = connections[Math.floor(Math.random() * connections.length)]; } // Is the connection connected