Intermediate LevelNode JS
How do you build production health check endpoints using process.uptime() and memory metrics?
❓ Interview Prompt: Build /health endpoints returning HTTP 200 with JSON payload containing process.uptime() (in seconds), process.memoryUsage(), and database connection status.
Production orchestrators (Kubernetes, AWS ALB) rely on HTTP '/health' endpoints to monitor service readiness and liveness:
Metrics to Expose:
•
'process.uptime()': Service running time in seconds.
•
'process.memoryUsage().heapUsed': Active heap RAM.
•
Database Connectivity: Health check query on DB connection pool.
Code Implementation Example
javascript
import http from 'node:http';
import mongoose from 'node:mongoose';
http.createServer(async (req, res) => {
if (req.url === '/health') {
const isDbConnected = mongoose.connection.readyState === 1;
const statusCode = isDbConnected ? 200 : 503;
res.writeHead(statusCode, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
status: isDbConnected ? 'UP' : 'DOWN',
uptimeSeconds: Math.floor(process.uptime()),
memoryHeapMB: (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)
}));
}
}).listen(3000);💡Building production health check endpoint in Node.js.
🎯 Interview Key Takeaway
Return 503 status on health check endpoints if critical database connections or downstream dependencies fail.
#health check#process.uptime#Kubernetes#Intermediate
Back to all Node JS Questions→