Implementing Health Checking

1. Implementing Health Service

ProtoDetail
grpc.health.v1.HealthStandardized service
MethodsCheck (unary), Watch (server stream)
StatusUNKNOWN, SERVING, NOT_SERVING, SERVICE_UNKNOWN

2. Registering Health Server

Example: Register health

import (
    healthpb "google.golang.org/grpc/health/grpc_health_v1"
    "google.golang.org/grpc/health"
)
h := health.NewServer()
healthpb.RegisterHealthServer(srv, h)
h.SetServingStatus("", healthpb.HealthCheckResponse_SERVING)         // overall
h.SetServingStatus("user.v1.UserService", healthpb.HealthCheckResponse_SERVING)

3. Setting Service Status

KeyMeaning
""Overall server health
Service namePer-service health
Unknown serviceReturns SERVICE_UNKNOWN

4. Creating Health Check Client

Example: Client

hc := healthpb.NewHealthClient(conn)
res, err := hc.Check(ctx, &healthpb.HealthCheckRequest{Service: "user.v1.UserService"})

5. Calling Check Method

ResultAction
SERVINGSend traffic
NOT_SERVINGMark unhealthy
err NOT_FOUNDService not registered

6. Using Watch Method

Example: Watch stream

stream, _ := hc.Watch(ctx, &healthpb.HealthCheckRequest{Service: "user.v1.UserService"})
for {
    r, err := stream.Recv()
    if err != nil { break }
    fmt.Println("status", r.Status)
}

7. Handling Status Changes

TriggerAction
DB unreachableSetServingStatus(NOT_SERVING)
DB recoversSetServingStatus(SERVING)
Shutdown beginShutdown() sets all NOT_SERVING

8. Implementing Custom Health Logic

CheckDetail
LivenessProcess can respond
ReadinessDependencies (DB, cache) healthy
StartupInitial cache warm-up done

9. Integrating with Load Balancer

MechanismDetail
gRPC client healthCheckConfigService config field
Kubernetesgrpc readiness probe (1.24+)
EnvoyNative gRPC health checking

10. Setting Overall Server Status

PatternDetail
Empty service key ""Reflects whole server
ShutdownCall h.Shutdown() in shutdown hook