Designing truthful health checks across a distributed estate: liveness vs readiness vs startup, which dependencies to check where, how probes cause cascading restarts and fleet-wide outages, and implementing, tuning and securing ASP.NET Core health checks.
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.
"I start from who acts on the check and what they do with the answer. Kubernetes restarts a container that fails liveness, and takes a pod out of the Service endpoints if it fails readiness. A load balancer such as Azure Front Door or Application Gateway stops routing to a backend that fails its probe. Those are automatic actions with no human involved, so the check must be true for this one instance, and acting on it must actually help.
So liveness only answers 'is this process able to make progress?' Can it respond at all, is the ThreadPool not deadlocked? It never checks the database. If it did, a 30-second database failover would fail liveness on every pod, Kubernetes would restart all of them, and you'd get a cold-start stampede against a database that's only just come back. Readiness is 'should I get traffic right now?' That covers warm-up done, caches primed and the instance not draining. I'm careful with shared dependencies there too. If all pods fail readiness together, the Service has zero endpoints, and clients get connection errors instead of the fast 503 your app could have returned. For example, at [company] [a readiness check on Redis took every pod out of rotation during a 2-minute Redis blip, and the whole API went dark instead of just losing caching]. [We moved Redis to a Degraded status reported to monitoring, and the next Redis incident caused slower responses, not an outage.]
The mistake I see is treating health checks as a monitoring dashboard. Rich dependency status is useful, but it belongs on an internal endpoint, scraped by monitoring, with alerts to humans. Probes stay cheap, time-boxed and boring."
| Check | Question | Who acts | Action on failure | Include | Never include |
|---|---|---|---|---|---|
| Liveness | Is this process stuck? | Kubernetes kubelet | Restart the container | Process responds; optionally a deadlock or watchdog check | Database, Redis, other services |
| Readiness | Send traffic here now? | Kubernetes Service, load balancer | Remove from rotation | Warm-up done, not draining, local resources | Dependencies shared by every instance (see below) |
| Startup | Has it finished starting? | Kubernetes kubelet | Delay liveness; restart if it never starts | Migrations checked, caches loaded | Anything slow that runs on every probe |
| Deep / dependency health | How are my dependencies? | Monitoring and on-call | Alert a human | Database, queues, third parties, with latency | Nothing automated should act on it |
SQL failover (30 s)
│
├─ liveness checks SQL ──► all 20 pods fail ──► kubelet restarts all ──► cold start
│ │
│ 20 pods × connection pool warm-up + JIT
│ ▼
│ SQL hit by a stampede the moment it returns
│
└─ readiness checks SQL ──► all pods NotReady ──► Service has 0 endpoints
└─► even cached reads now fail
| Dependency | Readiness? | Reason |
|---|---|---|
| Local warm-up (cache primed, model loaded) | Yes | Specific to the instance; fixing it needs time, not a restart |
| Draining during shutdown | Yes | Remove from rotation before stopping |
| Shared database / Redis / downstream API | Usually no; report Degraded to monitoring | Fails on all instances at once; removing them all helps nobody |
| A per-instance resource (local disk, sidecar) | Yes | Another instance may be healthy |
A 20-pod order API had liveness and readiness both checking SQL with a 5 s query timeout. Kubernetes' default 1 s probe timeout meant the checks failed under load even with SQL healthy. During a 40 s Azure SQL failover, every pod restarted. Recovery took 9 minutes because of a connection stampede. After splitting the checks (liveness self-only, readiness warm-up only, SQL on a monitored internal endpoint), the next failover caused 40 s of 503s on writes and no restarts.
Checks whether the candidate understands health checks as automated control loops and can stop them from turning a dependency blip into a fleet-wide outage.
Green flags
Red flags
A probe is a feedback loop that takes an automatic action. Control loops need the action to fix the condition being measured. Restarting a pod fixes a deadlocked process. It does not fix a database failover. If the action can't fix what the check measures, the check must not trigger that action.
periodSeconds: 10, timeoutSeconds: 1, failureThreshold: 3, successThreshold: 1.failureThreshold × periodSeconds (30 s by default) restarts the container.failureThreshold × periodSeconds greater than your worst start time.AddHealthChecks() registers HealthCheckService. Each MapHealthChecks endpoint runs the checks selected by its Predicate in parallel and aggregates the results: the worst status wins (Healthy < Degraded < Unhealthy). ResultStatusCodes maps the statuses to HTTP codes; by default Healthy and Degraded give 200 and Unhealthy gives 503.
GET /healthz/ready
└─ HealthCheckMiddleware
├─ Predicate: tags contains "ready"
├─ run selected IHealthCheck.CheckHealthAsync(context, ct) in parallel
├─ aggregate: worst status wins
└─ write status code + body (ResponseWriter)
IHealthCheckPublisher runs checks on a timer (HealthCheckPublisherOptions.Period) and pushes results somewhere, for example to Application Insights. That is the right place for dependency health.AddDbContextCheck<TContext>() (from Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore) calls CanConnectAsync, which is cheap but still a round trip.On SIGTERM, Kubernetes removes the pod from endpoints and signals the container at about the same time. The endpoint update takes a moment to reach every node and ingress, so a pod that stops immediately drops in-flight and newly routed requests. The fix is to flip readiness to unhealthy on shutdown, keep serving for a few seconds (a preStop sleep or HostOptions.ShutdownTimeout), then stop.
Azure Front Door, Application Gateway and App Service's health check feature each remove failing backends. Know what each does when every backend fails. Some keep routing to all of them and some return errors. Test it in a non-production environment, because that is exactly the moment a shared-dependency check puts you in.
A detailed health response can disclose dependency names, versions and connection details. Keep the public probe endpoint to a bare status. Put detailed output on an internal port or host (RequireHost("*:8081")) or behind RequireAuthorization, and never include connection strings or exception messages. This matters for ACSC Essential Eight-style hardening reviews.
kubectl get pods -w restart everything.Degraded check on an internal endpoint and repeat. Confirm no restarts.IHealthCheckPublisher that logs results every 30 s and view them in Application Insights.timeoutSeconds fail it.IHostApplicationLifetime.ApplicationStopping and measure dropped requests during a rolling deploy with a load tool.Separate liveness, readiness and internal dependency endpoints, with a warm-up gate, drain on shutdown and a cached dependency check.
// Program.cs (.NET 10)
using Microsoft.Extensions.Diagnostics.HealthChecks;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ReadinessGate>();
builder.Services.AddDbContext<OrdersDb>();
builder.Services.AddHealthChecks()
// Liveness: the process responds. Nothing shared.
.AddCheck("self", () => HealthCheckResult.Healthy(), tags: ["live"])
// Readiness: instance-specific state only (warm-up done, not draining).
.AddCheck<ReadinessGate>("warmup-and-drain", tags: ["ready"])
// Dependencies: Degraded, not Unhealthy, and only on the internal endpoint.
.AddDbContextCheck<OrdersDb>("sql", failureStatus: HealthStatus.Degraded, tags: ["deps"]);
// Push dependency health to monitoring on a timer: humans act on it, not probes.
builder.Services.Configure<HealthCheckPublisherOptions>(o =>
{
o.Period = TimeSpan.FromSeconds(30);
o.Predicate = r => r.Tags.Contains("deps");
});
var app = builder.Build();
// Flip readiness off as soon as shutdown starts, so endpoints drain before we stop.
var gate = app.Services.GetRequiredService<ReadinessGate>();
app.Lifetime.ApplicationStopping.Register(gate.StartDraining);
app.MapHealthChecks("/healthz/live", new() { Predicate = r => r.Tags.Contains("live") });
app.MapHealthChecks("/healthz/ready", new() { Predicate = r => r.Tags.Contains("ready") });
// Detailed dependency status: internal port only, never on the public listener.
app.MapHealthChecks("/healthz/deps", new() { Predicate = r => r.Tags.Contains("deps") })
.RequireHost("*:8081");
// Warm-up: prime caches, then open the gate.
_ = Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(5)); // stands in for cache priming / JIT warm-up
gate.MarkWarm();
});
app.Run();
public sealed class ReadinessGate : IHealthCheck
{
private volatile bool _warm;
private volatile bool _draining;
public void MarkWarm() => _warm = true;
public void StartDraining() => _draining = true;
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct) =>
Task.FromResult((_warm, _draining) switch
{
(_, true) => HealthCheckResult.Unhealthy("draining"),
(false, _) => HealthCheckResult.Unhealthy("warming up"),
_ => HealthCheckResult.Healthy()
});
}
public sealed class OrdersDb(Microsoft.EntityFrameworkCore.DbContextOptions<OrdersDb> options)
: Microsoft.EntityFrameworkCore.DbContext(options);
# Kubernetes probes: startup covers slow starts; liveness is lenient; readiness is quick.
startupProbe:
httpGet: { path: /healthz/live, port: 8080 }
periodSeconds: 5
failureThreshold: 24 # up to 120 s to start
livenessProbe:
httpGet: { path: /healthz/live, port: 8080 }
periodSeconds: 10
timeoutSeconds: 2
failureThreshold: 6 # 60 s of failure before a restart
readinessProbe:
httpGet: { path: /healthz/ready, port: 8080 }
periodSeconds: 5
timeoutSeconds: 2
failureThreshold: 2
lifecycle:
preStop:
sleep: { seconds: 10 } # let endpoint removal propagate before SIGTERM handling
BackgroundService loop updates, failing if it is older than a few minutes, or a ThreadPool queue-length threshold held for a sustained period.timeoutSeconds from the measured p99 of the check plus a margin.failureThreshold × periodSeconds to about 1.5–2 times that. Alert on pods that hit it.ApplicationStopping and add a preStop delay.RequireHost or RequireAuthorization.The senior framing is that every health check is a small piece of automation with the power to take instances out of service, so I review it like a deployment script: what does it act on, and can that action make things worse? The test I apply is "if this check fails on every instance at the same moment, what happens?" If the answer is a fleet restart or zero backends, the check is in the wrong place. Dependency health is still valuable. It goes to monitoring through IHealthCheckPublisher or Application Insights availability tests, with alerts that page a human who can decide. I also log every probe state change (not every probe), so a post-incident review can see when instances left rotation and why.
The setup order in ASP.NET Core matters for clarity: register everything once with AddHealthChecks(), tag each check by its purpose (live, ready, deps), then map one endpoint per purpose with a Predicate on the tag. One check can serve several endpoints. On timings, I set probe values from measurement: timeoutSeconds above the check's p99 latency, readiness quick to react (5 s period, 2 failures), and liveness slow to kill (a minute of failure), because a wrong restart costs more than a slow one. I separate application readiness (the whole service is usable, which is a monitoring and SLO question) from instance readiness (this pod should get traffic, which is the probe question).
There is one honest exception: a readiness dependency check makes sense when instances really can differ. Examples are a per-instance sidecar, a local disk, or a zonal dependency where other zones are healthy. Then removing the bad instance helps.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Self-only liveness plus in-process watchdogs | Every service | A little code for heartbeats | Never add shared dependencies to it |
| Instance-local readiness (warm-up, drain) | Every service | A little code | Do not add shared dependencies |
| Degraded dependency checks on an internal endpoint | Monitoring and dashboards | Alert tuning | As an input to automated routing |
| Zonal or per-instance dependency in readiness | Instances can really differ | Careful design and testing | Dependencies shared by every instance |
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.
An overloaded service with unbounded queues collapses: requests wait so long that many time out after the server has done the work, so goodput (successful responses that arrive in time) falls towards zero while CPU stays at 100%. Load shedding means rejecting excess work early and cheaply so the work you accept finishes in time.
In ASP.NET Core I use the rate limiting middleware (AddRateLimiter / UseRateLimiter) with a concurrency limiter sized by Little's law (concurrency = throughput × latency, measured at the healthy limit) and a small queue. Rejected requests get 503 with Retry-After, or 429 when a single client is over its quota. I shed by priority: checkout before batch exports, health probes never. Clients must honour Retry-After and back off with jitter.
The trade-off: you deliberately fail some users to keep the system serving most of them.
On SIGTERM, Kubernetes removes the pod from endpoints and signals the container at roughly the same time, but endpoint removal takes a few seconds to reach every node and ingress. So I fail readiness as soon as ApplicationStopping fires and add a preStop sleep of about 5–10 s so routing catches up. I let the host finish in-flight requests within HostOptions.ShutdownTimeout (30 s by default since .NET 8), and keep terminationGracePeriodSeconds longer than the preStop delay plus the shutdown timeout. Background services must honour the stopping token. I verify with a load test during a rolling deploy: zero 5xx.
How to tell it (STAR)
**S:** At [company], a routine Azure SQL failover turned into a [9-minute] outage for our order API. **T:** I led the review and owned the fix. **A:** Kubernetes events showed every pod failing its liveness probe, because the probe ran a SQL query, so all 20 restarted at once and then stampeded the database as it came back. I split the checks: liveness only checks the process, readiness covers warm-up and draining, and SQL health goes to monitoring as Degraded on an internal port. I also added a startup probe and wrote the pattern into our service template. **R:** The next failover caused about 40 seconds of failed writes and zero restarts. The unexplained restarts under load also stopped.
Last updated 23 Nov 2026.