API health check endpoints: liveness vs readiness, and how to test what calls them
Most writing about health checks is about the server side: what /health should return. This post is about the other side, the code that calls them. That means a CI step that waits for the API before running tests, an uptime monitor, a Kubernetes probe or a load balancer. A health endpoint is only as good as whatever reads it, and that reader is rarely tested against a 503 or a probe that hangs.
The examples use three free endpoints at https://api.testingapis.com/api/health, which need no key and can be made to fail on demand. Every response below was captured on 3 December 2026.
Three health endpoints
$ curl -s https://api.testingapis.com/api/health
{"status":"healthy","uptimeSeconds":248710,"timestamp":"2026-12-03T16:48:52Z"}
$ curl -s https://api.testingapis.com/api/health/live
{"status":"alive"}
$ curl -s https://api.testingapis.com/api/health/ready
{"status":"ready","checks":[
{"name":"memory-store","status":"up","responseTimeMs":1},
{"name":"graphql","status":"up","responseTimeMs":3},
{"name":"websockets","status":"up","responseTimeMs":2}]}| Endpoint | Answers the question | Who asks |
|---|---|---|
/api/health | Is it up, and since when? | Humans, status pages, simple uptime monitors |
/api/health/live | Is the process running, or is it stuck? | The orchestrator, to decide whether to restart it |
/api/health/ready | Can it serve traffic right now? | The load balancer and deploy scripts, to decide whether to send requests |
Liveness vs readiness
The two probes sound alike, but a failure on each leads to a very different action.
| Liveness | Readiness | |
|---|---|---|
| What it checks | The process can answer HTTP at all | The things a request needs: database, cache, downstream services |
| Failure means | Restart the container | Stop sending traffic to it until it recovers |
| Should it call the database? | No | Yes, with a short timeout |
| Good response | 200 with a tiny body | 200, or 503 with the failing check named |
The usual mistake is to put a database query in the liveness check. Then a database blip fails liveness on every pod at once, Kubernetes restarts all of them, and a 30-second outage turns into several minutes of cold starts. The database is down whether you restart or not. Restarting only helps when the process itself is broken, such as a deadlock or a stuck event loop, and that is all liveness should check.
Readiness is where dependencies belong. A pod that can't reach the database should stop getting traffic, while its neighbours that can reach it keep serving. The checks array in the response above shows the useful shape: one entry per dependency, with its status and how long it took.
Make the probe fail on purpose
Every endpoint on the API takes two query parameters for this. ?error=CODE returns that status instead of the real response, and ?delay=N waits N seconds before answering (up to 10):
$ curl -s -i "https://api.testingapis.com/api/health/ready?error=503"
HTTP/1.1 503 Service Unavailable
content-type: application/json; charset=utf-8
x-simulated: true
{"status":503,"error":"Service Unavailable","message":"Simulated error. Use ?error={code} to test different status codes.","simulated":true}
$ curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" "https://api.testingapis.com/api/health/live?delay=3"
200 3.788161sBetween them you can test the four outcomes a probe reader has to handle:
| Outcome | URL | What the caller should do |
|---|---|---|
| Ready | /api/health/ready | Carry on |
| Not ready | /api/health/ready?error=503 | Wait and ask again; don't send traffic |
| Server error | /api/health/ready?error=500 | Treat as not ready, and log it: the health check itself is broken |
| Hung | /api/health/ready?delay=10 | Give up after a short timeout and count it as a failure |
A wait-for-ready script for CI
Integration tests that start right after a deploy will fail at random if the API is still warming up. A script that polls the readiness endpoint first fixes that, but only if it handles the slow case. A plain fetch has no timeout, so one hung request can block the pipeline until the CI job is killed. This version gives each attempt its own timeout and reports why it gave up:
const READY_URL = process.env.READY_URL ?? "https://api.testingapis.com/api/health/ready";
// Polls a readiness endpoint until it answers 200 or the deadline passes.
// Each attempt has its own timeout, so one hung request can't eat the whole budget.
export async function waitForReady(url = READY_URL, { deadlineMs = 30_000, attemptTimeoutMs = 2_000, intervalMs = 1_000 } = {}) {
const started = Date.now();
let last;
for (let attempt = 1; Date.now() - started < deadlineMs; attempt++) {
try {
const res = await fetch(url, { signal: AbortSignal.timeout(attemptTimeoutMs) });
const body = await res.json().catch(() => null);
if (res.status === 200) return { ready: true, attempts: attempt, checks: body?.checks ?? [] };
last = { reason: "not_ready", status: res.status, down: (body?.checks ?? []).filter((c) => c.status !== "up").map((c) => c.name) };
} catch (err) {
last = { reason: err.name === "TimeoutError" ? "timeout" : "unreachable", message: err.message };
}
await new Promise((r) => setTimeout(r, intervalMs));
}
return { ready: false, ...last };
}Testing the script against real failures
Each case points the script at a URL that behaves the way a real outage would. There is no mock server to write:
import { test } from "node:test";
import assert from "node:assert/strict";
import { waitForReady } from "./wait-for-ready.js";
const BASE = "https://api.testingapis.com/api/health";
test("a ready service passes on the first attempt", async () => {
const r = await waitForReady(`${BASE}/ready`);
assert.equal(r.ready, true);
assert.equal(r.attempts, 1);
assert.ok(r.checks.every((c) => c.status === "up"));
});
test("a 503 is reported as not ready, with the status", async () => {
const r = await waitForReady(`${BASE}/ready?error=503`, { deadlineMs: 3_000 });
assert.deepEqual([r.ready, r.reason, r.status], [false, "not_ready", 503]);
});
test("a hung probe is a timeout, not a crash", async () => {
const r = await waitForReady(`${BASE}/ready?delay=5`, { deadlineMs: 4_000, attemptTimeoutMs: 1_500 });
assert.deepEqual([r.ready, r.reason], [false, "timeout"]);
});
test("a wrong host is unreachable", async () => {
const r = await waitForReady("https://health.invalid/ready", { deadlineMs: 1_500 });
assert.deepEqual([r.ready, r.reason], [false, "unreachable"]);
});$ node --test wait-for-ready.test.js
✔ a ready service passes on the first attempt (1251.7447ms)
✔ a 503 is reported as not ready, with the status (3869.4041ms)
✔ a hung probe is a timeout, not a crash (5031.6106ms)
✔ a wrong host is unreachable (1515.892ms)
ℹ tests 4
ℹ pass 4
ℹ fail 0| Test | The bug it catches |
|---|---|
| Ready on first attempt | A script that always sleeps first and slows every pipeline |
| 503 is not ready | Treating any response as success, or crashing on a non-JSON body |
| Hung probe | No per-request timeout, so the job hangs until CI kills it |
| Wrong host | A DNS error reported as "not ready", which sends you looking at the wrong thing |
The hung-probe test takes about five seconds, not four: the last attempt started inside the deadline and ran its full 1.5-second timeout. That is the cost of a per-attempt timeout, and the reason to keep it short.
A readiness report in Python
Standard library only. It prints each check and exits non-zero when the service isn't ready, so it works as a CI step or a cron job:
import json
import sys
import urllib.error
import urllib.request
BASE = "https://api.testingapis.com/api/health"
def probe(path, timeout=2):
try:
with urllib.request.urlopen(BASE + path, timeout=timeout) as r:
return r.status, json.load(r)
except urllib.error.HTTPError as e:
return e.code, json.load(e)
except (urllib.error.URLError, TimeoutError) as e:
return None, {"error": str(getattr(e, "reason", e))}
for path in ["/live", "/ready", "/ready?error=503", "/ready?delay=5"]:
status, body = probe(path)
checks = ", ".join(f"{c['name']}={c['status']}" for c in body.get("checks", []))
print(f"{path:18} {status} {checks or body.get('error') or body.get('status')}")
status, _ = probe("/ready")
sys.exit(0 if status == 200 else 1)$ python health.py
/live 200 alive
/ready 200 memory-store=up, graphql=up, websockets=up
/ready?error=503 503 Service Unavailable
/ready?delay=5 None The read operation timed outurlopen raises HTTPError for a 503, so the error body has to be read from the exception. A script that only catches URLErrorreports a 503 as "unreachable", which hides the more useful message.
Probe settings in Kubernetes
The same split in a pod spec, for your own service. The numbers are where the tests above help: timeoutSeconds has to be longer than your slowest healthy readiness check, and failureThreshold × periodSeconds is how long a hang lasts before anything happens.
containers:
- name: api
image: example/api:1.4.2
startupProbe: # gives a slow boot time before liveness starts counting
httpGet: { path: /api/health/live, port: 8080 }
periodSeconds: 5
failureThreshold: 24 # up to 2 minutes to start
livenessProbe: # failing this restarts the container
httpGet: { path: /api/health/live, port: 8080 }
periodSeconds: 10
timeoutSeconds: 2
failureThreshold: 3
readinessProbe: # failing this only takes the pod out of the Service
httpGet: { path: /api/health/ready, port: 8080 }
periodSeconds: 5
timeoutSeconds: 2
failureThreshold: 2Try your readiness timeout against ?delay=: if /api/health/ready?delay=3 still counts as healthy in your monitor, your timeout is longer than you think.
GET or HEAD?
Some uptime monitors send HEAD requests to save bandwidth. Not every health endpoint accepts them. Here, /api/healthdoes and the other two don't:
$ curl -s -o /dev/null -w "%{http_code}\n" -I https://api.testingapis.com/api/health
200
$ curl -s -o /dev/null -w "%{http_code}\n" -I https://api.testingapis.com/api/health/ready
405A monitor set to HEAD would report the readiness endpoint as down while it is fine. Check the method your monitor uses, or point it at GET. The same applies to your own service: if you want HEAD to work, test it, because many frameworks only route it when you ask them to.
Common health check mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Dependencies in liveness | A database blip restarts every pod | Liveness checks the process only |
Returning 200 with {"status":"down"} | Load balancers and monitors read the code, not the body, and keep sending traffic | Answer 503 when not ready |
| No timeout on the caller | A hung probe hangs the deploy | A timeout on every attempt, plus an overall deadline |
| Slow readiness checks | Probes time out under load and pods flap in and out | Time-box each dependency check; cache results for a second or two |
| Versions, hostnames or errors in a public health response | Free reconnaissance for anyone who asks | Keep the public response small; put detail behind auth |
| Monitor uses HEAD, endpoint only allows GET | False alarms at 3 a.m. | Match the method, and test it |
Questions
What should a health check endpoint return?
A status code first: 200 when healthy, 503 when not. A small JSON body helps humans: a status word and, for readiness, one entry per dependency, as in the example above. Monitors and load balancers mostly look at the code alone.
Is there a free health check endpoint to test a monitor against?
Yes. The three endpoints in this post need no key, and ?error=503 or ?delay=N make them fail when you want. For other status codes, see the HTTP status codes list, and for random latency and dropped connections, the failure injection API.
Should readiness fail when a non-critical dependency is down?
Only if the instance can't do its job without it. If the search service is down but checkout still works, report the search check as down in the body and keep answering 200. Otherwise one optional service can take your whole API out of the load balancer.
How do I test my retry logic against a failing service?
The resilience track covers timeouts, retries, backoff and circuit breakers with live endpoints, and the 503 handling guide does the same in C#.
The health endpoints, and GET /api, which lists every endpoint from the live route table, are in the catalog and health check reference.