Least Connections Algorithm
Description
The Least Connections Algorithm is a load balancing method that directs traffic to the server with the fewest active connections. This algorithm is effective in environments where servers have similar capabilities and traffic patterns, ensuring an even distribution of the load.
C++ Code (without comments)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Server {
int id;
int connections;
};
int findServerWithLeastConnections(const vector<Server>& servers) {
int minConnections = servers[0].connections;
int serverIndex = 0;
for (int i = 1; i < servers.size(); ++i) {
if (servers[i].connections < minConnections) {
minConnections = servers[i].connections;
serverIndex = i;
}
}
return serverIndex;
}
void distributeRequest(vector<Server>& servers) {
int serverIndex = findServerWithLeastConnections(servers);
servers[serverIndex].connections++;
cout << "Request assigned to Server " << servers[serverIndex].id << endl;
}
int main() {
vector<Server> servers = {
{1, 10},
{2, 5},
{3, 7}
};
for (int i = 0; i < 10; ++i) {
distributeRequest(servers);
}
return 0;
}
Time and Space Complexity
Operation | Time Complexity | Space Complexity |
---|---|---|
Find server with least connections | O(N) | O(1) |
Distribute request | O(N) | O(1) |
Where:
- N: Number of servers.