Liveness vs Readiness in Axum, and the Health Check That Always Said OK

My readiness endpoint answered 200 with the database gone, because a handler with no return type answers 200. Two health checks in axum that mean different things, an empty 503, and tests that call the router without opening a port.

Simone Negro, Backend & AI Developer
5 min read

A health check has one job: say “no” when something is wrong. My first readiness endpoint couldn’t. It ran a query against the database, ignored the result and returned nothing, and in axum a handler that returns nothing answers 200 OK:

async fn readyz(State(pool): State<PgPool>) {
    let _ = sqlx::query("SELECT 1").execute(&pool).await;
}
readyz with no database: 200 OK

This post is about doing it properly in the Rust backend I’m building: two endpoints that answer different questions, a 503 with nothing in it, a router shape that every module can follow, and tests that hit the router without opening a port. The examples come from a small demo service, so the paths and names differ from what I run, but every number below was measured on it.

Two questions, two endpoints

“Is the service healthy?” hides two different questions, and they lead to different actions:

EndpointQuestionChecksIf it fails
/livezIs the process alive?nothing, it only has to answerrestart the backend
/readyzCan it serve requests now?a trivial query to the databasedon’t send it traffic, but don’t restart it: the problem is elsewhere

Mixing them causes real damage. If liveness also checked the database, a database outage would make the orchestrator restart a backend that was fine, again and again, while the actual problem sat somewhere else.

A status code and nothing else

In axum, a handler returns anything that implements IntoResponse, and StatusCode does. Returning only a status code gives a response with that status and an empty body, which is all a health check needs:

/// Liveness: the process answers. Never touches the database.
async fn livez() -> StatusCode {
    StatusCode::OK
}

/// Readiness: the database answers a trivial query.
async fn readyz(State(pool): State<PgPool>) -> Result<StatusCode, StatusCode> {
    sqlx::query("SELECT 1")
        .execute(&pool)
        .await
        // The cause belongs in the logs, not in the answer.
        .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;

    Ok(StatusCode::OK)
}

Result<StatusCode, StatusCode> works because axum knows how to turn both sides into a response: Ok becomes the 200, Err becomes the 503. map_err swaps the database error for the 503 and ? returns it.

Why an empty body? Because health endpoints are usually reachable by more things than the rest of the API, and every word you add is information: a version number tells someone which vulnerabilities to try, and a database error tells them what you run. The reason for a 503 is useful to me, so it goes into the logs, which is the topic of the next post in this series.

Each module brings its router, the state goes in once

The health checks need the connection pool, and so will every real module. The shape I settled on: each module exposes one function that returns its own router, and the startup code merges them and hands over the shared state once.

fn probes() -> Router<PgPool> {
    Router::new()
        .route("/livez", get(livez))
        .route("/readyz", get(readyz))
}

// at startup
let app = Router::new().merge(probes()).with_state(pool);

The type is the interesting part. Router<PgPool> reads as “a router that still needs a PgPool”. .with_state(pool) provides it and turns it into a plain Router, ready to serve. I got this wrong twice before it clicked. First I made probes take the pool as a parameter, as if it were a handler, and the compiler complained that I called it with no arguments. Then I called .with_state both inside probes and at startup, and got a mismatched types error, because the second call was giving a pool to a router that no longer needed one.

Testing the router without opening a port

A Router is a tower::Service: something that takes a request and returns a response. That means a test can hand it a request directly, with no server and no network. ServiceExt::oneshot does exactly that for one request.

The remaining problem is the pool. with_state needs a real PgPool, and I don’t want the tests to depend on a running database. connect_lazy_with builds a pool that doesn’t connect until someone uses it. Pointed at a port where nothing listens, it’s perfect: /livez never touches it, and /readyz fails to get a connection, which is precisely the case I want to test.

/// The probes with a lazy pool aimed at a closed port: it only tries to
/// connect when a handler uses it, so /livez never does.
fn app() -> Router {
    let port = std::net::TcpListener::bind("127.0.0.1:0")
        .unwrap()
        .local_addr()
        .unwrap()
        .port();
    let options = PgConnectOptions::new().host("127.0.0.1").port(port);
    let pool = PgPoolOptions::new()
        .acquire_timeout(Duration::from_secs(1))
        .connect_lazy_with(options);

    probes().with_state(pool)
}

async fn get(uri: &str) -> (StatusCode, usize) {
    let request = Request::get(uri).body(Body::empty()).unwrap();
    let response = app().oneshot(request).await.unwrap();
    let status = response.status();
    let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
    (status, body.len())
}

#[tokio::test]
async fn livez_is_200_without_a_database() {
    assert_eq!((StatusCode::OK, 0), get("/livez").await);
}

#[tokio::test]
async fn readyz_is_an_empty_503_without_a_database() {
    assert_eq!((StatusCode::SERVICE_UNAVAILABLE, 0), get("/readyz").await);
}

The port comes from binding to port 0, which makes the system pick a free one, and dropping the listener right away so that nothing answers on it. The short acquire_timeout keeps the readiness test at one second instead of the production wait. Three tests, the third one for a 404 on an unknown path, run in about a second. The 0 in the assertions is the body length: the test fails if anyone ever starts putting details into the answer.

And they guard the original bug. The handler from the top of this post answers 200 with no database, so it fails readyz_is_an_empty_503_without_a_database straight away.

What it does with the database actually down

The tests use a fake outage. To see a real one, I ran the demo service against a real Postgres and paused the database container, so it stopped answering without closing anything:

Situation/livez/readyz
database up200 in under 1 ms200 in 7 ms
database paused200 in under 1 ms503 after 3.0 s
database back200 in 47 ms, without restarting the service

The 3 seconds are the pool’s acquire_timeout: how long anything waits for a connection before giving up. In my backend it’s a little longer, and it’s worth knowing that whoever polls /readyz should wait at least that long before deciding the service is dead. And the last row is the one I like most: the pool reconnected by itself once the database came back, and readiness went green with no help.

A readiness check that can’t fail is worse than none

Without a health check, at least nobody believes anything. With one that always says OK, everything downstream trusts a lie: traffic keeps coming, alerts stay quiet, and the first report of the outage is a user. I now test the failing path of every health check before I trust its passing one. What I’m still unsure about is how much readiness should check: today it’s one query, and I don’t yet know which other dependencies deserve to make it say no.

The pool and its timeout come from the post about Postgres roles and the sqlx pool, if you want to see where they’re set up.

References