Discovery, load balancing and health checks
Discovery, load balancing and health checks
Service discovery maps a logical service name to available endpoints; load balancing chooses an endpoint. Readiness indicates whether an instance should receive traffic, whereas liveness checks whether it should be restarted. Discovery results and health observations may be stale. Use bounded connection attempts and handle endpoint failures even after successful discovery.
package main
import ( "fmt")
type Endpoint struct { Name string Ready bool}
func pick(es []Endpoint, next *int) (string, bool) { for i := 0; i < len(es); i++ { j := *next % len(es) *next = (j + 1) % len(es) if es[j].Ready { return es[j].Name, true } } return "", false}func main() { es := []Endpoint{{"a", true}, {"b", false}, {"c", true}} next := 0 for i := 0; i < 3; i++ { v, ok := pick(es, &next) fmt.Println(v, ok) }}Round robin skips unready endpoints and rotates among healthy ones. An empty list returns no endpoint without dividing by zero. The cursor is sequential and nonnegative; concurrent updates need synchronization and an immutable snapshot or equivalent protection. Equal request counts do not guarantee equal CPU load.
Expected output:
a truec truea trueExpose readiness without changing liveness
package main
import ( "fmt" "net/http" "net/http/httptest")
func ready(ok bool) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if !ok { w.WriteHeader(http.StatusServiceUnavailable) return } w.WriteHeader(http.StatusOK) }}func main() { for _, ok := range []bool{false, true} { w := httptest.NewRecorder() ready(ok).ServeHTTP(w, httptest.NewRequest("GET", "/ready", nil)) fmt.Println(w.Code) }}The handler exposes a fixed readiness snapshot in a local test. A real readiness signal should reflect ability to serve relevant requests without expensive checks on every probe. Liveness should not blindly fail because a shared remote dependency is down, which can create restart storms.
Expected output:
503200Try it locally
Write firstReady over a map-independent slice of booleans. Return the first ready index, or -1. Print results for [false,true] and an empty slice.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Distributed services 05: Discovery, load balancing and health checks
Check the lesson objective before moving on.
What does readiness primarily determine?
Can a healthy endpoint still fail on the next call?