📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You are designing health checks for a fleet of .NET services behind load balancers and Kubernetes. How do you make health checks tell the truth? Explain liveness, readiness and startup checks, which dependencies belong in which, how health checks cause cascading restarts and outages, and how you implement and secure them in ASP.NET Core.

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.

Senior Architecture Advanced aspnet-core distributed-systems health-checks kubernetes observability resilience

🎯 Key points

  • Liveness = can this process make progress: self response plus in-process watchdogs (stalled background loop, ThreadPool starvation), never shared dependencies
  • Readiness = should this instance get traffic now; checks only what is local to the instance and essential
  • Startup probe separates slow warm-up from liveness, sized from the measured worst start time
  • Shared-dependency checks make every instance fail at once: restarts or zero healthy backends
  • AddHealthChecks with tags; MapHealthChecks per endpoint with a Predicate; Degraded for non-critical dependencies
  • Cheap, cached, time-boxed checks; Kubernetes timeoutSeconds defaults to 1 s, so set it from measured check latency
  • Detailed health output is internal only: RequireHost or RequireAuthorization, no secrets or versions on public endpoints
  • Dependency health goes to monitoring (IHealthCheckPublisher, Application Insights) and alerts, not to probes that act automatically

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


Who acts on which check

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

How health checks cause outages

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

Should readiness check a dependency?

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

Production example

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.

🔍 What the interviewer is checking

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

  • Starts from who acts on the probe and what they do
  • Keeps shared dependencies out of liveness, and explains the problem with putting them in readiness
  • Knows Kubernetes probe defaults and the startup probe
  • Mentions drain on shutdown and securing detailed output

Red flags

  • "Check the database in the health endpoint" with no nuance
  • Treats health checks as monitoring dashboards
  • Never considers every instance failing at once

📚 Learn in depth

1. Probes are control loops

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.

2. Kubernetes probe mechanics

  • Defaults: periodSeconds: 10, timeoutSeconds: 1, failureThreshold: 3, successThreshold: 1.
  • A liveness failure for failureThreshold × periodSeconds (30 s by default) restarts the container.
  • A readiness failure removes the pod from the Service's EndpointSlices. Traffic stops, but the pod keeps running.
  • A startup probe disables liveness and readiness until it succeeds. Give it failureThreshold × periodSeconds greater than your worst start time.
  • The 1 s default timeout is the trap. A check that queries a database under load can easily take longer than 1 s.

3. ASP.NET Core health checks internals

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.
  • Health checks are registered as transient by default. Expensive checks should cache their result (for example for 10 s), so a probe storm doesn't become a database storm.
  • AddDbContextCheck<TContext>() (from Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore) calls CanConnectAsync, which is cheap but still a round trip.

4. Graceful shutdown and readiness

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.

5. Load balancer probes

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.

6. Security of health endpoints

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.

Try it yourself

  1. Add a SQL check to liveness in a kind or minikube cluster, then stop SQL for 60 s. Watch kubectl get pods -w restart everything.
  2. Move SQL to a Degraded check on an internal endpoint and repeat. Confirm no restarts.
  3. Add an IHealthCheckPublisher that logs results every 30 s and view them in Application Insights.
  4. Make a check that sleeps for 2 s and see the default 1 s timeoutSeconds fail it.
  5. Implement readiness flipping on IHostApplicationLifetime.ApplicationStopping and measure dropped requests during a rolling deploy with a load tool.

💻 Code

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

⚠ Common mistakes

  • Mistake: Checking the database in liveness. Why it is wrong: A database blip restarts every pod at once, and the cold starts stampede the database as it recovers. Instead: Liveness checks only the process itself.
  • Mistake: A liveness check that only returns 200 from a static handler, when the real risk is a stuck worker. Why it is wrong: The endpoint answers while the background consumer or ThreadPool is wedged, so a broken pod is never restarted. Instead: Add in-process, non-shared watchdogs to liveness, for example a heartbeat timestamp that each BackgroundService loop updates, failing if it is older than a few minutes, or a ThreadPool queue-length threshold held for a sustained period.
  • Mistake: Readiness that fails when a dependency shared by every instance fails. Why it is wrong: All instances leave rotation together, leaving zero backends, so even requests that didn't need the dependency fail. Instead: Report shared dependencies as Degraded on an internal endpoint and alert on them.
  • Mistake: Expensive checks run on every probe. Why it is wrong: With 50 pods probing every 5 s, the probes become real load, and they fail Kubernetes' 1 s default timeout under pressure. Instead: Keep probe checks in memory, cache any dependency results, and set timeoutSeconds from the measured p99 of the check plus a margin.
  • Mistake: No startup probe for a slow-starting service, or one sized by guesswork. Why it is wrong: Liveness kills the pod before it finishes warming up, so it ends up in a restart loop. A huge threshold hides pods that will never start. Instead: Measure the worst start time (cold node, image pull excluded, migrations checked, caches loaded) and set failureThreshold × periodSeconds to about 1.5–2 times that. Alert on pods that hit it.
  • Mistake: Not flipping readiness during shutdown. Why it is wrong: Requests are routed to a pod that is stopping, causing errors on every deploy. Instead: Fail readiness on ApplicationStopping and add a preStop delay.
  • Mistake: Exposing detailed health JSON publicly. Why it is wrong: It discloses dependency names, versions and sometimes exception text to attackers. Instead: Keep public probes to a bare status; put details behind RequireHost or RequireAuthorization.
  • Mistake: Rate-limiting or authenticating the probe endpoint. Why it is wrong: Probes fail under load or when the identity provider is down, and healthy pods are killed. Instead: Exempt probe endpoints from rate limiting and authentication, and keep them minimal.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate discusses whether readiness should include the database or downstream services Why: Checks the specific readiness-probe dependency trade-off in Kubernetes
    How to answer

    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.

    • Check local prerequisites; handle dependency failures in the request path with timeouts, circuit breakers and fallbacks.
    • Exceptions: a dependency that belongs to this instance only (a sidecar, a per-pod cache warm-up), or a prerequisite without which the instance can serve nothing at all and the failure is instance-specific.
    • Liveness is narrower still: only a stuck process.

    The trade-off is against the SLO: serving degraded responses usually costs less error budget than having zero ready pods.

  2. When: Candidate mentions busy instances failing probes under load Why: Checks that probes are exempt from load shedding and how overload interacts with health checks
    How to answer

    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.

  3. When: Candidate mentions draining or readiness during shutdown Why: Checks understanding of SIGTERM, endpoint propagation delay, preStop hooks and HostOptions.ShutdownTimeout
    How to answer

    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.

🛠 Real-world problems: how you handle them

Azure SQL failover restarting every pod through liveness probes
Situation
An order API of [20 pods on AKS in Australia East] backed by Azure SQL. Liveness and readiness both ran a SQL query with a 5 s timeout. Kubernetes probe timeouts were left at the 1 s default.
Signals
During a [40 s] planned Azure SQL failover, every pod restarted at once, there were zero ready endpoints for about 2 minutes, and SQL connection spikes followed when pods came back. Users saw [9 minutes] of errors. Before the incident there were already occasional unexplained restarts under load.
Investigation
`kubectl describe pod` showed liveness probe failures with timeouts. Kubernetes events lined up with the SQL failover in the Azure Resource Health timeline. Application Insights showed connection pool warm-up storms. The probe timing showed the 1 s timeout being exceeded by SQL checks under normal load.
Resolution
Immediate: removed the SQL check from liveness and raised probe timeouts. Real fix: liveness self-only, readiness for warm-up and drain only, SQL as a Degraded check on an internal endpoint with an IHealthCheckPublisher feeding alerts, plus a startup probe.
Prevention
A health-check standard in the platform template, a review question ("what if this fails on every instance at once?"), and a quarterly game day in Azure Chaos Studio that triggers a SQL failover and checks for no restarts.

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.

↩ Usually asked after

More in Reliability Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me