Health check route
Learn what a health check route is, why load balancers and process managers probe it, what a good health answer contains, and which status codes and shapes to use
A health check route is a small route on a server whose only job is to answer the question "are you alive and able to work?" It does no real work itself. It takes no input, reads no database, and returns a short answer, usually just the word ok, in a fraction of a second. Other systems call it again and again, every few seconds, and use the answer to decide whether the server should keep receiving traffic.
Where This Fits
So far the server has routes for people: pages and data that a user asks for. A health check route is a route for machines. The caller is not a person with a browser. It is a load balancer deciding where to send the next request, a container runtime deciding whether to restart a dying process, or a deployment platform deciding whether a new version is ready to take over. This page explains the idea behind that route, what it should and should not do, and how other systems read its answer.
Think of a nurse checking a patient's pulse. The check does not treat anything. It only reports whether the patient is alive and stable, and it does it often enough that a change is noticed quickly. A health check route is the server's pulse, and the systems that call it are the nurses.
The Smallest Working Version
The smallest health check is a route that always answers ok. Create a project with this Cargo.toml and this src/main.rs.
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
// src/main.rs
use axum::{routing::get, Router};
async fn health() -> &'static str {
"ok"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello!" }))
.route("/health", get(health));
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();
}
Run it and ask the route its question:
cargo run
curl http://127.0.0.1:3000/health
ok
The answer is one word, and the request finishes in a few milliseconds. That is the whole design in miniature: a route that is always there, always fast, and always honest about the one thing it reports. The exact response shape, JSON instead of plain text, and the status codes around it are the subject of the implementation page, and this page stays with the idea itself.
Working Setup:
If curl http://127.0.0.1:3000/health prints ok and returns at once, the route is live. If curl reports a connection error, the server is not running. If it reports a 404, the route was registered under a different path.
Why a Server Needs a Route for Machines
A person can tell a server is down because the page does not load. A machine cannot tell that by looking. It needs a way to ask, and it needs the answer to be machine-readable: a status code it can compare, and a body it can parse without guessing. The health check route is that way of asking. Without it, every system that watches the server has to guess at its health from side effects, like whether a TCP connection opens, which says nothing about whether the server can actually answer a request.
Three kinds of callers use the route, and each one wants something slightly different from it. A load balancer asks before sending each batch of traffic, and it wants a fast yes or no so it can route around a sick server. A container runtime asks on a schedule, and it wants to know whether to restart the process. A deployment platform asks during a rollout, and it wants to know whether the new version is ready before it sends it real users. One route serves all three, because all three ask the same question, just at different times and for different reasons.
The Concept Behind the Check
A health check is a probe, which is a small test sent from outside. The probe does not inspect the server's internals. It sends a normal HTTP request, exactly like a browser would, and reads the normal HTTP response. That outside-in view is the point. A server can believe it is healthy while being unable to answer a request, because its listener is bound but its handlers are stuck, or because its event loop is blocked. A probe catches that, because it measures what a caller actually experiences.
The probe has a timeout, usually a few seconds, and a schedule, usually every few seconds. Each probe is one data point. One failed probe does not condemn the server. Most systems wait for several failures in a row before acting, because a single slow answer can be a brief spike rather than a real failure. That patience is called the failure threshold, and it is set on the caller's side, not in the route. The route only answers. The caller decides what the answers mean.
A Probe Measures What a Caller Feels:
A health check that inspects the server from the inside, by reading a flag or a counter, can report healthy while the server is unable to answer a request. A probe sent from the outside measures the real thing: whether a request sent over the network gets an answer back. That outside-in view is why the route is an HTTP route and not an internal status flag.
A beginner can picture a lighthouse keeper flashing a lamp every few seconds. Ships do not steer by one flash. They steer by the pattern: regular flashes mean the lighthouse is working, and a long darkness means something is wrong. The health check route is the lamp, and the caller watches the pattern, not any single flash.
What a Good Health Answer Contains
A health answer has two parts: a status code and a body. The status code is the real answer, and the body is the detail. A healthy server answers with status 200, which means OK in HTTP, and a body that says so in words. An unhealthy server answers with status 503, which means Service Unavailable, and a body that says what is wrong. The caller reads the code first and the body only if it needs the detail.
The body should be small and fixed in shape. A single word, ok, is enough for a route that only reports aliveness. A small JSON object with one field, {"status": "ok"}, is enough for a route that a dashboard parses. The body should never contain a stack trace, a database error, or any detail that would help an attacker learn about the system. It should also never be large: a health answer that returns a megabyte of diagnostics on every probe wastes the bandwidth of the very systems trying to help.
| Status code | Meaning | When the route returns it |
|---|---|---|
| 200 OK | The server is alive and able to work | The normal answer, almost always |
| 503 Service Unavailable | The server is alive but cannot work | A dependency the server needs is down, and the server knows it |
The 503 case deserves care. A server that returns 200 while its database is down is lying, and the load balancer will keep sending it traffic it cannot serve. A server that returns 503 while its database is briefly slow is crying wolf, and the load balancer will pull a healthy server out of rotation. The route should only report what it has actually checked, and it should only check things it can check quickly and reliably. That boundary, between what the route checks and what it does not, is the hardest design decision on this page.
What the Route Should Check
A health check can report two different things, and beginners often mix them up. The first is aliveness: is the process running and able to answer a request? The second is readiness: is the process able to do useful work right now, including reaching its database? A route that only checks aliveness answers fast and almost always says yes. A route that checks readiness answers more slowly and says no whenever a dependency is down.
The smallest version on this page checks aliveness only, because it does nothing but return a fixed string. That is the right default for a first health check. It proves the process is up, the listener is bound, the router works, and the runtime is not stuck. Those four facts cover most real outages, because most outages are a crashed process or a hung runtime, and both make the aliveness check fail.
Checking a dependency belongs in the route only when the server genuinely cannot serve any request without that dependency, and only when the check itself is fast and cheap. A database ping that takes a few milliseconds qualifies. A query that scans a table does not. A check that calls another service over the network is a health check of that other service, not of this one, and it makes this server look sick whenever the other service has a bad minute. The rule is simple: the route reports on this server, not on the world around it.
A Health Check Must Never Do Real Work:
A health check that writes to the database, sends an email, or charges a card is not a health check. It is a side effect that runs every few seconds, forever, driven by a machine that does not know what it is triggering. Keep the route read-only, fast, and free of side effects, or the monitoring system becomes a source of load and damage.
What the Route Should Not Do
A health check route should not require authentication. The systems that call it, load balancers and container runtimes, do not have user accounts, and they cannot log in. A health route behind a login check always answers 401, which the caller reads as "unhealthy", and the server is pulled out of rotation or restarted forever. The route is public by design, and its safety comes from how little it reveals, not from a password.
It should not return different answers for different callers. A route that says ok to one IP address and 503 to another is not a health check, it is a guessing game, and no caller can trust it. It should not depend on the request body or on query parameters. A probe sends a plain GET with no body, and the route must answer that exact request.
It should not be slow. A health check that takes two seconds to answer makes every probe take two seconds, and a caller with a three-second timeout starts failing probes on a healthy server. Keep the handler trivial: return a fixed value, and do nothing else. If a dependency check is added, it must have its own short timeout, shorter than the probe timeout, so the route answers 503 quickly instead of hanging until the caller gives up.
Never Put Secrets in a Health Response:
A health response is fetched by machines, stored in logs, and sometimes shown on dashboards. Anything in the body can end up in a log file. Never include a database password, a token, a connection string, or an internal address in a health answer. The body should contain the word ok and nothing a stranger could use.
Where the Route Lives
The health check route lives in the same router as every other route, registered with the same .route call. It is not a separate server, not a separate port, and not a special mode. That matters, because a health check on a different port can report healthy while the main port is broken, and a check on a different server can report healthy while the real server is down. The probe must travel the same path a real request travels: the same listener, the same router, the same runtime.
Its path should be short, stable, and obvious. /health is the convention, and conventions matter here because the caller is often configured by a different person from the one who wrote the server. A platform that expects /health and finds nothing returns errors and pages someone at night. A path that changes between versions breaks every probe configured against the old one. Pick /health once, keep it forever, and do not move it.
How Callers Use the Answer
A load balancer keeps a list of healthy servers and sends each new request to one of them. When a server's health check starts failing, the balancer removes it from the list, so no new traffic reaches it. When the check starts passing again, the balancer adds it back. The server itself never knows this happened, except that its traffic drops to nothing and then returns. That is the point: the balancer protects users from a sick server without the server doing anything.
A container runtime uses the check to decide whether to restart the process. When the check fails several times in a row, the runtime kills the container and starts a fresh one. That restart is a blunt tool, and it only helps when the failure is a stuck process rather than a broken dependency. Restarting a server whose database is down just produces a fresh server whose database is still down, and the cycle repeats. The health route cannot fix that, but it can at least report the truth, so the operator sees the pattern in the logs.
A deployment platform uses the check to decide whether a new version is ready. It starts the new version, waits for the health check to pass, and only then sends it traffic and stops the old version. If the check never passes, the platform stops the rollout and keeps the old version running. That is the safest way to deploy, and it depends entirely on the health route answering honestly: a route that always returns 200 lets a broken version take traffic, and a route that is too strict blocks a good version from ever going live.
The Health Check Flow
The sequence below shows one probe from the caller's side, from the moment it decides to check to the moment it acts on the answer.
Caller waits for the next probe interval
|
v
Caller sends GET /health
|
v
Server routes the request to the health handler
|
v
Handler returns 200 and ok, or 503 and an error
|
v
Caller records the result
|
v
Caller acts only after several results in a row
The last step is the one beginners miss. A single result changes nothing. The caller waits for a pattern, several failures or several successes, before it routes traffic away or restarts a process. That patience is what keeps a brief spike from causing a restart, and it is why the route's job is to be honest on every single probe, not to be clever about which probes to fail.
Testing a Health Check Route
A health check is easy to test because it has no inputs and a fixed output. The test builds the router, sends a GET to /health without any network, and checks the status and the body.
// tests/health_test.rs
use axum::{
body::Body,
http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
#[tokio::test]
async fn health_returns_ok() {
let app = app();
let response = app
.oneshot(Request::builder().uri("/health").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
The test needs the app function to register the /health route, and it needs tower as a dev-dependency:
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
oneshot sends one request through the router without starting a server, which makes the test fast and free of port conflicts. The assertion checks the status code only, because the status code is the part the caller actually reads. A second assertion on the body, checking that it contains ok, is a useful addition, and it belongs in the same test.
Common Beginner Mistakes
Protecting the health route with authentication
// Wrong - the load balancer has no token, so it always gets 401
use axum::response::IntoResponse;
async fn require_token(request: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
if request.headers().get("authorization").is_none() {
return axum::http::StatusCode::UNAUTHORIZED.into_response();
}
next.run(request).await
}
let app = Router::new()
.route("/health", get(health))
.layer(axum::middleware::from_fn(require_token));
A health route behind an auth layer answers 401 to every probe, and the caller reads 401 as unhealthy. The server is pulled out of rotation within a minute of going live. The fix is to register the health route outside any auth layer, so it answers without a token, while the real routes stay protected.
Making the health check slow or heavy
// Wrong - a full table scan on every probe, every few seconds
async fn health(State(pool): State<PgPool>) -> &'static str {
let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
.fetch_one(&pool)
.await
.unwrap();
"ok"
}
A count over a whole table on every probe turns the monitoring system into a load generator. On a large table the probe takes seconds, and on a busy server the probes pile up behind each other. The fix is to check aliveness with a fixed answer, and if a database check is genuinely needed, to use the cheapest possible probe, a one-row select with a short timeout.
Returning 200 when the server cannot work
// Wrong - the database is down, but the route still says ok
async fn health() -> &'static str {
"ok"
}
This is only wrong when the route claims to check readiness. A pure aliveness route that returns ok while the database is down is honest: it reports that the process is alive, which is true. The mistake is in the claim, not the code. If the route is documented and configured as a readiness check, it must actually check the dependency, or it will send traffic to a server that cannot serve it. Decide which kind of check the route is, say so in one line of code or comment, and then make the code match the decision.
Using a different path on every deployment
A health route that lives at /health in development, /healthz in staging, and /api/v1/health in production forces every caller to be configured three times, and one of those configurations will be wrong. Pick one path, use it everywhere, and treat changing it as a breaking change, because for the systems that probe it, that is exactly what it is.
Final Complete Example
Here is the smallest version grown into a realistic shape: the same router as a real project, with the health route registered alongside the user-facing routes, and nothing else changed.
// src/lib.rs
use axum::{routing::get, Router};
pub fn app() -> Router {
Router::new()
.route("/", get(home))
.route("/health", get(health))
}
async fn home() -> &'static str {
"Welcome!"
}
async fn health() -> &'static str {
"ok"
}
// src/main.rs
use axum_project::app;
#[tokio::main]
async fn main() {
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"] }
Run it and probe it twice, once as a person and once as a machine would:
cargo run
curl http://127.0.0.1:3000/
curl http://127.0.0.1:3000/health
The first curl returns the welcome text. The second returns ok. Two routes, two audiences, one server, and the health route costs almost nothing to keep.
Summary
The single most important insight is that a health check route is a promise, not a feature. It promises the systems around the server that they can ask, at any time, whether the server is able to work, and get an honest answer in a fraction of a second. Everything else on this page follows from that promise: the answer must be fast, because the question is asked every few seconds; it must be public, because the asker has no account; it must be small, because the answer is read by machines and stored in logs; and it must be honest, because a lie sends traffic to a server that cannot serve it or pulls a healthy server out of rotation.
The decision framework that follows is one question: what does this route claim to check? If it claims aliveness, a fixed answer is correct, and the route stays trivial forever. If it claims readiness, the route must check the dependency it claims to check, quickly, with its own timeout, and answer 503 when the check fails. The concrete shape of that answer, the JSON body, the status code, and the handler that produces them, is the next thing to build, because a promise is only useful once it has a form the caller can read.