knaxuslearn · build · ship

Projects / Load balancer / Phase 1

Phase 1 of 4 · about 2.5 hours

Spread the requests

You end with a proxy that sends 3,000 requests evenly across three servers, and a clear picture of what goes wrong when one of them dies.

Two words first. A backend is one of the servers that really answers requests. A reverse proxy sits in front of them: the client talks to the proxy, the proxy makes a new request to a backend, and the answer travels back. The client never needs to know which backend did the work. A load balancer is a reverse proxy that has to choose.

Step 1.1: Three tiny backends (about 30 minutes)

We need something to balance. Write a very small web server that says its own name, so we can see who answered. Create cmd/backend/main.go:

// A tiny web server to stand in for one of your real backends.
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"sync/atomic"
	"time"
)

func main() {
	port := flag.Int("port", 9001, "port to listen on")
	name := flag.String("name", "a", "name shown in every answer")
	delay := flag.Duration("delay", 0, "wait this long before answering /")
	flaky := flag.Bool("flaky", false, "fail every second /health check")
	flag.Parse()

	var checks atomic.Int64
	mux := http.NewServeMux()
	mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		if *flaky && checks.Add(1)%2 == 0 {
			http.Error(w, "flaky", http.StatusInternalServerError)
			return
		}
		fmt.Fprintln(w, "ok")
	})
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		time.Sleep(*delay)
		w.Header().Set("X-Backend", *name)
		fmt.Fprintf(w, "hello from %s\n", *name)
	})

	addr := fmt.Sprintf(":%d", *port)
	log.Printf("backend %s listening on %s", *name, addr)
	log.Fatal(http.ListenAndServe(addr, mux))
}

It is a plain web server with two routes. / waits for -delay, then answers hello from <name> and puts its name in an X-Backend header. /health answers ok. The -delay and -flaky flags are for experiments later, and you can ignore them for now.

Start three of them, each in its own terminal:

go run ./cmd/backend -port 9001 -name a
go run ./cmd/backend -port 9002 -name b
go run ./cmd/backend -port 9003 -name c

Each one prints backend a listening on :9001 and keeps running. In your command terminal, ask one directly:

curl -i localhost:9001/
HTTP/1.1 200 OK
X-Backend: a
Date: Mon, 23 Nov 2026 06:30:51 GMT
Content-Length: 13
Content-Type: text/plain; charset=utf-8

hello from a

If a firewall asks whether to allow incoming connections, allow it. These servers only talk to your own machine.

Step 1.2: Forward one request (about 35 minutes)

Now the smallest possible proxy. Go ships one in the standard library: httputil.ReverseProxy. Create main.go in the lb folder:

package main

import (
	"flag"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
)

func main() {
	listen := flag.String("listen", ":8080", "address the proxy listens on")
	target := flag.String("backend", "http://localhost:9001", "backend to forward to")
	flag.Parse()

	u, err := url.Parse(*target)
	if err != nil {
		log.Fatal(err)
	}
	proxy := httputil.NewSingleHostReverseProxy(u)

	log.Printf("proxy on %s -> %s", *listen, u)
	log.Fatal(http.ListenAndServe(*listen, proxy))
}

NewSingleHostReverseProxy builds a handler that rewrites each incoming request to point at the target, sends it, and copies the answer back. It also adds an X-Forwarded-For header, so the backend can see the original caller. Because *httputil.ReverseProxy is itself an http.Handler, we can hand it straight to ListenAndServe.

Run it in the proxy terminal and ask it for a page:

go run .
curl -i localhost:8080/

You should see hello from a and the X-Backend: a header, exactly as if you had asked the backend. The proxy is invisible when it works.

Step 1.3: Take turns (about 35 minutes)

One backend is not a balancer. Let's keep a list and hand requests out in turn, a policy called round robin. Create pool.go:

package main

import (
	"fmt"
	"net/http"
	"net/http/httputil"
	"net/url"
	"sync/atomic"
)

// A Backend is one server we can send requests to.
type Backend struct {
	URL   *url.URL
	proxy *httputil.ReverseProxy
}

// A Pool hands requests to its backends in turn.
type Pool struct {
	backends []*Backend
	next     atomic.Uint64
}

func NewPool(rawURLs []string) (*Pool, error) {
	if len(rawURLs) == 0 {
		return nil, fmt.Errorf("need at least one backend")
	}
	p := &Pool{}
	for _, raw := range rawURLs {
		u, err := url.Parse(raw)
		if err != nil {
			return nil, fmt.Errorf("bad backend %q: %w", raw, err)
		}
		p.backends = append(p.backends, &Backend{URL: u, proxy: httputil.NewSingleHostReverseProxy(u)})
	}
	return p, nil
}

func (p *Pool) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	i := (p.next.Add(1) - 1) % uint64(len(p.backends))
	p.backends[i].proxy.ServeHTTP(w, r)
}

The part that matters is ServeHTTP. next is a counter that goes up by one on every request. Taking it modulo the number of backends gives 0, 1, 2, 0, 1, 2, and so on.

Why atomic.Uint64 and not a plain number? Go runs every incoming request in its own goroutine, a lightweight thread, so many requests run at the same moment. Two of them could read the same counter value and pick the same backend, or corrupt the counter. An atomic does the read and the increment as one step nobody can interrupt.

Replace main.go so it takes a list of backends:

package main

import (
	"flag"
	"log"
	"net/http"
	"strings"
)

func main() {
	listen := flag.String("listen", ":8080", "address the proxy listens on")
	backends := flag.String("backends", "http://localhost:9001,http://localhost:9002,http://localhost:9003", "comma-separated backend addresses")
	flag.Parse()

	pool, err := NewPool(strings.Split(*backends, ","))
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("proxy on %s with %d backends", *listen, len(pool.backends))
	log.Fatal(http.ListenAndServe(*listen, pool))
}

Stop the proxy with Ctrl+C and start it again with go run .. Ask it six times:

for i in 1 2 3 4 5 6; do curl -s localhost:8080/; done
hello from a
hello from b
hello from c
hello from a
hello from b
hello from c

Three servers, taking turns. Six curls prove the idea, but not that it holds up under load. That is next.

Step 1.4: Count with a load generator (about 30 minutes)

We will measure a lot in this project, so let's write the measuring tool once. Create cmd/loadgen/main.go:

// Sends requests as fast as it can and reports what came back.
package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	"net/http"
	"sort"
	"strings"
	"sync"
	"sync/atomic"
	"time"
)

func main() {
	url := flag.String("url", "http://localhost:8080/", "address to hit")
	total := flag.Int("n", 1000, "number of requests (ignored when -d is set)")
	dur := flag.Duration("d", 0, "run for this long instead of a fixed count")
	workers := flag.Int("c", 10, "requests in flight at once")
	method := flag.String("method", "GET", "HTTP method")
	flag.Parse()

	client := &http.Client{
		Timeout:   10 * time.Second,
		Transport: &http.Transport{MaxIdleConnsPerHost: *workers},
	}

	ctx := context.Background()
	if *dur > 0 {
		var cancel context.CancelFunc
		ctx, cancel = context.WithTimeout(ctx, *dur)
		defer cancel()
	}

	var (
		mu        sync.Mutex
		latencies []time.Duration
		backends  = map[string]int{}
		failures  = map[string]int{}
		sent      atomic.Int64
		wg        sync.WaitGroup
	)
	start := time.Now()
	for i := 0; i < *workers; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for ctx.Err() == nil {
				if *dur == 0 && sent.Add(1) > int64(*total) {
					return
				}
				t0 := time.Now()
				req, _ := http.NewRequest(*method, *url, strings.NewReader(""))
				resp, err := client.Do(req)
				took := time.Since(t0)
				mu.Lock()
				switch {
				case err != nil:
					if ctx.Err() == nil {
						failures["connection error"]++
					}
				case resp.StatusCode != http.StatusOK:
					failures[resp.Status]++
				default:
					backends[resp.Header.Get("X-Backend")]++
					latencies = append(latencies, took)
				}
				mu.Unlock()
				if err == nil {
					io.Copy(io.Discard, resp.Body)
					resp.Body.Close()
				}
			}
		}()
	}
	wg.Wait()
	elapsed := time.Since(start)

	ok := len(latencies)
	failed := 0
	for _, n := range failures {
		failed += n
	}
	fmt.Printf("sent     %d in %s (%.0f/s)\n", ok+failed, elapsed.Round(10*time.Millisecond), float64(ok+failed)/elapsed.Seconds())
	fmt.Printf("ok       %d\n", ok)
	fmt.Printf("failed   %d\n", failed)
	for _, k := range sortedKeys(failures) {
		fmt.Printf("  %-18s %d\n", k, failures[k])
	}
	for _, k := range sortedKeys(backends) {
		fmt.Printf("backend %-3s %d\n", k, backends[k])
	}
	if ok > 0 {
		sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
		fmt.Printf("latency  p50 %s  p99 %s\n", latencies[ok/2].Round(100*time.Microsecond), latencies[ok*99/100].Round(100*time.Microsecond))
	}
}

func sortedKeys(m map[string]int) []string {
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	return keys
}

It starts -c workers. Each worker sends a request, waits for the answer and sends the next, until -n requests are done or -d time has passed. Then it prints how many worked, how many failed and why, which backend answered each one (from the X-Backend header), and the median and 99th percentile latency.

A percentile says how slow the slowest requests were. The p99 is the time that 99 out of 100 requests beat, so it shows the unlucky ones that an average hides.

go run ./cmd/loadgen -n 3000 -c 20
sent     3000 in 380ms (7946/s)
ok       3000
failed   0
backend a   1000
backend b   1000
backend c   1000
latency  p50 2.3ms  p99 6.5ms

The three counts are the check: exactly 1,000 each. Your speed and latency will differ, since they depend on your machine.

Step 1.5: Break it (about 20 minutes)

Every system works while nothing is wrong. Let's find out what ours does when a backend dies. In the terminal running backend b, press Ctrl+C. Then ask six times:

for i in 1 2 3 4 5 6; do curl -s -o /dev/null -w "%{http_code} " localhost:8080/; done; echo
200 502 200 200 502 200

One request in three fails with 502 Bad Gateway, which means the proxy could not get an answer from the backend. Your pattern may start in a different place. Run the load generator again:

go run ./cmd/loadgen -n 3000 -c 20
sent     3000 in 330ms (9087/s)
ok       2000
failed   1000
  502 Bad Gateway    1000
backend a   1000
backend c   1000
latency  p50 2.3ms  p99 6.1ms

A thousand failures. The proxy has no idea b is gone, so it keeps sending it every third request. In the proxy terminal you will see the reason, repeated:

http: proxy error: dial tcp 127.0.0.1:9002: connect: connection refused

Start backend b again before moving on, with the same command as in Step 1.1.

Phase 1 done

Three thousand requests, three equal piles, and a failure you can point at. A quarter of the project is behind you.