At the end of part 2, I killed one of three backends and every third request to steer came back as a 502. Round robin had no idea the backend was dead.
The obvious fix is health checks: poll each backend, and stop sending traffic to the ones that don’t answer. I built that, and measured it. Health checks on their own still drop requests, because there’s always a gap between a backend dying and the next check noticing.
the experiment Link to heading
Three backends on my laptop, 100 requests to steer, then I kill one backend and send 300 more. The requests go one at a time with curl, and I count the status codes. Here’s the result for three versions of steer, with health checks every 2 seconds:
| version | 200 OK | 502 |
|---|---|---|
| phase 2: round robin, no health checks | 300 | 100 |
| health checks only (3 runs) | 380, 397, 380 | 20, 3, 20 |
| health checks plus retries (3 runs) | 400, 400, 400 | 0, 0, 0 |
Health checks are a huge improvement over nothing. But look at the middle row: 20 failures, then 3, then 20. The number changes because it depends on when the kill lands. If a check is about to run, the gap is tiny. If one just finished, the backend gets almost 2 full seconds of traffic it can’t answer.
A health check tells you what was true at the last check. Everything between checks is a guess.
These numbers are from one curl at a time. Real traffic is much busier, and every extra request in that gap has a one-in-three chance of landing on the dead backend.
the fix: let real requests be health checks Link to heading
A failed request is the most up-to-date health information you can get. So steer now has two mechanisms:
- active checks: a background goroutine polls
/healthzon every backend every 2 seconds - passive detection: when a real request can’t reach a backend, that backend goes out of rotation immediately, and the request is retried on another one
Here’s the entire failure in the log from one of the zero-error runs. Exactly one request touched the dead backend:
GET /after3 -> http://localhost:8082 failed: dial tcp [::1]:8082: connect: connection refused
backend http://localhost:8082 is DOWN (request failed)
The client never found out. The remaining requests were split evenly: 150 each to the two backends still alive.
The two mechanisms have different jobs. Real requests take a backend out quickly, and only health checks bring it back. Passive detection can’t bring a backend back on its own, because a backend that’s out of rotation doesn’t get any requests to succeed at.
the tricky bit: ReverseProxy has already replied Link to heading
In part 1 I went through how much Go’s httputil.ReverseProxy does for you. One of the things it does is send a 502 the moment a backend fails. Once that’s written to the client, you can’t take it back, so you can’t retry.
The way around it is to replace its error handler with one that writes nothing and just remembers what went wrong:
func recordFailure(w http.ResponseWriter, r *http.Request, err error) {
if failed, ok := r.Context().Value(failureKey{}).(*error); ok {
*failed = err
return
}
http.Error(w, "bad gateway", http.StatusBadGateway)
}
The error gets back to my code through the request’s context, which is a bag of values that travels along with a request. Then the handler can loop:
for {
b := p.Next(tried)
if b == nil {
http.Error(w, "no healthy backends", http.StatusServiceUnavailable)
return
}
tried[b] = true
var failed error
ctx := context.WithValue(r.Context(), failureKey{}, &failed)
b.Proxy.ServeHTTP(w, r.WithContext(ctx))
if failed == nil {
return
}
// ...mark the backend down, and decide whether to retry
}
you can’t retry everything Link to heading
Retrying a GET is safe. Retrying a POST might charge someone twice, because the backend may have processed the request before the connection failed. So steer only retries GET, HEAD and OPTIONS requests with no body.
That has a real cost. When I killed two backends and sent six POSTs, this came back:
502 502 200 200 200 200
Each newly dead backend costs one failed POST before steer takes it out of rotation. In that test, though, the connection was refused, so the backend definitely never saw the request and a retry would have been safe. Telling “never got there” apart from “got there and then died” is something I haven’t done yet.
things that surprised me Link to heading
Skipping a dead backend isn’t fair. The obvious way to skip a dead backend is to move on to the next one in the list. But with backends A, B, C and B dead, every request meant for B goes to C. A gets a third of the traffic and C gets two thirds. So Next builds a list of the live backends and picks from that, and a test checks the split is exactly even.
Closing a browser tab looks like a backend failure. When a client hangs up, the proxy reports an error. If I treated that as the backend’s fault, people closing tabs could take healthy servers out of rotation. So steer checks whether the client’s request was cancelled before blaming the backend.
My first test returned thirty 503s in a row. I’d started steer and the backends at the same moment. Steer’s first health check ran before the backends were listening, marked them all down, and didn’t look again for 2 seconds. Steer was right! It’s the same gap between “started” and “ready” that caught me out in part 1.
the race from part 2 came back Link to heading
In part 2 I said reading the backend list was safe because nothing wrote to it. Now the health checker writes to each backend while requests read from it, so the flag is an atomic.Bool:
func (b *Backend) SetAlive(alive bool, reason string) {
if b.alive.Swap(alive) == alive {
return
}
// ...log the change
}
Swap sets the new value and returns the old one in a single step, so if two goroutines report the same failure, only one of them logs it. All 11 tests pass under go test -race.
what it still can’t do Link to heading
- A backend that hangs. If it accepts the connection and never answers, requests already in flight just wait. The health check takes it out of rotation, but doesn’t rescue those requests. That needs timeouts, which is phase 6.
- HTTP 500s. A backend answering with an error is still answering, so steer passes it through.
- Flapping. One failed check takes a backend out, and one pass brings it back.
things I’m still not sure about Link to heading
- How many failed checks should it take? Real load balancers usually want several in a row, to avoid flapping. But every extra check widens the gap I measured above.
- Can retries make an outage worse? Here a retry is cheap, because a refused connection fails instantly. But if backends are failing because they’re overloaded, retrying adds more load to the survivors. That’s the same trap I wrote about in Narya, and I’d like to measure it.
Next is phase 4, least connections, where I finally get to make one backend slow on purpose and watch round robin do the wrong thing.
The code is at github.com/balakrishnan-vasudevan/steer.