knaxuslearn · build · ship

Projects / Load balancer / Phase 3

Phase 3 of 4 · about 2.5 hours

Choose well, wait less

You end with a table that shows least connections handling the same slow backend about four times faster than round robin.

A balancer that only skips dead servers still has two weaknesses. It can wait forever on a hung backend, and it treats a slow backend exactly like a fast one.

Step 3.1: Never wait forever (about 40 minutes)

First see the problem. Stop backend c and start it as a very slow server:

go run ./cmd/backend -port 9003 -name c -delay 5s

Restart the proxy pointing only at it, and time one request:

go run . -backends http://localhost:9003
curl -s -o /dev/null -w "%{http_code} after %{time_total}s\n" localhost:8080/
200 after 5.001753s

Five seconds, politely. Now imagine a backend that never answers. The default transport behind ReverseProxy has no limit on how long it waits for a response, so every client of that backend would hang until it gave up, and each hung request ties up memory and a connection on our side.

Add a transport of our own to backend.go, a function that turns an error into the right answer, and use both:

// transport is shared by every backend. The defaults wait forever and keep only
// two idle connections per backend, which is not enough for a busy proxy.
var transport = &http.Transport{
	DialContext:           (&net.Dialer{Timeout: time.Second}).DialContext,
	ResponseHeaderTimeout: 2 * time.Second,
	MaxIdleConnsPerHost:   100,
	IdleConnTimeout:       30 * time.Second,
}

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
		}
		writeProxyError(w, err)
	}
	b.alive.Store(b.check()) // start with the truth, not a guess
	go b.healthLoop()
	return b
}

// writeProxyError answers the client: 504 when the backend was too slow, 502 otherwise.
func writeProxyError(w http.ResponseWriter, err error) {
	var netErr net.Error
	if errors.As(err, &netErr) && netErr.Timeout() {
		http.Error(w, "backend timed out", http.StatusGatewayTimeout)
		return
	}
	http.Error(w, "bad gateway", http.StatusBadGateway)
}

The transport sets three limits:

  • DialContext gives up connecting after one second.
  • ResponseHeaderTimeout gives up after two seconds without the start of an answer.
  • MaxIdleConnsPerHost lets the proxy keep 100 idle connections ready per backend. The default is 2, which under real load means the proxy keeps opening and closing connections instead of reusing them.

writeProxyError answers 504 Gateway Timeout when the backend was too slow and 502 when it failed in some other way. The two mean different things to whoever is debugging: "the server is slow" and "the server is broken".

Restart the proxy and time the same request:

504 after 2.001152s

Two seconds, then a clear answer. Choose your own timeouts for real work. They must be longer than your slowest honest request, and shorter than your users' patience.

Step 3.2: Retry the safe ones (about 45 minutes)

Phase 2 lost four requests when a backend died. Most of them could have been saved: the proxy never reached the dead server, so it could simply try another. But careful, retrying is not always safe. Suppose a payment request reaches a server, the server charges the card, and then the connection drops. A retry would charge twice.

So we need rules. Ours are:

SituationRetry?Why
GET, HEAD or OPTIONSYesThese are idempotent: doing them twice has the same effect as once
POST and other methodsNoThe body is already consumed, and the first try may have been applied
The backend timed outNoA slow server is already struggling, and a retry adds load to it
The client gave upNoNobody is waiting for the answer

We retry at most once. The pool needs to learn how each attempt ended, so it can decide. The ErrorHandler runs on the same goroutine as the request, which lets us pass a small result object through the request's context, a bag of values that travels with a request.

Add the result type and update NewBackend in backend.go:

// attemptKey carries a *attemptResult through the request's context, so the
// pool can learn how an attempt on one backend ended.
type attemptKey struct{}

type attemptResult struct{ err error }

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
	go b.healthLoop()
	return b
}

Now pool.go changes more. Add context and errors to its imports, and replace pick and ServeHTTP with these four pieces:

const maxAttempts = 2 // the first try plus one retry

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

// pick returns a healthy backend we have not tried yet, or nil when there is none.
func (p *Pool) pick(tried map[*Backend]bool) *Backend {
	var candidates []*Backend
	for _, b := range p.backends {
		if b.alive.Load() && !tried[b] {
			candidates = append(candidates, b)
		}
	}
	if len(candidates) == 0 {
		return nil
	}
	return candidates[(p.next.Add(1)-1)%uint64(len(candidates))]
}

// retryable says whether a failed request may be sent to another backend.
func retryable(r *http.Request, err error) bool {
	if errors.Is(err, context.Canceled) {
		return false // the client gave up, nobody is waiting
	}
	var timeout interface{ Timeout() bool }
	if errors.As(err, &timeout) && timeout.Timeout() {
		return false // a slow backend is busy already, a retry only adds load
	}
	switch r.Method {
	case http.MethodGet, http.MethodHead, http.MethodOptions:
		return true
	}
	return false // the body is gone, and a POST may already have been applied
}

func (p *Pool) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	tried := map[*Backend]bool{}
	var lastErr error
	for attempt := 0; attempt < maxAttempts; attempt++ {
		b := p.pick(tried)
		if b == nil {
			if lastErr == nil {
				http.Error(w, "no healthy backend", http.StatusServiceUnavailable)
				return
			}
			break
		}
		tried[b] = true

		result := &attemptResult{}
		ctx := context.WithValue(r.Context(), attemptKey{}, result)
		b.proxy.ServeHTTP(w, r.WithContext(ctx))

		if result.err == nil {
			return
		}
		lastErr = result.err
		if !retryable(r, lastErr) {
			break
		}
	}
	writeProxyError(w, lastErr)
}

pick now takes the set of backends already tried, so a retry goes somewhere new. ServeHTTP loops up to maxAttempts times. A successful attempt returns. A failed one is stored, and retryable decides whether to go round again. When we give up, writeProxyError finally answers the client.

Test it with the same experiment as Step 2.4, once with GET, which is the default, and once with POST:

go run ./cmd/loadgen -d 6s -c 20
go run ./cmd/loadgen -d 6s -c 20 -method POST

Kill and restart backend b during each run, as before.

GET   failed   0
POST  failed   1

GET loses nothing, because every request that hit the dead backend was quietly tried on another. POST still loses the few that were in flight, exactly as the rules say. Your POST count will differ, but it should not be zero for long.

Pitfall: retries multiply load. If a backend is failing because it is overloaded, retrying every request on the survivors can push them over too. That is why we retry once, skip timeouts, and never retry blindly.

Step 3.3: Fewer requests for the busy one (about 35 minutes)

Round robin treats all backends as equal. Imagine one of them is slow today, perhaps another job is using its CPU. It still gets a third of the traffic, and its requests pile up.

Least connections is a better rule: send the next request to the backend with the fewest requests in progress right now. A slow backend has more in progress, so it gets fewer new ones.

We need a counter per backend, a policy on the pool, and a smarter pick. First backend.go gets the counter:

// 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
}

Then pool.go grows a policy, validated in NewPool, and a pick that knows both rules:

// A Pool hands requests to its healthy backends.
type Pool struct {
	backends []*Backend
	next     atomic.Uint64
	policy   string // "round-robin" or "least-connections"
}

func NewPool(rawURLs []string, policy string) (*Pool, error) {
	if policy != "round-robin" && policy != "least-connections" {
		return nil, fmt.Errorf("unknown policy %q", policy)
	}
	if len(rawURLs) == 0 {
		return nil, fmt.Errorf("need at least one backend")
	}
	p := &Pool{policy: policy}
	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 a healthy backend we have not tried yet, or nil when there is none.
func (p *Pool) pick(tried map[*Backend]bool) *Backend {
	var candidates []*Backend
	for _, b := range p.backends {
		if b.alive.Load() && !tried[b] {
			candidates = append(candidates, b)
		}
	}
	if len(candidates) == 0 {
		return nil
	}
	start := int((p.next.Add(1) - 1) % uint64(len(candidates)))
	if p.policy == "round-robin" {
		return candidates[start]
	}
	// Least connections. Starting at a different place each time breaks ties fairly.
	best := candidates[start]
	for i := 1; i < len(candidates); i++ {
		c := candidates[(start+i)%len(candidates)]
		if c.active.Load() < best.active.Load() {
			best = c
		}
	}
	return best
}

pick starts at a different place in the list each time. When two backends are tied, the tie goes to a different one each time, so ties do not always favour the first.

Count requests while they run. In ServeHTTP, add one line before the call to the backend and one after:

b.active.Add(1)
b.proxy.ServeHTTP(w, r.WithContext(ctx))
b.active.Add(-1)

Finally add a -policy flag to main.go:

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")
	policy := flag.String("policy", "round-robin", "round-robin or least-connections")
	flag.Parse()

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

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

Step 3.4: Measure both (about 30 minutes)

Now the test that settles it. Run three backends, two quick and one slow. Stop your backends and start them again:

go run ./cmd/backend -port 9001 -name a -delay 5ms
go run ./cmd/backend -port 9002 -name b -delay 5ms
go run ./cmd/backend -port 9003 -name c -delay 100ms

Run the proxy once with each policy, and send the same 5 second load at each:

go run . -policy round-robin
go run ./cmd/loadgen -d 5s -c 30

go run . -policy least-connections
go run ./cmd/loadgen -d 5s -c 30
PolicyRequests per secondabcp99
round-robin7841,3331,3331,333101.9 ms
least-connections3,1357,7547,694500101.7 ms

Same backends, same load, four times the throughput. Round robin sent a third of the traffic to the slow server, and the workers waiting on it could not send anything else. Least connections sent it only 500 of nearly 16,000 requests.

Two notes. First, the p99 barely moved: the few requests that do land on c are still slow, and p99 sees them. Second, our load generator is closed loop: each worker waits for an answer before sending the next, so a slow backend also slows the sender. Real users arrive whether or not your server is keeping up, and then a slow backend builds a queue instead of lowering throughput. The ranking of the policies stays the same, but the numbers would look different.

Phase 3 done

The proxy no longer waits forever, it quietly retries what is safe, and it moves work away from a backend that is falling behind. Three quarters done.