Junior — Middle
How can traffic balancing be achieved between servers for optimal system performance?
sobes.tech AI
Answer from AI
To balance traffic between servers, the following approaches are usually used:
- Round Robin — a simple method where requests are sequentially directed to each server in turn.
- Least Connections — a request is sent to the server with the fewest active connections.
- IP Hash — selecting a server based on hashing the client's IP, which ensures session persistence on the same server.
In Go, ready-made solutions can be used, such as the built-in net/http/httputil package with ReverseProxy for creating a load balancer, or external tools (NGINX, HAProxy).
Example of a simple load balancer in Go with Round Robin:
package main
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"sync/atomic"
)
var servers = []string{
"http://localhost:8081",
"http://localhost:8082",
}
var current uint32
func getNextServer() *url.URL {
idx := atomic.AddUint32(¤t, 1)
serverURL, _ := url.Parse(servers[int(idx)%len(servers)])
return serverURL
}
func handler(w http.ResponseWriter, r *http.Request) {
target := getNextServer()
proxy := httputil.NewSingleHostReverseProxy(target)
proxy.ServeHTTP(w, r)
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
This load balancer will sequentially redirect requests to the servers in the list.