---
title: "Health Checks"
description: "Liveness vs. readiness: two endpoints with different jobs, and how Kubernetes uses them."
---

> Documentation Index
> Fetch the complete documentation index at: https://codex.mirio.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Health Checks

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

### Go

```go
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"}}`))
    }
}
```

### Rust (axum)

```rust
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.

```json
// 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.

:::note
If you expose a `/metrics` endpoint (Prometheus), put health checks and metrics on a separate
internal port that isn't behind your public load balancer or Caddy reverse proxy. They're
infrastructure concerns, not API endpoints.
:::

## Kubernetes probes

```yaml
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: 3
```

`initialDelaySeconds` 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.

:::tip
Add a startup probe for apps with long initialization (loading a large model,
running migrations on startup). Without it, a slow-starting app will fail
liveness probes and get restarted in a loop before it's ever had a chance to
become ready.

```yaml
startupProbe:
httpGet:
  path: /health
  port: 8080
failureThreshold: 30 # 30 × 10s = 5 minutes max startup window
periodSeconds: 10
```

:::

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](https://codex.mirio.dev/reliability/graceful-shutdown/) for the drain sequence and
how to size the drain timeout against `terminationGracePeriodSeconds`.

Source: https://codex.mirio.dev/reliability/health-checks/index.mdx
