Junior — Middle
Can you explain the working principle of the Least Connection load balancing algorithm?
sobes.tech AI
Answer from AI
The Least Connection load balancing algorithm distributes incoming requests to servers by choosing the server with the fewest active connections at the moment.
Working principle:
- The load balancer monitors the number of current active connections on each server.
- When a new request arrives, the server with the minimum number of active connections is selected.
- The request is directed to this server, and the active connection count increases.
- After the request is processed, the count decreases.
This allows for even distribution of load, especially when processing times vary, and prevents overloading individual servers.
Example in Go (simplified):
package main
import "fmt"
type Server struct {
Address string
ActiveConnections int
}
func leastConnection(servers []Server) *Server {
var selected *Server
for i := range servers {
if selected == nil || servers[i].ActiveConnections < selected.ActiveConnections {
selected = &servers[i]
}
}
return selected
}
func main() {
servers := []Server{
{Address: "server1", ActiveConnections: 5},
{Address: "server2", ActiveConnections: 2},
{Address: "server3", ActiveConnections: 3},
}
server := leastConnection(servers)
fmt.Printf("Selected server: %s with %d active connections\n", server.Address, server.ActiveConnections)
}