knaxuslearn · build · ship

Projects / Load balancer / Phase 4

Phase 4 of 4 · about 2.5 hours

Change it while it runs

You end with a script that swaps a backend under load and shuts the proxy down mid-flight, and both runs report failed 0.

Everything so far needed a restart to change anything. A restart drops every request in flight. Real balancers are changed all day: servers added, servers retired, new versions rolled out. So the proxy must be able to change, and to stop, without hurting anyone.

Step 4.1: A status page (about 25 minutes)

Before changing things live, we need to see them. Add three counters to the backend, served and failed next to active:

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

	active atomic.Int64 // requests being served right now
	served atomic.Int64 // requests that got an answer from this backend
	failed atomic.Int64 // attempts that ended in an error
}

Count them in ServeHTTP, where an attempt ends:

if result.err == nil {
    b.served.Add(1)
    return
}
b.failed.Add(1)
lastErr = result.err

Then add a handler to pool.go that reports every backend as JSON:

type backendStatus struct {
	URL    string `json:"url"`
	Alive  bool   `json:"alive"`
	Active int64  `json:"active"`
	Served int64  `json:"served"`
	Failed int64  `json:"failed"`
}

// StatusHandler reports the state of every backend as JSON.
func (p *Pool) StatusHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var out []backendStatus
		for _, b := range p.backends {
			out = append(out, backendStatus{
				URL:    b.URL.String(),
				Alive:  b.alive.Load(),
				Active: b.active.Load(),
				Served: b.served.Load(),
				Failed: b.failed.Load(),
			})
		}
		w.Header().Set("Content-Type", "application/json")
		enc := json.NewEncoder(w)
		enc.SetIndent("", "  ")
		enc.Encode(out)
	})
}

Finally serve it from a route of its own in main.go. The proxy keeps everything else:

mux := http.NewServeMux()
mux.Handle("/_lb/status", pool.StatusHandler())
mux.Handle("/", pool)

Pass mux instead of pool to ListenAndServe, and go run ./cmd/loadgen -n 300 -c 5. Then:

curl -s localhost:8080/_lb/status
[
  {
    "url": "http://localhost:9001",
    "alive": true,
    "active": 0,
    "served": 100,
    "failed": 0
  },
  {
    "url": "http://localhost:9002",
    "alive": true,
    "active": 0,
    "served": 100,
    "failed": 0
  }
]

The output continues for the third backend. This page is the first thing you will reach for whenever something looks wrong.

Pitfall: this page shows your internal addresses to anyone who can reach the proxy. We left out any login to keep the code short. A real one belongs on a private port.

Step 4.2: Backends from a file (about 35 minutes)

Today the backends are fixed when the proxy starts. Let's read them from a file, and re-read it on demand. Create config.go:

package main

import (
	"fmt"
	"os"
	"strings"
)

// readBackends reads one backend address per line. Blank lines and lines
// starting with # are ignored.
func readBackends(path string) ([]string, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	var out []string
	for _, line := range strings.Split(string(data), "\n") {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		out = append(out, line)
	}
	if len(out) == 0 {
		return nil, fmt.Errorf("%s lists no backends", path)
	}
	return out, nil
}

The file is one address per line, and # starts a comment. Create backends.txt next to it:

http://localhost:9001
http://localhost:9002
http://localhost:9003

The pool must change while requests are reading it. Locking the list for every request would slow everything down. Instead we never edit the list: we build a new list and swap one pointer to it. A request loads the pointer once and uses whatever list it got, and that list stays valid for as long as it is used.

Change the pool in pool.go like this, and add log and sync to its imports:

// A Pool hands requests to its healthy backends.
type Pool struct {
	list   atomic.Pointer[[]*Backend] // replaced as a whole, never edited in place
	next   atomic.Uint64
	policy string // "round-robin" or "least-connections"

	reloadMu sync.Mutex // one reload at a time
}

func NewPool(rawURLs []string, policy string) (*Pool, error) {
	if policy != "round-robin" && policy != "least-connections" {
		return nil, fmt.Errorf("unknown policy %q", policy)
	}
	p := &Pool{policy: policy}
	p.list.Store(&[]*Backend{})
	if err := p.Reload(rawURLs); err != nil {
		return nil, err
	}
	return p, nil
}

// Reload makes the pool match the given addresses. Backends that stay keep their state,
// new ones are added, and the ones that left stop receiving requests. Requests already
// running on a removed backend finish normally.
func (p *Pool) Reload(rawURLs []string) error {
	if len(rawURLs) == 0 {
		return fmt.Errorf("need at least one backend")
	}
	p.reloadMu.Lock()
	defer p.reloadMu.Unlock()

	current := map[string]*Backend{}
	for _, b := range *p.list.Load() {
		current[b.URL.String()] = b
	}

	var next []*Backend
	for _, raw := range rawURLs {
		u, err := url.Parse(raw)
		if err != nil {
			return fmt.Errorf("bad backend %q: %w", raw, err)
		}
		if b, ok := current[u.String()]; ok {
			next = append(next, b)
			delete(current, u.String())
			continue
		}
		log.Printf("add:  %s", u)
		next = append(next, NewBackend(u))
	}
	p.list.Store(&next)

	for _, gone := range current {
		log.Printf("drop: %s", gone.URL)
	}
	return nil
}

Reload keeps backends that stay, so their counters and health state survive. It starts new ones, and drops the missing ones from the list. A request already running on a dropped backend finishes normally, since it holds its own reference.

Two small edits follow. In pick and in StatusHandler, anywhere you wrote p.backends, write *p.list.Load().

Next main.go reads the file, and a signal triggers a reload. A signal is a small message the operating system sends to a process. By long habit, SIGHUP means "read your configuration again":

package main

import (
	"flag"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	listen := flag.String("listen", ":8080", "address the proxy listens on")
	config := flag.String("config", "backends.txt", "file with one backend address per line")
	policy := flag.String("policy", "round-robin", "round-robin or least-connections")
	flag.Parse()

	addrs, err := readBackends(*config)
	if err != nil {
		log.Fatal(err)
	}
	pool, err := NewPool(addrs, *policy)
	if err != nil {
		log.Fatal(err)
	}

	// SIGHUP: read the file again and apply the difference.
	hup := make(chan os.Signal, 1)
	signal.Notify(hup, syscall.SIGHUP)
	go func() {
		for range hup {
			addrs, err := readBackends(*config)
			if err == nil {
				err = pool.Reload(addrs)
			}
			if err != nil {
				log.Printf("reload failed, keeping the old backends: %v", err)
			}
		}
	}()

	mux := http.NewServeMux()
	mux.Handle("/_lb/status", pool.StatusHandler())
	mux.Handle("/", pool)

	log.Printf("proxy on %s with backends from %s", *listen, *config)
	log.Fatal(http.ListenAndServe(*listen, mux))
}

Build the proxy and run the binary. We build first because go run puts a wrapper process in between, which makes signals awkward to send.

go build -o bin/lb . && bin/lb

Now add a fourth backend. Start go run ./cmd/backend -port 9004 -name d, add http://localhost:9004 as a new line in backends.txt, and tell the proxy:

kill -HUP $(pgrep -x lb)
2026/11/23 06:33:40 add:  http://localhost:9004

Run six curls and you will see d in the answers. No restart, no dropped request.

Step 4.3: Reload under load, and a leak (about 45 minutes)

Removing a backend has a trap. Let's walk into it. With the proxy running on a, b and c, remove the b line from backends.txt and send SIGHUP. Now stop backend b's process and wait four seconds:

2026/11/23 06:37:13 drop: http://localhost:9002
2026/11/23 06:37:16 down: http://localhost:9002 (health check failed)

The proxy dropped b, and three seconds later complained that b is down. Of course it did: the health loop for b is still running, forever, checking a server we no longer own. Every reload would leak one more goroutine.

The fix is a way to tell the loop to stop. Go's answer is a context with a cancel function. In backend.go, add context to the imports, add a stop field and give the loop a context to watch:

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

	active atomic.Int64 // requests being served right now
	served atomic.Int64 // requests that got an answer from this backend
	failed atomic.Int64 // attempts that ended in an error

	stop context.CancelFunc // ends the health loop when the backend leaves the pool
}

func NewBackend(u *url.URL) *Backend {
	b := &Backend{URL: u, proxy: httputil.NewSingleHostReverseProxy(u)}
	b.proxy.Transport = transport
	b.proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
		if isDialError(err) {
			b.markDown(err) // do not wait for the next health check
		}
		if a, ok := r.Context().Value(attemptKey{}).(*attemptResult); ok {
			a.err = err // the pool decides what to do next
			return
		}
		writeProxyError(w, err)
	}
	b.alive.Store(b.check()) // start with the truth, not a guess
	ctx, cancel := context.WithCancel(context.Background())
	b.stop = cancel
	go b.healthLoop(ctx)
	return b
}

func (b *Backend) healthLoop(ctx context.Context) {
	ticker := time.NewTicker(healthInterval)
	defer ticker.Stop()
	okRun, failRun := 0, 0
	for {
		select {
		case <-ctx.Done():
			return
		case <-ticker.C:
		}
		if b.check() {
			failRun = 0
			if !b.alive.Load() {
				okRun++
				if okRun >= riseAfter {
					okRun = 0
					b.alive.Store(true)
					log.Printf("up:   %s", b.URL)
				}
			}
		} else {
			okRun = 0
			failRun++
			if failRun >= fallAfter {
				b.markDown(errors.New("health check failed"))
			}
		}
	}
}

Reload calls gone.stop() for every backend it removes:

for _, gone := range current {
    log.Printf("drop: %s", gone.URL)
    gone.stop()
}

Rebuild, repeat the experiment, and the second line never appears. Remove b, stop b, wait: silence.

Now the real test. Start four backends with -delay 5ms, on ports 9001 to 9004, and put 9001 to 9003 in the file. Send traffic for eight seconds:

go run ./cmd/loadgen -d 8s -c 20

About three seconds in, change the file to 9001, 9003 and 9004, and send SIGHUP. A little later, stop backend b for good:

sent     24892 in 8.01s (3109/s)
ok       24892
failed   0
backend a   8298
backend b   3136
backend c   8297
backend d   5161
latency  p50 6.2ms  p99 9.8ms

Zero failures. Backend b served until the moment it was dropped, d took over from there, and nobody noticed.

Step 4.4: Stop politely (about 30 minutes)

The last change is the one that happens at every deploy: stopping. If the proxy is killed with requests in flight, those clients get errors. A polite stop does three things: stop accepting new connections, let the running requests finish, then exit.

Go has Server.Shutdown for exactly this. Let's first write it the obvious way. Add context, errors and time to the imports of main.go. Then replace the last two lines of main, the log.Printf("proxy on ...") and the log.Fatal(...), with a real http.Server and a signal handler:

	srv := &http.Server{Addr: *listen, Handler: mux, ReadHeaderTimeout: 5 * time.Second}

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()
	go func() {
		<-ctx.Done()
		log.Printf("shutting down")
		shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		srv.Shutdown(shutdownCtx)
	}()

	log.Printf("proxy on %s with %d backends", *listen, len(addrs))
	if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
		log.Fatal(err)
	}

signal.NotifyContext gives us a context that is cancelled when the process receives Ctrl+C or a SIGTERM, the signal a deploy tool sends to ask a program to stop. The goroutine waits for that, then calls Shutdown.

Stop your backends and start all three again with -delay 1s, so every request takes a second. Rebuild with go build -o bin/lb . && bin/lb, then shut the proxy down while thirty requests are in the air:

go run ./cmd/loadgen -n 30 -c 30 & sleep 0.3; pkill -TERM -x lb; wait
sent     30 in 320ms (94/s)
ok       0
failed   30
  connection error   30

All thirty failed. The log says shutting down and then nothing. Why? ListenAndServe returns the moment Shutdown starts, not when it finishes. main then reaches its end and the whole process exits, taking the unfinished requests with it.

Pitfall: this bug is invisible in a quick test with fast requests. It only bites when something is in flight, which is exactly when you shut down on a busy day.

The fix is to make main wait until Shutdown has really returned. The shutdown goroutine closes a channel when it is done, and main waits for it. Replace the same block with this one:

	srv := &http.Server{Addr: *listen, Handler: mux, ReadHeaderTimeout: 5 * time.Second}

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()
	drained := make(chan struct{})
	go func() {
		defer close(drained)
		<-ctx.Done()
		log.Printf("shutting down, waiting for requests in flight")
		shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		if err := srv.Shutdown(shutdownCtx); err != nil {
			log.Printf("shutdown: %v", err)
		}
	}()

	log.Printf("proxy on %s with %d backends", *listen, len(addrs))
	if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
		log.Fatal(err)
	}
	<-drained // ListenAndServe returns the moment Shutdown starts, not when it ends
	log.Printf("bye")

Rebuild, start the proxy again and run the same test:

sent     30 in 1.02s (30/s)
ok       30
failed   0
backend a   10
backend b   10
backend c   10
latency  p50 1.0047s  p99 1.0155s

And in the proxy terminal:

2026/11/23 06:33:56 shutting down, waiting for requests in flight
2026/11/23 06:33:57 bye

All thirty finished, each in about a second, then the proxy said goodbye. The ten second limit in Shutdown means a stuck request cannot keep it alive forever.

Step 4.5: The final test (about 15 minutes)

Let's put both tests in one script, so you can run it any time you change the code. It starts its own backends and proxy, so stop yours first. Create final-test.sh in the lb folder:

#!/bin/bash
# final-test.sh: change the backends under load, then shut down under load.
# Both parts should end with "failed   0".
cd "$(dirname "$0")" || exit 1
go build -o bin/backend ./cmd/backend && go build -o bin/loadgen ./cmd/loadgen && go build -o bin/lb . || exit 1

pids=()
trap 'kill "${pids[@]}" 2>/dev/null' EXIT
backend() { bin/backend -port "$1" -name "$2" -delay "$3" >/dev/null 2>&1 & pids+=($!); }

echo "Part 1: swap a backend while 20 clients keep sending"
backend 9001 a 5ms; backend 9002 b 5ms; backend 9003 c 5ms; backend 9004 d 5ms
printf 'http://localhost:9001\nhttp://localhost:9002\nhttp://localhost:9003\n' > backends.txt
bin/lb -config backends.txt >lb.log 2>&1 &
lb=$!
sleep 1
bin/loadgen -d 6s -c 20 > part1.txt &
load=$!
sleep 2
printf 'http://localhost:9001\nhttp://localhost:9003\nhttp://localhost:9004\n' > backends.txt
kill -HUP $lb
wait $load
grep -E "^(ok|failed|backend)" part1.txt
kill $lb; wait $lb 2>/dev/null

echo
echo "Part 2: shut down while 30 slow requests are in flight"
backend 9011 a 1s; backend 9012 b 1s; backend 9013 c 1s
printf 'http://localhost:9011\nhttp://localhost:9012\nhttp://localhost:9013\n' > backends.txt
bin/lb -config backends.txt >lb.log 2>&1 &
lb=$!
sleep 1
bin/loadgen -n 30 -c 30 > part2.txt &
load=$!
sleep 0.3
kill -TERM $lb
wait $load
grep -E "^(ok|failed)" part2.txt
wait $lb 2>/dev/null; echo "lb exited with code $?"

Make it executable and run it:

chmod +x final-test.sh && ./final-test.sh
Part 1: swap a backend while 20 clients keep sending
ok       19085
failed   0
backend a   6362
backend b   2100
backend c   6362
backend d   4261

Part 2: shut down while 30 slow requests are in flight
ok       30
failed   0
lb exited with code 0

Two failed 0 lines. If either is not zero, the failing request is a clue: check the proxy log in lb.log, which the script leaves behind.

Phase 4 done

You changed the backends while people were using it, and you stopped it while they were mid-request, and nobody saw an error. You have just built, in about 10 hours, the core of what every load balancer has to get right.