Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you implement health check and readiness endpoints for a Go service?
Health checks are mandatory for Kubernetes deployments. A liveness probe tells Kubernetes whether the process is running (should it restart?). A readiness probe tells Kubernetes whether the pod should receive traffic (is it ready to serve?).
type HealthChecker struct { db *sql.DB cache *redis.Client start time.Time } func NewHealthChecker(db *sql.DB, cache *redis.Client) *HealthChecker { return &HealthChecker{db: db, cache: cache, start: time.Now()} } // Liveness: is the process alive? (simple, no dependency checks) func (h *HealthChecker) LivenessHandler(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{ "status": "ok", "uptime": time.Since(h.start).String(), }) } // Readiness: can the service handle requests? (checks dependencies) func (h *HealthChecker) ReadinessHandler(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) defer cancel() type depStatus struct { Status string `json:"status"` Error string `json:"error,omitempty"` } ready := true deps := map[string]depStatus{} if err := h.db.PingContext(ctx); err != nil { deps["database"] = depStatus{Status: "unhealthy", Error: err.Error()} ready = false } else { deps["database"] = depStatus{Status: "healthy"} } if err := h.cache.Ping(ctx).Err(); err != nil { deps["cache"] = depStatus{Status: "unhealthy", Error: err.Error()} ready = false } else { deps["cache"] = depStatus{Status: "healthy"} } status := http.StatusOK if !ready { status = http.StatusServiceUnavailable } writeJSON(w, status, map[string]any{ "ready": ready, "dependencies": deps, }) } // Register hc := NewHealthChecker(db, cache) mux.HandleFunc("GET /healthz", hc.LivenessHandler) // liveness mux.HandleFunc("GET /readyz", hc.ReadinessHandler) // readiness
More Related questions...