Health checks are an essential part of modern applications. They allow you to monitor whether your system is up, responsive, and connected to its dependencies such as databases, caches, or external services. A simple health check endpoint can help DevOps teams, load balancers, and monitoring systems detect issues early.
Without health checks, your system might fail silently. Requests could time out, users might experience outages, and automated scaling tools may not know when to replace unhealthy instances. Implementing health checks ensures that failures are detected quickly and addressed automatically.
// Program.cs
using Microsoft.Extensions.Diagnostics.HealthChecks;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHealthChecks()
.AddSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))
.AddUrlGroup(new Uri("https://api.example.com/health"), name: "ThirdPartyAPI");
var app = builder.Build();
app.MapHealthChecks("/health");
app.Run();ASP.NET health checks can include checks for SQL Server connectivity and third-party APIs. This ensures not only the application but also critical dependencies are healthy.
// build.gradle
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
// application.properties
management.endpoints.web.exposure.include=health
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
// Custom Health Indicator
@Component
public class ThirdPartyHealthIndicator implements HealthIndicator {
@Override
public Health health() {
try {
// Example: call third-party API
URL url = new URL("https://api.example.com/health");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
if (conn.getResponseCode() == 200) {
return Health.up().build();
}
} catch (Exception e) {
return Health.down().withDetail("error", e.getMessage()).build();
}
return Health.down().build();
}
} Spring Boot Actuator automatically checks database connectivity. You can also create custom health indicators for external APIs.
const express = require('express');
const mysql = require('mysql2/promise');
const fetch = require('node-fetch');
const app = express();
app.get('/health', async (req, res) => {
try {
// Check DB connection
const connection = await mysql.createConnection({ host: 'localhost', user: 'root', database: 'test' });
await connection.query('SELECT 1');
connection.end();
// Check third-party API
const response = await fetch('https://api.example.com/health');
if (!response.ok) throw new Error('Third-party API down');
res.json({ status: 'UP' });
} catch (error) {
res.status(500).json({ status: 'DOWN', error: error.message });
}
});
app.listen(3000, () => console.log('Server running on port 3000'));Express can integrate database checks using MySQL or PostgreSQL drivers and external API checks using libraries like node-fetch.
// pages/api/health.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import mysql from 'mysql2/promise';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
// DB Check
const connection = await mysql.createConnection({ host: 'localhost', user: 'root', database: 'test' });
await connection.query('SELECT 1');
connection.end();
// Third-party API check
const apiRes = await fetch('https://api.example.com/health');
if (!apiRes.ok) throw new Error('Third-party API unavailable');
res.status(200).json({ status: 'UP' });
} catch (error: any) {
res.status(500).json({ status: 'DOWN', error: error.message });
}
} Next.js allows health checks as API routes. You can integrate both database connectivity and third-party API availability checks.
from flask import Flask, jsonify
import mysql.connector
import requests
app = Flask(__name__)
@app.route('/health')
def health():
try:
# DB check
conn = mysql.connector.connect(host='localhost', user='root', password='secret', database='test')
cursor = conn.cursor()
cursor.execute("SELECT 1")
cursor.close()
conn.close()
# Third-party API check
r = requests.get('https://api.example.com/health')
r.raise_for_status()
return jsonify(status='UP')
except Exception as e:
return jsonify(status='DOWN', error=str(e)), 500
if __name__ == '__main__':
app.run(port=5000)Flask can easily perform SQL queries and external API requests inside the health check endpoint to ensure all critical services are reachable.
// routes/web.php
use IlluminateSupportFacadesDB;
use IlluminateSupportFacadesHttp;
Route::get('/health', function () {
try {
// DB Check
DB::select('SELECT 1');
// Third-party API check
$response = Http::get('https://api.example.com/health');
if ($response->failed()) {
throw new Exception('Third-party API down');
}
return response()->json(['status' => 'UP']);
} catch (Exception $e) {
return response()->json(['status' => 'DOWN', 'error' => $e->getMessage()], 500);
}
});In Laravel, you can use Eloquent or raw queries to validate database connectivity, and the built-in HTTP client to check third-party APIs.
# deployment.yaml
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 5
periodSeconds: 10
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 5
periodSeconds: 10Kubernetes uses liveness and readiness probes to determine if pods should be restarted or receive traffic. Point them to your health check endpoint.
# prometheus.yml
scrape_configs:
- job_name: 'myapp-health'
metrics_path: /health
static_configs:
- targets: ['localhost:8080']Prometheus can scrape health or metrics endpoints. Although health checks often return JSON, exposing Prometheus metrics alongside them provides detailed observability.
# Example AWS Target Group health check configuration HealthCheckPath: /health HealthCheckIntervalSeconds: 30 HealthCheckTimeoutSeconds: 5 HealthyThresholdCount: 5 UnhealthyThresholdCount: 2
AWS ALBs can use your health endpoint to automatically route traffic only to healthy instances. This ensures users aren’t affected by failing servers.
Health checks are critical for reliable systems. A basic health endpoint ensures that the application is alive, while advanced checks verify databases and third-party dependencies. Integrating these checks with Kubernetes, Prometheus, or AWS load balancers makes your system self-healing and highly observable. Without them, your application may appear to be running but silently fail to serve users. By implementing comprehensive health checks across frameworks and monitoring systems, you safeguard uptime, stability, and user experience.