Health Checks
Health checks expose signals that tell orchestrators, load balancers, and monitoring systems whether an application is alive, ready to serve traffic, and has access to its dependencies.
Overview
Health endpoints are control-plane contracts, not generic diagnostics. Liveness answers whether the process is irrecoverably stuck and should restart; it must not fail merely because a dependency is unavailable. Readiness answers whether this instance should receive new traffic and may include only dependencies required for serving that traffic. Startup protects slow initialization from premature liveness failures. ASP.NET Core registers IHealthCheck implementations and uses tags and predicates to expose separate endpoints. Checks need short cancellation-aware timeouts, bounded concurrency, stable sanitized output, and failure status chosen from operational consequences. Cache expensive results where appropriate, secure detailed dashboards, and test probe timings against deployment grace periods. A misdesigned probe can create restart loops or synchronized dependency load during the incident it was meant to diagnose.
What you will learn
- Separate liveness, readiness, and startup semantics.
- Implement cancellation-aware dependency probes.
- Aggregate required and optional dependency status.
- Configure probe budgets with deployment behavior.
- Protect diagnostic output.
- Test transitions and failure consequences.
Prerequisites
- ASP.NET Core routing and dependency injection.
- Container or load-balancer probe fundamentals.
- Known required and optional dependencies.
When to use Health Checks
Good fit
- An orchestrator or load balancer needs an action signal.
- A dependency determines traffic readiness.
- Startup initialization needs a distinct grace window.
Choose another approach when
- Liveness performs every dependency query.
- A public endpoint exposes exception details.
- Checks trigger repairs or destructive side effects.
Key concepts
A lightweight process signal whose failure asks the orchestrator to restart this instance.
A traffic-admission signal that reflects whether the instance can serve its required workload.
An initialization gate that delays normal liveness and readiness evaluation for slow-starting applications.
A cancellation-aware component reports Healthy, Degraded, or Unhealthy plus controlled diagnostic data.
Registration tags let separate endpoints select only the checks appropriate for each consumer.
Required and optional dependencies map to different aggregate statuses and routing consequences.
Timeout, period, and failure threshold together define how quickly infrastructure reacts.
Machine-readable status supports automation while detailed diagnostics remain protected and sanitized.
Architecture
Kubernetes probes call dedicated health endpoints filtered by tag; the readiness endpoint checks real dependencies while the liveness endpoint stays lightweight, and the UI dashboard polls all endpoints for operator visibility.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The sample models startup state, required and optional dependencies, cancellation, and deterministic aggregate results without external infrastructure.
- 01Name consumers
List who calls each endpoint and what action they take.
- 02Separate signals
Keep process liveness distinct from startup and traffic readiness.
- 03Classify dependencies
Mark dependencies required, optional, or irrelevant to a route.
- 04Implement probes
Use short cancellation-aware checks with controlled result data.
- 05Aggregate status
Map required failures to Unhealthy and optional failures to Degraded.
- 06Configure timing
Align timeout, interval, threshold, startup grace, and shutdown drain.
- 07Secure and observe
Protect details, monitor transitions, and rehearse failure and recovery.
Code example
Checks are registered with tags, exposed on separate endpoints filtered by tag, and a custom database check demonstrates how to surface a real dependency result with diagnostic data.
using Microsoft.Extensions.Diagnostics.HealthChecks;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddHealthChecks()
// Liveness: trivial — if this fails the process is hung
.AddCheck("self", () => HealthCheckResult.Healthy(), tags: ["live"])
// Readiness: real dependencies
.AddNpgSql(
builder.Configuration.GetConnectionString("Database")!,
name: "database",
failureStatus: HealthStatus.Unhealthy,
tags: ["ready"])
.AddRedis(
builder.Configuration.GetConnectionString("Redis")!,
name: "cache",
failureStatus: HealthStatus.Degraded,
tags: ["ready"])
.AddCheck<MessageBusHealthCheck>("messaging", tags: ["ready"]);
var app = builder.Build();
// Liveness: lightweight, no dependency checks
app.MapHealthChecks("/health/live", new()
{
Predicate = check => check.Tags.Contains("live"),
ResponseWriter = WriteJsonResponse
});
// Readiness: all dependency checks
app.MapHealthChecks("/health/ready", new()
{
Predicate = check => check.Tags.Contains("ready"),
ResponseWriter = WriteJsonResponse
});
app.Run();
// Custom check: verifies a business-critical queue is reachable
public sealed class MessageBusHealthCheck(
IServiceBusClientFactory factory) : IHealthCheck
{
public async Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context, CancellationToken ct)
{
try
{
var client = factory.CreateAdminClient();
var props = await client.GetQueueRuntimePropertiesAsync(
"order-events", ct);
var data = new Dictionary<string, object>
{
["activeMessages"] = props.Value.ActiveMessageCount,
["deadLetterMessages"] = props.Value.DeadLetterMessageCount
};
return props.Value.DeadLetterMessageCount > 1000
? HealthCheckResult.Degraded("High dead-letter count", data: data)
: HealthCheckResult.Healthy(data: data);
}
catch (Exception ex)
{
return HealthCheckResult.Unhealthy(
"Service Bus unreachable", ex);
}
}
}
static Task WriteJsonResponse(HttpContext ctx, HealthReport report) =>
ctx.Response.WriteAsJsonAsync(new
{
status = report.Status.ToString(),
checks = report.Entries.Select(e => new
{
name = e.Key,
status = e.Value.Status.ToString(),
description = e.Value.Description,
data = e.Value.Data
})
});Testing strategy
Test the state transitions and the infrastructure action each status is meant to cause.
- Verify startup is unhealthy until initialization completes.
- Fail a required dependency and assert readiness.
- Fail an optional dependency and assert degradation.
- Prove cancellation reaches slow probes.
- Test endpoint tag selection.
- Rehearse probe timing during deploy and drain.
Security considerations
Health data can reveal architecture and credentials if responses are not deliberately constrained.
- Expose only status publicly.
- Protect detailed dashboards.
- Never return connection strings or exception stacks.
- Rate limit expensive diagnostic endpoints.
- Audit operator access.
Performance and scalability
Frequent probes from many replicas can become production load.
- Keep liveness dependency-free.
- Set short timeouts.
- Cache expensive readiness checks briefly.
- Avoid sequential slow probes.
- Measure probe latency and call volume.
Deployment and operations
Probe timings must match startup, traffic drain, and shutdown behavior.
- Set startup grace from measured startup.
- Remove readiness before shutdown.
- Keep liveness threshold tolerant of pauses.
- Version response contracts.
- Test rolling deployment and dependency outage.
Common problems and fixes
Pods restart during database outage.
Likely cause: Liveness checks the database.
Fix: Move dependency checks to readiness.
Traffic arrives before initialization.
Likely cause: No startup or readiness gate exists.
Fix: Report startup state until initialization completes.
Probe requests time out.
Likely cause: A dependency call ignores cancellation.
Fix: Apply a short timeout and propagate the token.
Probe creates database load.
Likely cause: Every caller runs an expensive query.
Fix: Use a cheap query and bounded caching.
Dashboard leaks internals.
Likely cause: Detailed output is public.
Fix: Authenticate details and return minimal public JSON.
Pod never receives traffic.
Likely cause: Readiness failure lacks component evidence.
Fix: Log sanitized per-check status and inspect thresholds.
Best practices
- Separate probe semantics.
- Keep liveness local.
- Tag checks by consumer.
- Classify dependency criticality.
- Honor cancellation.
- Sanitize public output.
- Bound probe cost.
- Rehearse deployment transitions.
Production checklist
- Consumers and actions are documented.
- Liveness is lightweight.
- Startup grace is measured.
- Readiness includes only required dependencies.
- Checks honor cancellation and timeout.
- Public output is sanitized.
- Probe timing matches drain behavior.
- Outage and rolling-deploy drills pass.
Common interview questions
Liveness versus readiness?
Liveness decides restart; readiness decides whether this instance receives traffic.
Why not put database checks in liveness?
A shared outage would restart every healthy process and can worsen recovery.
What is a startup probe for?
It grants initialization time before normal liveness and readiness thresholds apply.
How do tags help?
They let endpoints select different registered checks for different consumers.
When should a check return Degraded?
When an optional capability is impaired but core traffic can still be served.
Why must checks honor cancellation?
Probe infrastructure has a deadline and abandoned dependency calls consume resources.
Should health checks repair systems?
No; checks should observe and report, while controlled operators perform remediation.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Health Readiness Lab
A deterministic .NET 10 sample demonstrating startup state, required and optional dependency aggregation, degraded readiness, and cancellation-aware probes.
- Run
dotnet run --project src/HealthReadinessLab- Test
dotnet test HealthReadinessLab.slnx