Covers the ASP.NET Core health checks middleware: registering checks with AddHealthChecks, mapping endpoints, dependency checks, the three HealthStatus values, tags and filtering, and splitting liveness from readiness.
Health checks are a built-in ASP.NET Core feature that lets an orchestrator, load balancer or monitor ask the app "are you OK?" over HTTP. You register checks with builder.Services.AddHealthChecks(), each one an IHealthCheck that returns Healthy, Degraded or Unhealthy, and expose them with app.MapHealthChecks("/health"). By default Healthy and Degraded return 200 and Unhealthy returns 503. Degraded means "still serving, but something non-critical is slow or down" (a cache, an optional feature), so the instance stays in rotation while you get a signal.
Dependency checks (SQL Server, Redis, Service Bus) come from AddDbContextCheck<T>() or the community AspNetCore.HealthChecks.* packages, each with a short timeout. With tags and a Predicate you expose two endpoints:
The trade-off: more checks give more truth but make the endpoint slower and make it easier for a shared dependency to take every instance out at once.
"Health checks are ASP.NET Core's built-in way for something outside the app, like Kubernetes, Azure App Service, a load balancer or an availability test, to ask whether this instance is OK. I register checks with
AddHealthChecks(). Each check implementsIHealthCheckand returns aHealthCheckResultwith a status of Healthy, Degraded or Unhealthy plus an optional description and data. ThenMapHealthChecks("/health")adds an endpoint that runs the checks and returns 200 for Healthy or Degraded and 503 for Unhealthy, so the caller only needs the status code. Degraded is for 'working, but not at full strength', like Redis being down while I fall back to the database.For dependencies I don't write everything myself. There's
AddDbContextCheck<AppDbContext>()for EF Core, and the community AspNetCore.HealthChecks packages give me SQL Server, Redis, Azure Service Bus and many more. I give each one a timeout of a few hundred milliseconds, because the probe calling the endpoint has its own timeout and one hung connection must not make the whole instance look dead. I tag each check, for exampleready, and map two endpoints with a predicate:/health/liveruns no checks at all, and/health/readyruns only thereadychecks. Liveness answers 'is the process alive and able to answer HTTP?', so a restart would help if it fails. Readiness answers 'should this instance get traffic right now?', so it is fine for it to fail during start-up or while a cache warms.The mistake I see is putting the database check into liveness. When the database has a blip, every pod fails liveness, Kubernetes restarts all of them, and a short database problem becomes a full outage. Health checks should tell the truth about the instance, not about the whole world."
| Piece | What it does |
|---|---|
AddHealthChecks() |
Registers HealthCheckService and returns IHealthChecksBuilder |
AddCheck<T>(name, tags: ..., timeout: ...) |
Registers your own IHealthCheck with an optional per-check timeout |
AddDbContextCheck<T>() |
Runs CanConnectAsync on an EF Core context |
AspNetCore.HealthChecks.* |
Community checks: AddSqlServer, AddRedis, AddAzureServiceBusQueue ... |
MapHealthChecks(path, options) |
Endpoint that runs the selected checks |
HealthCheckOptions.Predicate |
Chooses which checks run for this endpoint |
ResultStatusCodes / ResponseWriter |
Customise status codes and the response body |
IHealthCheckPublisher |
Runs checks on a timer and pushes results somewhere (e.g. Application Insights) |
| Status | Default HTTP code | Meaning | What the caller does |
|---|---|---|---|
| Healthy | 200 | Everything this check cares about works | Nothing |
| Degraded | 200 | Serving, but slower or without a non-critical dependency | Keeps sending traffic; you alert or chart it |
| Unhealthy | 503 | Can't do its job | Readiness: stop routing to it. Liveness: restart it |
The overall result is the worst status of the checks that ran. You can change the mapping with ResultStatusCodes (for example, Degraded → 503 on a readiness endpoint if degraded really means "don't route here").
| Liveness | Readiness | |
|---|---|---|
| Question | Is the process stuck? | Can it serve requests now? |
| Typical checks | None, or an in-process check (e.g. a background loop's heartbeat) | Database, cache, required config loaded, warm-up done |
| On failure | Orchestrator restarts the container | Instance is removed from the load balancer, not restarted |
| Danger | Shared dependency here = mass restarts | Too strict = every instance out at once |
Two endpoints matter because the caller takes two different actions. With one endpoint you either restart instances that only needed draining, or never restart instances that are truly hung.
| Layer | Example value | Why |
|---|---|---|
Probe timeout (Kubernetes timeoutSeconds) |
2-3 s | The whole endpoint must answer within this |
Per-check timeout: |
300-500 ms | A hung dependency becomes Unhealthy/Degraded quickly instead of hanging the endpoint |
| Check work | SELECT 1, PING |
Probes run every few seconds on every instance |
A check that times out reports its failureStatus, so the endpoint still answers within the probe timeout. Under heavy load or thread-pool starvation even fast checks slow down, which is another reason liveness should do no I/O.
SELECT 1, short timeouts and, for expensive checks, cache results or use a publisher.RequireHost("*:8081") (a management port not exposed through the ingress) or RequireAuthorization()..DisableHttpMetrics() so probes don't skew your latency charts.On an API with [12] pods, the database check sat in the only health endpoint, which was used for both probes. A [40-second] Azure SQL failover made every pod fail liveness and restart at the same moment, turning a [40-second] blip into [6 minutes] of 503s while pods cold-started. Splitting /health/live (no checks) from /health/ready (database tagged ready, 500 ms timeout) meant the next failover only took pods out of rotation for the [40 seconds] it lasted.
Checks the candidate knows the ASP.NET Core health checks API and, more importantly, the different purposes of liveness and readiness.
Green flags
AddHealthChecks, MapHealthChecks, IHealthCheck and the three statuses with their status codesRed flags
GET /health/ready
│
▼
HealthCheckMiddleware (endpoint)
│ Predicate filters registrations by tag
▼
HealthCheckService.CheckHealthAsync()
│ runs selected checks IN PARALLEL, each in its own DI scope
│ each gets a CancellationToken (request aborted / per-check Timeout)
▼
HealthReport { Status = worst(entries), Entries, TotalDuration }
│
▼
ResultStatusCodes maps status → 200 / 503
ResponseWriter writes body (default: plain text "Healthy")
The default DefaultHealthCheckService creates a scope per check, so a check can inject scoped services such as a DbContext. If a check throws, the result is the registration's failureStatus (Unhealthy by default) with the exception attached, so one broken check does not crash the endpoint.
HealthCheckRegistration holds the name, factory, FailureStatus, Tags, and since .NET 7 a per-check Timeout, Delay and Period (used by the publisher). Set timeout: on slow dependency checks so a hung Redis connection can't make the whole endpoint hang past the probe timeout.
probe timeout (e.g. 1s)
└── endpoint must answer within it
└── each check timeout must be shorter (e.g. 500 ms)
A check should answer a yes/no question about this instance in milliseconds. Good examples:
BackgroundService writes lastHeartbeat; the liveness check fails if it is older than 2 minutes (the loop is stuck);startup tag);Bad examples: calling another service's health endpoint (cascades), running business queries, or checking things the instance can't fix.
AddHealthChecks() also registers an IHostedService that, when you add an IHealthCheckPublisher, runs checks every Period (default 30 s) after a Delay (default 5 s) and calls PublishAsync(report). Use this to send health as a metric or availability telemetry without anyone calling the endpoint.
| Caller | Uses |
|---|---|
| Kubernetes kubelet | livenessProbe, readinessProbe, startupProbe |
| Azure App Service | Health check feature: removes an instance after repeated failures (configurable) |
| Azure Container Apps | Liveness, readiness and startup probes |
| Azure Front Door / Application Gateway / Load Balancer | Health probes decide routing |
| Application Insights standard test | External availability from several regions |
Aspire's ServiceDefaults template maps /health (all checks) and /alive (checks tagged live) and, by default, only in Development, because exposing them publicly is a risk. That is a good reminder that you have to choose how to expose them in production.
dotnet new webapi, add AddHealthChecks().AddCheck("self", () => HealthCheckResult.Healthy(), tags: ["live"]) and map /health/live and /health/ready with predicates. Curl both.AddDbContextCheck<AppDbContext>(tags: ["ready"]), stop the database container and watch /health/ready go to 503 while /health/live stays 200.timeout: TimeSpan.FromMilliseconds(500) and see the result.ResponseWriter that writes JSON with each entry's status and duration, then protect it with RequireHost("*:8081").dotnet-counters monitor -n MyApi Microsoft.AspNetCore.Hosting while hitting /health/live in a loop, then add .DisableHttpMetrics() and compare.Liveness and readiness endpoints with a dependency check, a heartbeat check and a management-only detailed view.
// Program.cs (.NET 10). Packages: Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore,
// AspNetCore.HealthChecks.Redis
using System.Text.Json;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>();
builder.Services.AddSingleton<WorkerHeartbeat>();
builder.Services.AddHostedService<OrderWorker>();
builder.Services.AddHealthChecks()
// Liveness: only in-process state. Never a shared dependency.
.AddCheck<WorkerHeartbeatCheck>("worker-heartbeat", tags: ["live"])
// Readiness: what this instance needs to serve traffic.
.AddDbContextCheck<AppDbContext>("sql", tags: ["ready"])
// Optional dependency: Degraded keeps the instance in rotation.
.AddRedis(builder.Configuration.GetConnectionString("Redis")!, "redis",
failureStatus: HealthStatus.Degraded, tags: ["ready"],
timeout: TimeSpan.FromMilliseconds(500));
var app = builder.Build();
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("live")
}).DisableHttpMetrics();
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("ready")
}).DisableHttpMetrics();
// Detailed JSON only on the management port, never through the public ingress.
app.MapHealthChecks("/health/details", new HealthCheckOptions
{
ResponseWriter = WriteJsonAsync
}).RequireHost("*:8081");
app.Run();
static Task WriteJsonAsync(HttpContext context, HealthReport report)
{
context.Response.ContentType = "application/json";
var body = new
{
status = report.Status.ToString(),
totalMs = report.TotalDuration.TotalMilliseconds,
checks = report.Entries.Select(e => new
{
name = e.Key,
status = e.Value.Status.ToString(),
ms = e.Value.Duration.TotalMilliseconds,
error = e.Value.Exception?.GetType().Name // type only: no connection strings in output
})
};
return context.Response.WriteAsync(JsonSerializer.Serialize(body));
}
namespace Orders.Health;
using Microsoft.Extensions.Diagnostics.HealthChecks;
public sealed class WorkerHeartbeat(TimeProvider clock)
{
private long _lastTicks = clock.GetUtcNow().UtcTicks;
public void Beat() => Interlocked.Exchange(ref _lastTicks, clock.GetUtcNow().UtcTicks);
public TimeSpan Age => clock.GetUtcNow() - new DateTimeOffset(Interlocked.Read(ref _lastTicks), TimeSpan.Zero);
}
// Fails liveness if the background loop has stopped beating: a restart would actually help.
public sealed class WorkerHeartbeatCheck(WorkerHeartbeat heartbeat) : IHealthCheck
{
private static readonly TimeSpan MaxAge = TimeSpan.FromMinutes(2);
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
=> Task.FromResult(heartbeat.Age < MaxAge
? HealthCheckResult.Healthy()
: HealthCheckResult.Unhealthy($"Worker heartbeat is {heartbeat.Age.TotalSeconds:F0}s old"));
}
/health endpoint for both probes. Why it is wrong: the orchestrator takes two different actions (restart versus stop routing), so one answer can't be right for both: you either restart pods that only needed draining or never restart truly hung ones. It also means start-up warm-up and dependency blips trigger restarts. Instead: map /health/live and /health/ready with tag predicates.SELECT 1 / CanConnectAsync, short timeouts, or a publisher with a cached result.timeout: on each dependency check, shorter than the probe timeout.RequireAuthorization(), and never connection strings or exception messages in the output.failureStatus: HealthStatus.Degraded.Health checks are an API for machines, so design them around what the caller will do with the answer. A liveness failure leads to a restart, so it should only fail when a restart would help. A readiness failure removes traffic, so it should fail when this instance can't serve but others might. If a failure would apply to every instance at once, it usually isn't a health problem for the orchestrator to act on; it's an alert for a human.
| Check type | When it fits | Cost | When not to |
|---|---|---|---|
| No-op liveness | Most web APIs | None | When a background loop can hang silently: add a heartbeat check |
| Dependency in readiness | Hard dependency the instance can't serve without | A query per probe per pod | Shared dependency with no fallback across all pods: alert instead of draining everything |
| Degraded for optional dependency | Cache, recommendations, feature with fallback | Small | When degraded is really broken for users |
| Publisher (push) | Expensive checks, dashboards | Background timer | As the only liveness signal (orchestrator must call in) |
Measure it: track probe failures (kube_pod_container_status_restarts_total, readiness flaps) and check durations; a health endpoint that takes 400 ms is a smell.
A health check is an automated decision: the orchestrator or load balancer acts on it, so it must answer exactly the question the actor asks. Liveness asks "is this process stuck?", so the answer is a restart. It never checks shared dependencies. Readiness asks "should this instance get traffic now?" It checks warm-up and local essentials, not something every instance shares. Startup probes give slow starts time before liveness applies.
The classic failure is a database check in liveness or readiness: one database blip makes every instance fail together. You get a fleet restart or zero healthy backends, which turns a partial outage into a total one. In ASP.NET Core I use tagged checks mapped to separate endpoints, keep them cheap and time-boxed, and keep detailed output internal. Dependency health goes to monitoring and alerts, where a human decides.
Mostly no. Readiness should say whether this instance can serve traffic: started, warmed up, not shutting down. If it checks a shared database or another service, one dependency outage marks every pod unready, discovery removes them all, and a partial outage (some endpoints still worked, cached reads still worked) becomes a total one.
The trade-off is against the SLO: serving degraded responses usually costs less error budget than having zero ready pods.
A burst of 502s on every rollout is almost always a shutdown or start-up race, not a code bug. On termination, Kubernetes sends SIGTERM to the container and removes the pod from the Service endpoints at the same time, so the ingress keeps sending requests for a few seconds to a process that is closing. I fix it in layers, with numbers that must add up: a preStop sleep (about 10 s) so routing updates first; HostOptions.ShutdownTimeout sized from the measured p99.9 request duration (say 15 s) so in-flight requests drain; and terminationGracePeriodSeconds larger than both together (35 s). Then readiness probes that only pass when the app is warm and fail once ApplicationStopping fires, separate from liveness, plus maxUnavailable: 0. I also check keep-alive timeouts: if Kestrel closes idle connections before the proxy does, the proxy reuses a dead connection and returns 502. The trade-off is slightly slower deployments for zero dropped requests.
Last updated 23 Nov 2026.