-
Notifications
You must be signed in to change notification settings - Fork 4
Add health check for database dependency #23
Description
Summary
The `/health` endpoint only checks if the server is running, not if dependencies (like PostgreSQL) are healthy.
Current State
The health check likely returns 200 OK even if the database is down.
Expected Outcome
Implement comprehensive health checks:
```go
// internal/api/handlers.go
type HealthStatus struct {
Status string `json:"status"`
Version string `json:"version"`
Checks map[string]CheckResult `json:"checks"`
Timestamp time.Time `json:"timestamp"`
}
type CheckResult struct {
Status string `json:"status"` // "healthy", "unhealthy", "degraded"
Message string `json:"message,omitempty"`
Duration string `json:"duration,omitempty"`
}
func (s *Server) HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
checks := make(map[string]CheckResult)
overallStatus := "healthy"
// Check database if configured
if s.store != nil {
start := time.Now()
if s.store.IsHealthy(r.Context()) {
checks["database"] = CheckResult{
Status: "healthy",
Duration: time.Since(start).String(),
}
} else {
checks["database"] = CheckResult{
Status: "unhealthy",
Message: "database connection failed",
}
overallStatus = "unhealthy"
}
}
// Add more checks as needed
checks["server"] = CheckResult{Status: "healthy"}
status := HealthStatus{
Status: overallStatus,
Version: version.Get().Version,
Checks: checks,
Timestamp: time.Now(),
}
statusCode := http.StatusOK
if overallStatus != "healthy" {
statusCode = http.StatusServiceUnavailable
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(status)
}
```
Kubernetes Probes
Support separate endpoints for different probe types:
- `/health/live` - Liveness probe (is the process running?)
- `/health/ready` - Readiness probe (can it accept traffic?)
Acceptance Criteria
- Health check includes database status
- Returns 503 if critical dependencies are unhealthy
- Response includes version and timestamp
- Separate liveness and readiness endpoints
- Unit tests for health check logic
- Documentation updated