Expose a status check so load balancers and orchestrators can route around an instance before it fails user requests.
A process can be alive — accepting TCP connections — while its database connection is exhausted or a critical dependency is unreachable. Without a real health signal, a load balancer keeps sending it traffic it can't actually serve, and every one of those requests fails.
The service exposes `/health` (or similar) that actively checks its critical dependencies — database connectivity, downstream APIs it can't function without — and returns healthy/unhealthy accordingly. The orchestrator or load balancer polls it on an interval and stops routing to instances that report unhealthy.
Rather than always returning 200, the endpoint actively verifies the database is reachable and reports failure honestly.
const db = {
async ping() {
// simulate an unreachable database
throw new Error("connection refused");
},
};
async function healthCheck() {
const checks = { database: false };
try {
await db.ping();
checks.database = true;
} catch {
checks.database = false;
}
const healthy = Object.values(checks).every(Boolean);
return {
status: healthy ? 200 : 503,
body: { status: healthy ? "healthy" : "unhealthy", checks },
};
}
const result = await healthCheck();
console.log(result.status, result.body);
// 503 { status: 'unhealthy', checks: { database: false } }