Advertisement
Advanced ASP.NET Core, Health Checks

How would you implement a health check that reports Degraded (rather than a binary Healthy/Unhealthy) based on a performance threshold, like elevated database query latency?

Short answer

Measure the relevant metric (e.g., time a test query takes) inside CheckHealthAsync and compare it against defined thresholds, returning HealthCheckResult.Healthy() below a normal threshold, .Degraded() when elevated but still functional, and .Unhealthy() when it exceeds a…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Measure the relevant metric (e.g., time a test query takes) inside CheckHealthAsync and compare it against defined thresholds, returning HealthCheckResult.Healthy() below a normal threshold, .Degraded() when elevated but still functional, and .Unhealthy() when it exceeds a failure threshold entirely -- letting monitoring/alerting systems distinguish 'working but slow, investigate soon' from 'completely broken, page someone now,' since these two situations warrant very different responses.
public class DatabaseLatencyHealthCheck(AppDbContext db) : IHealthCheck {
    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default) {
        var sw = Stopwatch.StartNew();
        await db.Database.ExecuteSqlRawAsync("SELECT 1", ct);
        sw.Stop();

        return sw.ElapsedMilliseconds switch {
            < 100 => HealthCheckResult.Healthy($"{sw.ElapsedMilliseconds}ms"),
            < 1000 => HealthCheckResult.Degraded($"Slow: {sw.ElapsedMilliseconds}ms"),
            _ => HealthCheckResult.Unhealthy($"Very slow: {sw.ElapsedMilliseconds}ms")
        };
    }
}
Real-world example
An operations team's alerting distinguishes a Degraded database health status (query latency between 100ms-1s, triggering a low-priority Slack notification) from Unhealthy (over 1s, triggering an immediate on-call page), avoiding alert fatigue from paging on every minor latency blip while still catching genuine outages promptly.
Likely follow-ups
  • How should a load balancer or Kubernetes readiness probe treat a Degraded status differently from Unhealthy?
  • How do you avoid the health check's own overhead (running test queries) contributing meaningfully to database load?
Related topics