How to Build API Health Checks That Don't Lie
The AI briefing for Developers
Stay up to date with AI tools, model releases, and developer workflows that matter.
Weekly. Free. One click to leave.

- Premium Results
- Publish articles on SitePoint
- Daily curated jobs
- Learning Paths
- Discounts to dev tools
7 Day Free Trial. Cancel Anytime.
Most APIs have a health endpoint, and most of them lie. The classic version is a route that returns 200 OK with {"status":"ok"} no matter what. It proves that the Node.js process is running and that the router works. It says nothing about whether the API can actually serve a request, because the database, the cache and the third-party services the API depends on are never touched.
That kind of endpoint is worse than having none. The load balancer keeps sending traffic to a broken instance, the orchestrator never restarts it, and the dashboard stays green while users get errors. This guide shows how to build health checks that report what is really happening, how to keep them cheap and safe, and how to watch them from outside your own infrastructure.
Liveness, readiness and dependency health are different questions
A single "health" route usually tries to answer three different questions at once. It works better to separate them.
- Liveness: is the process stuck? If this fails, the right action is to restart the instance. It should only check things the process itself controls, such as whether the event loop responds. It must not fail because the database is down, or every instance will restart at the same time and make an outage worse.
- Readiness: can this instance serve traffic right now? If this fails, the load balancer should stop sending requests to it, but nothing needs to restart. This is where dependency checks belong.
- Dependency detail: which part is broken? A readiness check that only says "not ready" leaves the on-call engineer guessing. A short breakdown per dependency saves the first ten minutes of every incident.
Kubernetes formalizes the first two as liveness and readiness probes, and its documentation gives the same warning about liveness checks that depend on other services. The distinction is just as useful behind a plain load balancer or on a single VPS.
A readiness route that checks real dependencies
The example below uses Express 5 and PostgreSQL through node-postgres, plus one HTTP dependency: a recommendations service the API can live without. Install the two packages in an ES module project:
npm init -y
npm pkg set type=module
npm install express@5 pg
Step 1: Connect to the dependencies
// health.js
import express from "express";
import pg from "pg";
const app = express();
const pool = new pg.Pool({ connectionTimeoutMillis: 1000 });
// Without this listener, a database restart crashes the whole process.
pool.on("error", (err) => console.warn(`idle database client error: ${err.message}`));
const RECOMMENDATIONS_URL =
process.env.RECOMMENDATIONS_URL ?? "http://localhost:4000/healthz";
The pool.on("error") line is easy to forget and it matters here more than anywhere. When the database restarts, idle connections in the pool emit an error event. With no listener, Node.js treats it as unhandled and the process exits, so the outage your health check was supposed to report takes the API down with it. The node-postgres pool documentation calls this out for the same reason.
Step 2: Give every check its own timeout
function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`timeout after ${ms} ms`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
Without a timeout, a hung database connection makes the health endpoint hang too, and the caller sees a timeout instead of a clear answer. The clearTimeout() in finally matters on a route that gets called several times a second: without it, every successful check leaves a timer running in the background.
For HTTP dependencies, fetch() can enforce its own limit with AbortSignal.timeout(), which also cancels the request instead of just ignoring its result.
Step 3: Mark which dependencies are critical
const DEPENDENCIES = [
{
name: "database",
critical: true,
run: () => pool.query("SELECT 1"),
},
{
name: "recommendations",
critical: false,
run: async () => {
const res = await fetch(RECOMMENDATIONS_URL, {
signal: AbortSignal.timeout(1000),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
},
},
];
async function checkDependency({ name, critical, run }, ms = 1500) {
const started = performance.now();
try {
await withTimeout(run(), ms);
return { name, critical, ok: true, ms: Math.round(performance.now() - started) };
} catch (err) {
console.warn(`health check "${name}" failed: ${err.message}`);
return { name, critical, ok: false, ms: Math.round(performance.now() - started) };
}
}
SELECT 1 is the lightest possible round trip: it proves the connection works without touching any table. The critical flag decides what a failure means. The API can't serve requests without its database, but it can still serve most of them without recommendations. Error messages go to the log, not into the response.
Step 4: Cache the result for a few seconds
const CACHE_MS = 3000;
let cached = null;
function getReadiness() {
const now = Date.now();
if (!cached || now - cached.at > CACHE_MS) {
cached = {
at: now,
results: Promise.all(DEPENDENCIES.map((dep) => checkDependency(dep))),
};
}
return cached.results;
}
The checks run in parallel with Promise.all, so the endpoint takes as long as the slowest dependency rather than the sum of all of them. Caching the promise, not the finished result, has a useful side effect: if ten load balancer probes arrive while a check is still running, all ten wait for the same check instead of starting ten more.
Step 5: Turn the results into a status code
// Liveness: the process answers. No dependencies here.
app.get("/healthz", (req, res) => {
res.set("Cache-Control", "no-store");
res.json({ status: "ok" });
});
// Readiness: can this instance do real work?
app.get("/readyz", async (req, res) => {
const results = await getReadiness();
const checks = Object.fromEntries(
results.map((r) => [r.name, r.ok ? "ok" : "fail"])
);
const criticalDown = results.some((r) => r.critical && !r.ok);
const anyDown = results.some((r) => !r.ok);
res.set("Cache-Control", "no-store");
res.status(criticalDown ? 503 : 200).json({
status: criticalDown ? "unavailable" : anyDown ? "degraded" : "ok",
checks,
version: process.env.APP_VERSION ?? "dev",
});
});
app.listen(3000, () => console.log("Listening on http://localhost:3000"));
The route can answer in three ways:
200** with **"status": "ok"when every dependency works.200** with **"status": "degraded"when only an optional dependency fails. The instance stays in rotation, and the body tells you what's wrong.503 Service Unavailable** with **"status": "unavailable"when a critical dependency fails. Load balancers and most monitors look at the status code first, so this is what takes the instance out of rotation.
Here is what the route returned while the database was stopped and started again during testing:
# all dependencies up
{"status":"ok","checks":{"database":"ok","recommendations":"ok"},"version":"dev"} [200]
# database stopped
{"status":"unavailable","checks":{"database":"fail","recommendations":"ok"},"version":"dev"} [503]
# database back, recommendations service down
{"status":"degraded","checks":{"database":"ok","recommendations":"fail"},"version":"dev"} [200]
Throughout the outage, /healthz kept answering 200, which is exactly what you want: nothing restarted, the instance just left the load balancer pool until the database came back.
Keep it cheap, fast and safe
A health endpoint is called constantly by load balancers, orchestrators and monitors, often several times a second across a fleet. That changes how you should write it.
- Use the lightest possible check per dependency. A ping or a trivial round trip such as
SELECT 1proves a connection works. Never run a real business query, a full table count or anything that takes locks. - Keep timeouts below the caller's timeout. If the load balancer gives up after 2 seconds, a 5-second dependency timeout means it never sees your answer. The example uses 1.5 seconds for that reason.
- Cache the result for a few seconds. Two to five seconds removes most of the load without hiding real failures for long.
- Don't leak internals. Hostnames, connection strings, stack traces and library versions don't belong in a public response. The example logs error messages and returns only
okorfailper dependency. An application version like theversionfield is usually fine to expose and helps confirm which deploy is live, but leave it out if you treat release numbers as sensitive. For rich diagnostics, use a separate route behind authentication. - Only hard dependencies should flip readiness to
503. Treat everything else as degraded, so a flaky optional service can't take every instance out of rotation at once. - Exclude the route from auth and rate-limit middleware that could fail for reasons unrelated to health, but do rate limit it at the edge if it's reachable from the internet.
Why internal checks are not enough
Everything above runs inside your infrastructure. The load balancer calls the instance over a private network, and the orchestrator calls it on localhost. That means a whole class of failures stays invisible to them:
- An expired or misconfigured TLS certificate on the public endpoint.
- A DNS change that points the public hostname at the wrong place.
- A firewall or security group rule that blocks traffic from outside.
- A CDN or reverse proxy that returns errors or stale responses while the origin is fine.
- Latency that only appears on the public path, for example after a routing change.
Users see all of these as "the API is down", while every internal probe reports green. The only way to catch them is to call the endpoint the way a client does: over the public internet, through DNS, TLS and every proxy in between.
Monitoring the endpoint from the outside
An external monitor should do more than check for a 200. Because the readiness route returns structured JSON, the monitor can assert on the value that matters instead of the status code alone. Most uptime tools that support API checks let you do this. With an API uptime monitor, for example, you can send the same headers a real client would, including an Authorization header if the route is protected, and require that the JSON path checks.database equals ok. If the value changes, or the body stops being valid JSON, the check fails even when the status code still looks fine.
This is also where the degraded state pays off. An internal load balancer ignores it, because the instance still answers 200. An external monitor that asserts on checks.recommendations can still warn you that an optional service has been failing for an hour.
A few settings are worth getting right whichever tool you use:
- Confirm before alerting. A single failed request can be a blip. Re-check after a short delay and only open an incident when the failure repeats.
- Warn on response time, not only on failure. If time to first byte creeps from 80 ms to 900 ms, clients with short timeouts start failing before the endpoint ever returns an error.
- Validate the full certificate chain. Browsers can often fetch a missing intermediate certificate on their own, but many HTTP clients and SDKs can't, so a chain that looks fine in a browser can still break API clients.
- Send alerts where the team already works, such as Slack, Discord or a webhook into your incident tooling, rather than an inbox nobody watches at night.
When you're debugging and just want a one-off answer, it also helps to check the URL from outside your own network before assuming the problem is in your code. If the public request fails while a request from inside the cluster succeeds, you can skip straight to DNS, TLS and the proxy layer.
A short checklist
- Separate liveness from readiness, and keep liveness free of dependencies.
- Give every dependency check its own timeout, shorter than the caller's, and run the checks in parallel.
- Handle connection-pool errors, so a database restart can't crash the process.
- Return
503only when a critical dependency fails, report optional ones as degraded, and include a per-dependency breakdown in the body. - Cache results for a few seconds and never expose secrets or stack traces.
- Monitor the public endpoint from outside, assert on the JSON value, and alert on slow responses as well as failures.
A health endpoint is a promise to everything that calls it. Make it a promise you keep, and the next outage will announce itself in seconds instead of in a support ticket.

