Sobes.tech
Junior — Middle

Kuidas toimub koormuse jaotamine serverite või süsteemi komponentide vahel?

sobes.tech AI

Vastus AI-lt

Load balancing is the process of evenly distributing incoming requests or tasks across multiple servers or system components to improve performance and fault tolerance.

Main implementation methods:

  • Round Robin — requests are sequentially sent in a circle to each server.
  • Least Connections — the request is directed to the server with the fewest active connections.
  • IP Hash — server selection based on a hash of the client's IP address, ensuring a session with a single server.

In Go, a simple load balancer can be implemented, for example, using an HTTP reverse proxy with server selection by Round Robin:

var servers = []string{"http://server1", "http://server2"}
var current int

func loadBalancer(w http.ResponseWriter, r *http.Request) {
    target := servers[current]
    current = (current + 1) % len(servers)
    // Redirect the request to the target
    http.Redirect(w, r, target+r.RequestURI, http.StatusTemporaryRedirect)
}

In real systems, specialized load balancers (nginx, HAProxy) or cloud solutions are used.