Sobes.tech
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:

  1. Round Robin — a simple method where requests are sequentially directed to each server in turn.
  2. Least Connections — a request is sent to the server with the fewest active connections.
  3. 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(&current, 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.