Implementing Health Checking
1. Implementing Health Service
| Proto | Detail |
|---|---|
| grpc.health.v1.Health | Standardized service |
| Methods | Check (unary), Watch (server stream) |
| Status | UNKNOWN, 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
| Key | Meaning |
|---|---|
| "" | Overall server health |
| Service name | Per-service health |
| Unknown service | Returns 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
| Result | Action |
|---|---|
| SERVING | Send traffic |
| NOT_SERVING | Mark unhealthy |
| err NOT_FOUND | Service 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
| Trigger | Action |
|---|---|
| DB unreachable | SetServingStatus(NOT_SERVING) |
| DB recovers | SetServingStatus(SERVING) |
| Shutdown begin | Shutdown() sets all NOT_SERVING |
8. Implementing Custom Health Logic
| Check | Detail |
|---|---|
| Liveness | Process can respond |
| Readiness | Dependencies (DB, cache) healthy |
| Startup | Initial cache warm-up done |
9. Integrating with Load Balancer
| Mechanism | Detail |
|---|---|
gRPC client healthCheckConfig | Service config field |
| Kubernetes | grpc readiness probe (1.24+) |
| Envoy | Native gRPC health checking |
10. Setting Overall Server Status
| Pattern | Detail |
|---|---|
| Empty service key "" | Reflects whole server |
| Shutdown | Call h.Shutdown() in shutdown hook |