Database connectivity in health check

Learn how to make a health check route test the real database connection with a SELECT 1 query, what status code to return when the database is down, and why the check must stay cheap and fast

A health check that only answers OK tells the truth about the web server and nothing about the database. The server can be running perfectly while the database is down, and every request that needs data will fail. A database health check fixes that blind spot. It runs one tiny query against the real database on every check, and answers 200 when the query works and 503 when it does not, so whatever is watching the route sees the same failure the users would see.

Where This Fits

The drain page ended with a server that stops cleanly and closes its pool. This page looks at the other end of the same connection: how the server proves, while it is running, that its database is still reachable. The plain health route from the earlier pages answers from the process alone. This page adds the pool to that answer, and a process that is alive and a process that can serve traffic are two different claims.

Think of a restaurant phone line. A plain health check is someone picking up the phone and saying hello. A database health check is picking up the phone and confirming the kitchen is actually cooking. The first proves the phone works. The second proves a customer can be fed.

The Smallest Working Version

The check needs the pool, and the pool arrives through shared state. The handler takes State<PgPool>, runs SELECT 1, and maps the two outcomes to two status codes.

// src/main.rs
use axum::{
    extract::State,
    http::StatusCode,
    response::IntoResponse,
    routing::get,
    Json, Router,
};
use serde_json::json;
use sqlx::PgPool;

async fn health() -> &'static str {
    "OK"
}

async fn db_health(State(pool): State<PgPool>) -> impl IntoResponse {
    match sqlx::query("SELECT 1").fetch_one(&pool).await {
        Ok(_) => (
            StatusCode::OK,
            Json(json!({"status": "ok", "database": "ok"})),
        ),
        Err(err) => (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({"status": "error", "database": format!("{err}")})),
        ),
    }
}

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL")
        .expect("DATABASE_URL must be set");
    let pool = PgPool::connect(&database_url)
        .await
        .expect("could not connect to Postgres");
    let app = Router::new()
        .route("/health", get(health))
        .route("/health/db", get(db_health))
        .with_state(pool);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
sqlx = { version = "=0.9.0", features = ["postgres", "runtime-tokio"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"

With Postgres running and DATABASE_URL set, start the server and check both routes:

curl http://127.0.0.1:3000/health
curl http://127.0.0.1:3000/health/db

The first prints OK. The second prints JSON:

{"database": "ok", "status": "ok"}

The versions checked for this page are axum 0.8.9, tokio 1.54.1, and sqlx 0.9.0, against Postgres 16.15. The code above was run live against a real local Postgres while writing this page, with the database up, then stopped, then started again, and the outputs below are the real outputs from those runs.

Working Setup:

If /health/db returns status 200 with "database": "ok", the whole chain works. The pool holds a live connection, the query reached Postgres and came back, and the handler turned that success into the right status code.

What the Check Proves When the Database Is Down

The interesting half of a health check is the failure case, and it was tested live. A throwaway Postgres was started on port 5999, the server was pointed at it, the database was stopped while the server kept running, and the routes were called again.

With the database up, the check answered:

curl http://127.0.0.1:3101/readyz
{"database": "ok", "status": "ready"}
HTTP 200

The verification server registered this same handler at /readyz instead of /health/db, so the outputs below show that path. The handler, the query, and the status codes are identical.

With the database stopped, the same route answered:

curl http://127.0.0.1:3101/readyz
{"database": "pool timed out while waiting for an open connection", "status": "not_ready"}
HTTP 503

Two details in that output matter. The status code is 503, which is the code that means the service is temporarily unavailable, and it is the code load balancers and platforms look for when deciding to stop sending traffic. The body names the failure in plain words, so a human reading the logs can see at once that the pool could not get a connection, rather than guessing from a bare number.

The plain /health route, called at the same moment with the database down, still answered OK with status 200. That split is the point of the page: the process was alive, the database was not, and the two routes told those two different truths at the same time.

When the throwaway database was started again, the check recovered on its own, with no restart of the app:

curl http://127.0.0.1:3101/readyz
{"database": "ok", "status": "ready"}
HTTP 200

The pool reconnected by itself once Postgres was back, and the next check passed. Nothing in the handler needed to reset or retry by hand.

Understanding the Handler Piece by Piece

The handler is short, but every part of it is a decision. The new or hard parts are the state extractor, the query, and the status mapping.

Taking the pool from state

async fn db_health(State(pool): State<PgPool>) -> impl IntoResponse {

State<PgPool> is an extractor that pulls the pool out of the router's shared state. The router was built with .with_state(pool), so every handler on that router can ask for the pool this way. A PgPool is cheap to clone and cheap to move into a handler, because it is a handle to a shared pool rather than a single connection. The handler does not open a connection itself. It borrows one from the pool for the length of one query and gives it back when the query finishes.

Running the smallest real query

    match sqlx::query("SELECT 1").fetch_one(&pool).await {

SELECT 1 is the smallest query that still proves something. It asks Postgres to do real work: parse the statement, run it, and send a row back. It touches no table, reads no data, and changes nothing, so it is safe to run every few seconds. It also exercises the full path a real request takes: the pool hands out a connection, the connection sends bytes to Postgres, Postgres answers, and the connection returns to the pool. A check that only looked at the pool's size or asked whether the pool existed would prove none of that.

fetch_one waits for exactly one row. SELECT 1 always returns one row when the database is up, so a success here is unambiguous. If the database is down, the await fails instead, and the failure lands in the Err branch.

Mapping the outcome to a status code

        Ok(_) => (
            StatusCode::OK,
            Json(json!({"status": "ok", "database": "ok"})),
        ),
        Err(err) => (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({"status": "error", "database": format!("{err}")})),
        ),

The handler returns a tuple of a status code and a JSON body, and Axum turns that into a response. The Ok branch discards the row itself with _, because the row's value, the number 1, carries no information. The Err branch formats the error into the body, so the response says what went wrong instead of only saying that something did.

The error text is safe to expose here because it describes a connection failure, not application data. It never contains rows from a table or values from a request. Even so, keep the body small. A health check is read by machines every few seconds, and a long error dump in every failed response is noise in the logs.

The Concept Behind the Check

A health check is a promise about what the answer means. The plain route promises the process is running. The database route promises the process can reach its data. The value of the check is exactly the strength of that promise, and the strength comes from doing the real thing: running a real query over a real connection, not checking a flag that says the database was reachable once at startup.

A beginner can think of it as a pulse check versus a blood test. Feeling a pulse proves the heart is beating. A blood test proves the rest of the body is working too. Both are useful, and neither replaces the other. The plain route is the pulse. The database route is the test that proves the system behind the pulse can do its job.

Why SELECT 1 and Not a Real Query

A tempting alternative is to check the database with a real query from the app, such as counting the users table. That check proves more, but it costs more and breaks more easily. If the users table is dropped or renamed, the health check fails even though the database is fine. If the table grows large, the count query gets slow, and a slow health check is worse than a weak one, because the platform checking it may time out and declare the server dead.

SELECT 1 avoids both problems. It depends on nothing in the schema, so a migration cannot break it. It costs almost nothing, so it stays fast even when the database is busy. The one thing it cannot prove is that a specific table exists, and that is a different check, one that belongs in a startup migration step or a deeper diagnostics route, not in a check that runs every few seconds.

Keeping the Check Fast

A health check runs on a schedule, often every five or ten seconds, from every load balancer and platform watching the service. If the check is slow, it adds load to the database and delays the verdict. Three rules keep it fast.

First, use the pool's acquire timeout, and keep it short for the check. The pool default is 30 seconds, which is the longest a request waits for a connection. A health check that waits 30 seconds for a dead database is useless, because the platform watching it gave up long before. In the live test on this page, the pool was given a two-second acquire timeout, and the failed check answered in about 2.2 seconds. That is still slow for a health check, and a one-second timeout would be better in production. The timeout is set on the pool builder:

// src/main.rs
use std::time::Duration;

let pool = sqlx::postgres::PgPoolOptions::new()
    .acquire_timeout(Duration::from_secs(2))
    .connect(&database_url)
    .await
    .expect("could not connect to Postgres");

Second, never run a write in a health check. A write changes data every time the platform probes, which corrupts counts, fills tables with junk rows, and can fail for reasons that have nothing to do with health, such as a unique constraint. A health check only reads, and SELECT 1 does not even read a table.

Third, keep the response small. A few fields of JSON are enough. A response that lists every table, every pool statistic, and the full server version is a diagnostics page, not a health check, and it turns a cheap probe into an expensive one.

A Health Check That Waits Too Long Looks Dead:

The pool's default acquire timeout is 30 seconds. If the database goes down and the health check waits the full 30 seconds before answering 503, most platforms will have already timed out the probe and marked the server unhealthy, or worse, left it in rotation while it cannot serve. Set a short acquire timeout on the pool, or the check answers too late to be useful.

What Happens at Startup When the Database Is Down

The live test turned up one more behaviour worth knowing. When the server was started against a database that was not running at all, it did not start and then report unhealthy. It failed at startup, because PgPool::connect itself waits for a connection up to the acquire timeout and then fails:

thread 'main' panicked at src/main.rs:76:10:
could not connect to Postgres: PoolTimedOut

With the default 30-second timeout, that failure takes 30 seconds to appear. With a two-second timeout, it appears in about two seconds. Either way, the program stops before it binds a port or answers a request, which is the fail-fast behaviour: a server that cannot reach its database should not pretend to be up. The health check covers the case where the database dies after startup. The startup failure covers the case where it was never there.

A Richer Version With More Detail

A plain ok or error is enough for a platform, but a human debugging at 2am wants a little more. A richer version reports each dependency separately and keeps the same 200 or 503 rule: 200 only when everything listed is fine.

// src/main.rs
use axum::{
    extract::State,
    http::StatusCode,
    response::IntoResponse,
    routing::get,
    Json, Router,
};
use serde_json::json;
use sqlx::PgPool;

async fn db_health(State(pool): State<PgPool>) -> impl IntoResponse {
    let db_ok = sqlx::query("SELECT 1")
        .fetch_one(&pool)
        .await
        .is_ok();
    let pool_size = pool.size();
    let idle = pool.num_idle();
    let status = if db_ok {
        StatusCode::OK
    } else {
        StatusCode::SERVICE_UNAVAILABLE
    };
    (
        status,
        Json(json!({
            "status": if db_ok { "ok" } else { "error" },
            "database": if db_ok { "ok" } else { "down" },
            "pool": {
                "size": pool_size,
                "idle": idle,
            },
        })),
    )
}

pool.size() reports how many connections the pool currently holds, and pool.num_idle() reports how many of them are sitting free. When the database is down, size falls as connections fail and are dropped, which is a useful clue in the logs. When the database is up but every connection is busy, idle reads 0, which explains why new requests are waiting. Neither number changes the status code. Only the query result does that, because only the query proves the database answers.

A success answer from this version looks like this:

{"database": "ok", "pool": {"idle": 9, "size": 10}, "status": "ok"}

The numbers come from the pool defaults: at most 10 connections, and here 9 of them idle, which is the normal shape of a quiet server.

The Pool Numbers Describe the Pool, Not the Database:

pool.size() counts connections the pool holds, and num_idle() counts the free ones. A pool can report 10 connections while the database is down, if those connections were opened before the failure and have not been noticed as dead yet. The query result is the only verdict. The numbers are context for a human, not a second verdict for the machine.

Checking Several Dependencies

Some servers depend on more than a database. A cache, a queue, or another service can each get their own small check, and the route answers 200 only when all of them pass. The pattern is the same for each one: try the smallest real operation, record true or false, and combine the results at the end.

// src/main.rs
async fn db_health(State(pool): State<PgPool>) -> impl IntoResponse {
    let db_ok = sqlx::query("SELECT 1")
        .fetch_one(&pool)
        .await
        .is_ok();
    let cache_ok = check_cache().await;
    let all_ok = db_ok && cache_ok;
    let status = if all_ok {
        StatusCode::OK
    } else {
        StatusCode::SERVICE_UNAVAILABLE
    };
    (
        status,
        Json(json!({
            "status": if all_ok { "ok" } else { "error" },
            "database": if db_ok { "ok" } else { "down" },
            "cache": if cache_ok { "ok" } else { "down" },
        })),
    )
}

async fn check_cache() -> bool {
    // The smallest real cache operation, for example a PING.
    // Return false when the cache does not answer.
    true
}

The rule for adding a dependency is strict: only list things the server cannot serve without. A cache that the app can work around is not a reason to report the whole service down. A database that holds every user record is. Each extra dependency makes the check stricter, and a check that is too strict takes the server out of rotation for failures its users would never have noticed.

Common Beginner Mistakes

Returning 200 with an error body

// Wrong - the platform sees 200 and keeps sending traffic to a dead database
async fn db_health(State(pool): State<PgPool>) -> Json<serde_json::Value> {
    match sqlx::query("SELECT 1").fetch_one(&pool).await {
        Ok(_) => Json(json!({"status": "ok"})),
        Err(_) => Json(json!({"status": "error"})),
    }
}

The body says error, but the status code says success, and platforms and load balancers read the status code. A failed check must return 503, or the check is decoration. The fix is the tuple return type from the examples above, which lets the handler set the code and the body together.

A 200 on a Failed Check Keeps a Dead Service in Rotation:

This mistake is silent and expensive. Nothing crashes, nothing logs an error, and the dashboard stays green, while every user request fails against a dead database, because the platform trusts the 200 and keeps routing traffic to the server. The status code is the verdict. The body is only the explanation.

Checking the database once at startup and caching the answer

// Wrong - the answer goes stale the moment the database dies
static DB_OK: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(true);

A flag set at startup says the database was reachable when the server started, which is already known from the fact that the server started. A health check must run the query on every call, because the database can die at any moment after startup, and the live test on this page showed exactly that: the same route answered 200, then 503, then 200 again as the database stopped and restarted, with no change to the server.

Using a heavy query for the check

// Wrong - slow, depends on the schema, and loads the database on every probe
let row = sqlx::query("SELECT count(*) FROM users")
    .fetch_one(&pool)
    .await;

A count over a real table gets slower as the table grows, fails when the table is renamed, and adds real load every few seconds. The fix is SELECT 1, which proves connectivity without touching any table.

Forgetting the pool in state

// Wrong - the handler cannot ask for a pool the router never received
let app = Router::new().route("/health/db", get(db_health));

Without .with_state(pool), the State<PgPool> extractor has nothing to extract, and the route fails at runtime when the first request arrives. The fix is to attach the pool to the router, as in the examples, and to clone the pool when it is also needed elsewhere, since cloning a pool handle is cheap.

Testing the Check

The check has two behaviours to test, and both need a real database, because a mock pool cannot fail the way a real one does. The first test is the happy path, run against the local Postgres:

curl -s -w "\nHTTP %{http_code}\n" http://127.0.0.1:3000/health/db
{"database": "ok", "status": "ok"}
HTTP 200

The second test needs the database to die while the server runs. The method used for this page works on any machine with a spare Postgres: start a throwaway database on a different port, point the server at it, stop the database, and call the route:

# Start a throwaway Postgres on port 5999, then start the server against it
# Stop the throwaway database
curl -s -w "\nHTTP %{http_code}\n" http://127.0.0.1:3101/readyz
{"database": "pool timed out while waiting for an open connection", "status": "not_ready"}
HTTP 503

The third test is recovery: start the database again and call the route once more. If it returns 200 without restarting the app, the pool reconnected on its own, which is the behaviour a production server needs.

Final Complete Example

Here is the full program: a plain liveness route, a database route, a short acquire timeout, and the pool close after shutdown.

// src/main.rs
use axum::{
    extract::State,
    http::StatusCode,
    response::IntoResponse,
    routing::get,
    Json, Router,
};
use serde_json::json;
use sqlx::PgPool;
use std::time::Duration;

async fn health() -> &'static str {
    "OK"
}

async fn db_health(State(pool): State<PgPool>) -> impl IntoResponse {
    match sqlx::query("SELECT 1").fetch_one(&pool).await {
        Ok(_) => (
            StatusCode::OK,
            Json(json!({"status": "ok", "database": "ok"})),
        ),
        Err(err) => (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({"status": "error", "database": format!("{err}")})),
        ),
    }
}

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL")
        .expect("DATABASE_URL must be set");
    let pool = sqlx::postgres::PgPoolOptions::new()
        .acquire_timeout(Duration::from_secs(2))
        .connect(&database_url)
        .await
        .expect("could not connect to Postgres");
    let app = Router::new()
        .route("/health", get(health))
        .route("/health/db", get(db_health))
        .with_state(pool.clone());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
    pool.close().await;
}
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
sqlx = { version = "=0.9.0", features = ["postgres", "runtime-tokio"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"

Summary

The useful split on this page is between proving the process runs and proving the system works. The plain route proves the first, the database route proves the second, and only the second can tell a load balancer to stop sending traffic when the data is gone. The check earns that power by doing the real thing on every call, a tiny query over a real connection, and by answering in the language machines read, a status code, with the details in the body for humans.

The decision framework is short. Put in the check every dependency the server cannot serve without, and nothing else. Keep each probe to the smallest real operation, keep it fast with a short timeout, and let the status code carry the verdict. A health check built that way stays honest as the system grows: when a new dependency appears, it gets its own small probe, and when the database dies at 2am, the route that says so is the same route that said everything was fine an hour earlier.