.NET Development
Health checks in ASP.NET Core: liveness, readiness and what Kubernetes does
A health check is a question an application asks itself, "can I serve requests right now?", and whose answer it publishes at a URL. A person does not read it: the orchestrator and the load balancer do, and they use that answer to decide whether to restart the process or stop sending it traffic. ASP.NET Core ships them built in: AddHealthChecks registers the checks and MapHealthChecks publishes them on a route.
A live process that cannot serve
A process can keep running with its database down, with startup half done or while waiting on an external service that does not answer. For whoever sends it requests, an application that runs but cannot serve is the same as an application that is down. That is why health checks split two questions: whether the process is alive (liveness) and whether it can take traffic (readiness).
An example outside software: a supermarket checkout. The cashier can be at the till with the lane closed because the till ran out of change. The cashier is alive, but not ready. Nobody replaces the cashier for that; customers are sent to another lane until someone brings coins. Kubernetes does the same with an instance that is not ready: it takes the instance out of the traffic rotation without restarting it.
A health check does not explain why something is slow; logs, metrics and traces do. The difference between those signals is covered in observability vs monitoring.
Why it was created
ASP.NET Core 2.2, released on December 4, 2018, brought a health checks service designed for environments such as Kubernetes. The Entity Framework Core (EF Core) check comes in a separate package, Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore.
Healthy, Degraded and Unhealthy
Each check returns one of three states. The state of the whole report is the state of the worst check: if any check is Unhealthy, the total is Unhealthy; otherwise, if any is Degraded, the total is Degraded. If every check is Healthy, or the route runs no checks at all, the total is Healthy. The middleware turns that total into an HTTP status code:
| State | Default status code | How Kubernetes reacts to an httpGet probe |
|---|---|---|
| Healthy | 200 | success |
| Degraded | 200 | success: the instance keeps receiving traffic |
| Unhealthy | 503 | failure; after three in a row, readiness takes the Pod out of the Service and liveness restarts the container |
Kubernetes counts an HTTP probe as passed with any status code from 200 to 399, and it decides on the status code alone: it does not read the JSON or the text of the body. For Degraded to return a different code, ResultStatusCodes in HealthCheckOptions has to change, and the dictionary must hold all three states; if one is missing, an InvalidOperationException is thrown.
Liveness, readiness and startup: three probes, three reactions
Kubernetes calls a probe the periodic request that the kubelet, the agent on each node, makes to a container. There are three, and each one triggers a different reaction when it fails failureThreshold times in a row:
| Probe | Question | On failure | Route in the sample |
|---|---|---|---|
| startup | has it finished starting? | the kubelet kills the container; until it passes, the other two do not run | /health/startup |
| liveness | is it alive? | the kubelet restarts the container | /health/live, no checks |
| readiness | can it take traffic? | the Pod leaves the EndpointSlices of its Services; the container keeps running | /health/ready |
The defaults for each probe are one request every 10 seconds (periodSeconds), 1 second of waiting (timeoutSeconds) and three failures in a row before reacting (failureThreshold). What a Pod and a Service are is explained in Docker vs Kubernetes.
Liveness must not look at dependencies: if it checks the database and the database goes down, Kubernetes restarts every instance, and a restart does not fix the database. The Kubernetes documentation warns that a badly implemented liveness probe can lead to cascading failures. The Microsoft Learn sample leaves liveness with no checks: if the process answers HTTP, it is alive. Dependencies belong in readiness, which, according to Kubernetes, can additionally check that each required service is available.
The code: three checks and four routes
The sample is an orders service on .NET 10, tested with SDK 10.0.401 and ASP.NET Core 10.0.12, with three checks: startup fails until the startup work has finished, database checks the database connection through EF Core and payments-api calls an external payments service. All three carry the ready tag, startup also carries the startup tag, and each route picks which checks it runs with a filter (Predicate). One list of checks serves four routes: liveness runs none, startup runs only the warm-up one, readiness runs the ones tagged ready and the JSON report runs them all, only on the management port.
src/HealthChecksDemo/Program.cs:
using HealthChecksDemo;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;
var builder = WebApplication.CreateBuilder(args);
// Port that serves the detailed JSON report. The middleware compares it with the local port
// of the connection, not with the Host header, so a client cannot pick it by sending a header.
// appsettings.json binds this port to localhost only; the public port listens on every interface.
int managementPort = builder.Configuration.GetValue("Management:Port", 8081);
string databasePath = Path.GetFullPath(
builder.Configuration.GetValue("Orders:DatabasePath", "data/orders.db")!,
builder.Environment.ContentRootPath);
Directory.CreateDirectory(Path.GetDirectoryName(databasePath)!);
string sqlite = new SqliteConnectionStringBuilder { DataSource = databasePath }.ToString();
builder.Services.AddDbContext<OrdersDb>(options => options.UseSqlite(sqlite));
builder.Services.AddSingleton<StartupGate>();
builder.Services.AddHostedService<WarmUpService>();
PaymentsOptions payments = builder.Configuration.GetSection("Payments").Get<PaymentsOptions>() ?? new PaymentsOptions();
builder.Services.AddSingleton(payments);
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<PaymentsHealthCache>();
// A base address without a trailing slash would drop its last segment: ".../v1" + "status" -> ".../status".
string paymentsBase = payments.BaseUrl.EndsWith('/') ? payments.BaseUrl : payments.BaseUrl + "/";
builder.Services.AddHttpClient(PaymentsApiHealthCheck.ClientName, client => client.BaseAddress = new Uri(paymentsBase));
builder.Services.AddHealthChecks()
// Fails until the warm-up work has finished. Runs on /health/startup and /health/ready.
.AddCheck<StartupHealthCheck>("startup", tags: ["startup", "ready"])
// EF Core check: calls Database.CanConnectAsync on OrdersDb.
.AddDbContextCheck<OrdersDb>("database", tags: ["ready"])
// A payments outage reports Degraded, not Unhealthy, so it does not take every instance
// out of the load balancer at once. The timeout cancels the call after CheckTimeoutMs.
.AddCheck<PaymentsApiHealthCheck>(
"payments-api",
failureStatus: HealthStatus.Degraded,
tags: ["ready"],
timeout: TimeSpan.FromMilliseconds(payments.CheckTimeoutMs));
// AddDbContextCheck has no timeout parameter, so the registration's Timeout is set here.
// On a timeout the EF Core check reports Unhealthy (results/contracts.txt, K9).
int databaseTimeoutMs = builder.Configuration.GetValue("Orders:CheckTimeoutMs", 800);
builder.Services.PostConfigure<HealthCheckServiceOptions>(options =>
options.Registrations.Single(r => r.Name == "database").Timeout = TimeSpan.FromMilliseconds(databaseTimeoutMs));
var app = builder.Build();
// Liveness: runs no checks. It answers 200 "Healthy" while the process can serve HTTP.
app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });
// Startup: runs only the "startup" check. 503 until the warm-up has finished, then 200.
app.MapHealthChecks("/health/startup", new HealthCheckOptions
{
Predicate = registration => registration.Tags.Contains("startup"),
});
// Readiness: runs the checks tagged "ready". Unhealthy -> 503; Healthy and Degraded -> 200 (defaults).
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = registration => registration.Tags.Contains("ready"),
});
// Every check with a JSON body, only for connections that arrived on the management port.
app.UseHealthChecks("/health/details", managementPort, new HealthCheckOptions
{
ResponseWriter = HealthReportJson.WriteAsync,
});
app.MapGet("/orders/count", async (OrdersDb db, CancellationToken ct) => await db.Orders.CountAsync(ct));
app.Run();
// Lets the test project start the app with WebApplicationFactory<Program>.
public partial class Program;
The timeout cancels the payments check after 800 ms, the value of CheckTimeoutMs in appsettings.json. While the startup work runs, liveness returns 200 Healthy, and startup and readiness 503 Unhealthy; when it finishes, both turn 200 Healthy. The Kubernetes probes for this application, taken from the repository README:
startupProbe:
httpGet: { path: /health/startup, port: 8080 }
periodSeconds: 5
failureThreshold: 30
livenessProbe:
httpGet: { path: /health/live, port: 8080 }
periodSeconds: 10
timeoutSeconds: 1
failureThreshold: 3
readinessProbe:
httpGet: { path: /health/ready, port: 8080 }
periodSeconds: 5
timeoutSeconds: 1
failureThreshold: 3
The startup probe points to /health/startup, so it waits for the startup work; its 30 attempts leave room for a slow startup, and if that work hangs, the kubelet kills the container after the last failure. These are sample values: Kubernetes only sets the defaults, and this configuration was not tested on a cluster.
In appsettings.json, the public port listens on every interface (http://+:8080), because the kubelet calls the Pod IP: with localhost, no probe would get through. The management port listens only on localhost:8081.
results/.Database check
AddDbContextCheck<OrdersDb> registers a check that calls EF Core's Database.CanConnectAsync. If a custom query is used instead, Learn asks for one that returns quickly, because running it on every probe can overload the database. The EF Core check does not always honor the registration's failureStatus: if the query throws or the timeout expires, it returns Unhealthy even when it was registered with Degraded. The repository tests, with failureStatus: HealthStatus.Degraded and SQLite:
- With the database file missing,
CanConnectAsyncreturns false and the check reports Degraded, as requested. The check does not create the file. - With a test query that throws, it reports Unhealthy, and the description carries the database message: "SQLite Error 1: 'no such table: MissingTable'."
- With a 300 ms timeout and a query that takes 5 seconds, it reports Unhealthy with the description "A task was canceled."
The source code of DbContextHealthCheck explains the difference: it catches any exception, the timeout cancellation included, and returns Unhealthy with its message. AddDbContextCheck has no timeout parameter either; the sample sets it to 800 ms with PostConfigure (Orders:CheckTimeoutMs). In the sample this changes nothing, because the database is registered with the default state, Unhealthy; it matters to anyone who registers this check with Degraded. SQLite reads a local file, so these tests do not measure a database check over the network.
External service check
PaymentsApiHealthCheck calls GET {BaseUrl}status: a 2xx status code is Healthy; any other code or a connection error gives the registration's FailureStatus, Degraded. Without a trailing slash in BaseUrl, the relative path would replace the last segment of the URL and the check would call a different route; that is why Program.cs adds it when it is missing. With the payments service answering 500, readiness returned 200 Degraded; with the service hanging, it returned 200 Degraded after 0.8 seconds, when the timeout expired. To Kubernetes, that Degraded changes nothing: the payments check only reports, in the body and in the log, and adds time to the probe. If it must not take the Pod out, another option is to drop its ready tag and run it only in /health/details.
ASP.NET Core runs the checks again on every request to the route: there is no timer and no cache by default. Without a cache, 200 concurrent requests to /health/ready made 200 calls to the payments service. That is why the check keeps its last result for 10 seconds: with the cache, the same 200 requests made a single call. The price is a stale answer: with payments already failing, readiness kept returning Healthy until the 10 seconds had passed. Each replica has its own cache, so with several replicas payments receives up to one call per replica every 10 seconds while it answers. If it hangs, a call cancelled by the timeout is not cached, and every request to readiness calls payments again. Each of those timeouts writes the full exception trace to the log.
If the caller drops the connection, the middleware cancels the checks: in 5 requests dropped after 200 ms, the 5 calls to payments were cancelled after 0.2 seconds, before the 800 ms timeout expired. What to do with regular requests while payments reports Degraded is a different problem, the one the circuit breaker pattern solves.
The JSON response
By default, the middleware answers in plain text with the total state, even when the request asks for JSON with the Accept header. ASP.NET Core has no JSON format of its own because, according to Learn, each monitoring system asks for its own; the repository writes one with a ResponseWriter. With payments answering 500, /health/details returned this (durations show as _ so the output does not change between runs):
P3 details -> 200 {"status":"Degraded","totalDurationMs":_,"checks":[{"name":"startup","status":"Healthy","durationMs":_,"description":"warm-up finished"},{"name":"database","status":"Healthy","durationMs":_,"description":null},{"name":"payments-api","status":"Degraded","durationMs":_,"description":"payments-api answered 500"}]}
When a check fails with an exception, the repository's JSON shows only its type, for example failed with SqliteException. The message can carry SQL text, file paths or host names, like the SQLite one in the previous section.
Risks of a health check
A health check runs production code every few seconds, on every replica, and any cost or failure of the check repeats at that rate.
Exposing details
The report with every check tells which dependencies the application has and how they fail. The sample publishes it only on the management port with UseHealthChecks(path, port), which compares the local port of the connection. RequireHost("*:5393") looks like it does the same, but it reads the Host header, which the client chooses: a request to port 5392 with Host: localhost:5393 got 200 with RequireHost and 404 with the port filter. Learn warns that RequireHost can be spoofed and suggests checking HttpContext.Connection.LocalPort. The port filter is not authentication. In the sample, the management port listens only on localhost, so no other network address reaches it: from another address of the machine, the connection was refused. Inside the Pod, its containers and kubectl port-forward, which connects to the Pod's localhost, do reach it. If it is opened to every interface, it protects the report only if it is not published in the Service or the Ingress, and inside the cluster any Pod can reach it unless a NetworkPolicy closes it. That port also serves every route of the application, not just the report.
/health/live, /health/startup and /health/ready answer anyone who reaches the public port, with any HTTP method, because MapHealthChecks does not set the verb: POST, PUT and DELETE also get 200. Learn offers RequireAuthorization for these routes, and the kubelet does not obtain credentials: it can only add fixed headers, the ones configured in httpHeaders. The sample does not protect them.
Slow checks
The registration timeout only cancels the cancellation token. A check that blocks the thread without looking at the token ignores it: with a 300 ms timeout, a check that blocked for 1.5 seconds took 1.5 seconds and came out Healthy. Meanwhile it holds a thread pool thread on every probe.
In a simulation of the kubelet's documented rules, not on a cluster, with the payments service hanging:
- with the check at 800 ms, readiness returned
200 Degradedafter 0.8 seconds and the probe passed on all four attempts; - with the check at 2 seconds, the probe ran out of its one second of waiting three times in a row and the Pod left the Service endpoints.
Liveness passed in both cases. The tests run on a single machine: with 800 ms, 0.2 seconds are left for the network between the node and the container, and the repository did not measure that latency.
timeoutSeconds. Otherwise the probe fails before the check answers, and Kubernetes takes the Pod out of the Service over a dependency the check was about to report as Degraded.Load on the dependencies
The rate limiting in ASP.NET Core sample keeps its health route outside the limiter because it does not query the database; a readiness route that calls the database or another service is no longer a cheap route.
What is left out
Three neighboring pieces are left out of the sample:
- Graceful shutdown: the application does not turn "not ready" when it receives SIGTERM. Kubernetes stops sending regular traffic to a Pod when it deletes it, even without a readiness probe.
- Publishers: ASP.NET Core can run the checks in the background and send the result to a monitoring system, with an initial delay of 5 seconds and a period of 30 by default. It is a separate mechanism and does not change when the checks of a route run.
- Third-party checks: the AspNetCore.Diagnostics.HealthChecks library brings checks for SQL Server and other services. Microsoft does not maintain it.
Conclusion
A health check is worth the reaction it triggers: liveness with no dependencies, readiness with required dependencies as Unhealthy and shared ones as Degraded, and every timeout below the probe's. Before copying the sample, it pays to review what someone reaching the public port can see, who can reach the management port and how many calls each dependency receives with the real number of replicas.
References
- NippysoftLabs: aspnet-core-health-checks (github.com)
- Health checks in ASP.NET Core (learn.microsoft.com)
- Liveness, Readiness, and Startup Probes (kubernetes.io)
- DbContextHealthCheck.cs at v10.0.12 · dotnet/aspnetcore (github.com)
- What's new in ASP.NET Core 2.2 (learn.microsoft.com)
- .NET Observability with OpenTelemetry (learn.microsoft.com)
Tags
Share this post
Subscribe
Get the latest posts delivered right to your inbox.
Leave a comment