Projects / Load balancer / Phase 2
Phase 2 of 4 · about 2.5 hours
Stop sending traffic to dead servers
You end with a backend killed in the middle of a busy run costs about four requests, not a thousand, and it rejoins by itself when it comes back.
The fix has two halves. The proxy needs to ask each backend whether it is well, over and over. And it needs to notice when a real request fails, without waiting for the next question.
Step 2.1: Remember who is alive (about 30 minutes)
First a place to write the answer. Create backend.go and move the Backend type out of pool.go into it:
package main
import (
"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
alive atomic.Bool
}
func NewBackend(u *url.URL) *Backend {
b := &Backend{URL: u, proxy: httputil.NewSingleHostReverseProxy(u)}
b.alive.Store(true) // for now we believe every backend is fine
return b
}
The new alive field is an atomic.Bool, for the same reason as the counter: request goroutines read it while another goroutine will soon write it. For now we believe every backend is fine.
pool.go loses its own Backend type, and gains a smarter way to choose:
package main
import (
"fmt"
"net/http"
"net/url"
"sync/atomic"
)
// A Pool hands requests to its healthy 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, NewBackend(u))
}
return p, nil
}
// pick returns the next healthy backend, or nil when there is none.
func (p *Pool) pick() *Backend {
var healthy []*Backend
for _, b := range p.backends {
if b.alive.Load() {
healthy = append(healthy, b)
}
}
if len(healthy) == 0 {
return nil
}
return healthy[(p.next.Add(1)-1)%uint64(len(healthy))]
}
func (p *Pool) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b := p.pick()
if b == nil {
http.Error(w, "no healthy backend", http.StatusServiceUnavailable)
return
}
b.proxy.ServeHTTP(w, r)
}
pick collects the healthy backends and takes turns among them, so a dead one is skipped and the others share its traffic. If nobody is healthy, ServeHTTP answers 503 Service Unavailable: "we are here, but we cannot serve you right now". That is more truthful than a 502 from a server we know is down.
Run it and the six curls should still go a b c a b c. To see the skipping work, change one line in NewBackend for a moment:
b.alive.Store(u.Port() != "9002") // temporary: pretend b is down
Restart the proxy and the answers become a c a c a c. Put the line back to b.alive.Store(true) before you continue.
Step 2.2: Ask them every second (about 45 minutes)
Now the proxy must find out for itself. Replace backend.go with this version:
package main
import (
"errors"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"sync/atomic"
"time"
)
const (
healthInterval = time.Second // how often we ask each backend "are you ok?"
fallAfter = 2 // failed checks in a row before we call a backend down
riseAfter = 2 // good checks in a row before we call it up again
)
var healthClient = &http.Client{Timeout: 500 * time.Millisecond}
// A Backend is one server we can send requests to.
type Backend struct {
URL *url.URL
proxy *httputil.ReverseProxy
alive atomic.Bool
}
func NewBackend(u *url.URL) *Backend {
b := &Backend{URL: u, proxy: httputil.NewSingleHostReverseProxy(u)}
b.alive.Store(b.check()) // start with the truth, not a guess
go b.healthLoop()
return b
}
// check asks the backend once whether it is healthy.
func (b *Backend) check() bool {
resp, err := healthClient.Get(b.URL.String() + "/health")
if err != nil {
return false
}
defer resp.Body.Close()
io.Copy(io.Discard, resp.Body)
return resp.StatusCode == http.StatusOK
}
func (b *Backend) healthLoop() {
ticker := time.NewTicker(healthInterval)
defer ticker.Stop()
okRun, failRun := 0, 0
for range 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"))
}
}
}
}
// markDown takes the backend out of rotation. It logs only when something changed.
func (b *Backend) markDown(why error) {
if b.alive.CompareAndSwap(true, false) {
log.Printf("down: %s (%v)", b.URL, why)
}
}
Read it from the top.
checkasks one backend for/healthand says yes only for a200answer. It uses its own client with a 500 millisecond timeout, so a hung backend cannot hang the check.NewBackendruns one check right away, so a new backend starts with the truth, then startshealthLoopwithgo. Thegokeyword runs a function in a new goroutine, alongside everything else.healthLoopwakes up every second and counts results in a row. Two failures in a row mark the backend down. Two successes in a row bring it back. Those numbers arefallAfterandriseAfter. Step 2.5 shows why we use two and not one.markDownusesCompareAndSwap, which changes the flag only if it was still true. That way only one caller logs the change, even if several notice at once.
Restart the proxy. Then press Ctrl+C in backend b's terminal and watch the proxy terminal. Start b again a few seconds later:
2026/11/23 06:37:05 proxy on :8080 with 3 backends
2026/11/23 06:37:07 down: http://localhost:9002 (health check failed)
2026/11/23 06:37:11 up: http://localhost:9002
The down line shows up one or two seconds after you stop b. The up line comes about two seconds after you restart it. In between, requests go only to a and c.
Step 2.3: Notice at once (about 25 minutes)
Up to two seconds of blindness is still a lot of failed requests on a busy site. Real traffic is also a health check, and a free one. When the proxy cannot even connect to a backend, there is no need to wait for the next probe.
Add "net" to the imports in backend.go. Then replace NewBackend and add isDialError:
func NewBackend(u *url.URL) *Backend {
b := &Backend{URL: u, proxy: httputil.NewSingleHostReverseProxy(u)}
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
}
http.Error(w, "bad gateway", http.StatusBadGateway)
}
b.alive.Store(b.check()) // start with the truth, not a guess
go b.healthLoop()
return b
}
// isDialError reports whether we could not even connect to the backend.
func isDialError(err error) bool {
var op *net.OpError
return errors.As(err, &op) && op.Op == "dial"
}
ReverseProxy calls ErrorHandler whenever it cannot get an answer. We check whether the failure was a dial error, which means the connection itself could not be made, and if so we mark the backend down on the spot. Then we still answer the unlucky request with a 502, since it already failed.
Notice what we do not do. A request that timed out, or a backend that answered with an error code, does not mark anything down in this step. A slow or grumpy server is not necessarily a dead one, and we do not want one bad request to take a good backend out.
Step 2.4: Kill one under load (about 30 minutes)
Time for the test that failed in Phase 1. With the proxy and all three backends running, start an 8 second run:
go run ./cmd/loadgen -d 8s -c 20
About two seconds in, press Ctrl+C in backend b's terminal. About three seconds later, start b again. When the run ends:
sent 45660 in 8s (5705/s)
ok 45656
failed 4
502 Bad Gateway 4
backend a 19289
backend b 7078
backend c 19289
latency p50 2.9ms p99 11.3ms
And in the proxy terminal:
2026/11/23 06:31:30 down: http://localhost:9002 (dial tcp 127.0.0.1:9002: connect: connection refused)
2026/11/23 06:31:34 up: http://localhost:9002
Four requests failed out of 45,660, the ones that were already in flight toward b when it died. Backend b served 7,078 requests before it died and after it came back, and a and c carried the rest.
Compare that with Phase 1: a thousand failures out of 3,000. Your failed count will differ. If it is a handful, you are right on target.
Step 2.5: Why two in a row? (about 20 minutes)
fallAfter and riseAfter are both 2. Why not 1, which reacts faster? Let's find out. The backend has a -flaky flag that fails every second health check. Stop backend c and start it like this:
go run ./cmd/backend -port 9003 -name c -flaky
Restart the proxy with the thresholds at 2. Wait ten seconds. The proxy log stays quiet, because the failures are never two in a row.
Now change both constants in backend.go to 1 and restart the proxy:
2026/11/23 06:31:54 down: http://localhost:9003 (health check failed)
2026/11/23 06:31:55 up: http://localhost:9003
2026/11/23 06:31:56 down: http://localhost:9003 (health check failed)
2026/11/23 06:31:57 up: http://localhost:9003
The backend flaps in and out of rotation every second. Each flap shifts load onto the others and back, which can overload them.
So the threshold is a trade. A low number reacts fast and flaps. A high number is calm but slow to notice a real death. Neither is right in general, and you have just seen both failure modes.
The calm setting also hides something: this backend fails half its checks and the proxy never says so. A real balancer would count the error rate too. Set both constants back to 2, and restart c normally.
Phase 2 done
You killed a server in the middle of a busy run and lost four requests. The proxy found out by itself, routed around it, and let it back in when it recovered. Half the project is done.