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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
