❤️ Is Your App Really Healthy?
App running but database down? Cache not responding? Health checks test dependencies. Perfect for load balancer readiness probes.
📝 Basic Setup
// Program.cs
builder.Services.AddHealthChecks()
.AddDbContextCheck()
.AddUrlGroup(new Uri("https://api.example.com"))
var app = builder.Build();
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = _ => false // Just checks if app is running
});
🎯 Custom Health Check
public class DatabaseHealthCheck : IHealthCheck
{
private readonly AppDbContext _db;
public DatabaseHealthCheck(AppDbContext db) => _db = db;
public async Task CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken)
{
try
{
await _db.Database.ExecuteSqlRawAsync("SELECT 1", cancellationToken);
return HealthCheckResult.Healthy("Database is responding");
}
catch (Exception ex)
{
return HealthCheckResult.Unhealthy("Database failed", ex);
}
}
}
// Register
builder.Services.AddHealthChecks()
.AddCheck("database_check", tags: new[] { "ready" });
✅ Health Check UI
- Install: AspNetCore.HealthChecks.UI
- Provides dashboard at /healthchecks-ui
- Shows history of health status changes
- Can send alerts on failure
“Load balancer kept sending traffic to app with dead database. Added health check. Load balancer now stops routing when DB fails. Zero downtime on DB maintenance.”
