Health checks are how the outside world asks a process whether it is alive and whether it can serve traffic. Those are two different questions, and they need two different endpoints.
Liveness vs. readiness
| Endpoint | Question | Failure means |
|---|---|---|
/health |
Is the process alive? | Restart the container |
/ready |
Can it serve traffic right now? | Remove from the LB rotation |
Liveness should be trivially cheap: return 200 if the process is running.
No database checks, no downstream calls. If liveness fails, Kubernetes restarts
the pod. A liveness check that depends on the database will restart your pod
every time the database hiccups.
Readiness checks whether the process can actually handle requests: database connectivity, required config loaded, warm-up complete. A failing readiness check stops new traffic from routing to the pod but doesn’t restart it. Use this during startup, database failovers, and deploys.
Implementation
func addHealthRoutes(mux *http.ServeMux, db *sql.DB) {
mux.HandleFunc("GET /health", handleLiveness)
mux.HandleFunc("GET /ready", handleReadiness(db))
}
func handleLiveness(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"ok"}`))
}
func handleReadiness(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
w.Header().Set("Content-Type", "application/json")
if err := db.PingContext(ctx); err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintf(w, `{"status":"unavailable","checks":{"database":"error"}}`)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"ok","checks":{"database":"ok"}}`))
}
}use axum::{Router, routing::get, extract::State, http::StatusCode, Json};
use serde_json::{json, Value};
use sqlx::PgPool;
use std::time::Duration;
pub fn health_routes(pool: PgPool) -> Router {
Router::new()
.route("/health", get(liveness))
.route("/ready", get(readiness))
.with_state(pool)
}
async fn liveness() -> (StatusCode, Json<Value>) {
(StatusCode::OK, Json(json!({"status": "ok"})))
}
async fn readiness(State(pool): State<PgPool>) -> (StatusCode, Json<Value>) {
match tokio::time::timeout(Duration::from_secs(2), pool.acquire()).await {
Ok(Ok(_)) => (
StatusCode::OK,
Json(json!({"status": "ok", "checks": {"database": "ok"}})),
),
_ => (
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({"status": "unavailable", "checks": {"database": "error"}})),
),
}
}Response format
Keep responses minimal. Detailed error messages in readiness responses leak internal topology to anyone who can reach the endpoint.
// healthy
{ "status": "ok" }
// degraded
{ "status": "unavailable", "checks": { "database": "error" } }Use 200 for healthy, 503 Service Unavailable for not ready. Some load
balancers only check the status code; the JSON body is for humans and dashboards.
Kubernetes probes
containers:
- name: api
image: api:latest
ports:
- containerPort: 8080
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 5
periodSeconds: 10
failureThreshold: 3
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 3initialDelaySeconds gives the process time to start before the first probe
fires. Set it to roughly how long your app takes to reach a ready state.
failureThreshold sets how many consecutive failures are required before
acting. A single failed probe triggering a restart is too aggressive; three
gives transient blips room to recover on their own.
During shutdown, the readiness probe should return 503 as soon as SIGTERM arrives,
before draining begins, so the load balancer stops routing new traffic before connections
close. See Graceful Shutdown for the drain sequence and
how to size the drain timeout against terminationGracePeriodSeconds.