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

📚 Interview question

What are health checks in ASP.NET Core? Explain how AddHealthChecks and MapHealthChecks work, how you add checks for dependencies such as SQL Server or Redis, what Healthy, Degraded and Unhealthy mean, and why you usually expose separate liveness and readiness endpoints.

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.

Junior Theory Beginner aspnet-core health-checks kubernetes liveness-probe observability readiness-probe

🎯 Key points

  • AddHealthChecks() registers IHealthCheck instances; MapHealthChecks("/path") exposes them as an endpoint
  • HealthStatus: Healthy = 200, Degraded = 200 by default, Unhealthy = 503
  • Dependency checks via AddCheck<T>, AddDbContextCheck<T> or AspNetCore.HealthChecks.* packages (SqlServer, Redis)
  • Tags plus HealthCheckOptions.Predicate split checks across endpoints
  • Liveness (/health/live) runs no dependency checks: 'is the process able to serve at all?'
  • Readiness (/health/ready) checks what the instance needs before it should receive traffic
  • Checks need timeouts and must be cheap; probes call them every few seconds
  • Don't expose details publicly: restrict with RequireHost, a separate port or authorisation

⏱ 30-second answer

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:

  • Liveness: no dependencies, just "the process is responsive".
  • Readiness: "I can serve traffic now", including critical dependencies.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 implements IHealthCheck and returns a HealthCheckResult with a status of Healthy, Degraded or Unhealthy plus an optional description and data. Then MapHealthChecks("/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 example ready, and map two endpoints with a predicate: /health/live runs no checks at all, and /health/ready runs only the ready checks. 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."


The building blocks

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 values

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 vs readiness

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.

Timeouts

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.

Keep them safe and cheap

  • Each probe call runs the checks, so a check that runs a heavy query every 5 seconds on 20 pods is real load. Use SELECT 1, short timeouts and, for expensive checks, cache results or use a publisher.
  • The detailed JSON response leaks internals (server names, versions, exception messages). Return only the plain status publicly and put details behind RequireHost("*:8081") (a management port not exposed through the ingress) or RequireAuthorization().
  • Exclude health endpoints from request metrics with .DisableHttpMetrics() so probes don't skew your latency charts.

Production example

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.

🔍 What the interviewer is checking

Checks the candidate knows the ASP.NET Core health checks API and, more importantly, the different purposes of liveness and readiness.

Green flags

  • Names AddHealthChecks, MapHealthChecks, IHealthCheck and the three statuses with their status codes
  • Splits liveness and readiness with tags and predicates
  • Keeps shared dependencies out of liveness and explains the mass-restart failure
  • Mentions timeouts, cheap checks and not exposing details publicly

Red flags

  • One endpoint that checks everything, used for every probe
  • Thinks Degraded returns 503 or doesn't know what Degraded is for
  • Calls downstream services' health endpoints from their own check

📚 Learn in depth

1. What happens on a health request

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.

2. Registrations have options

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)

3. Writing a good custom check

A check should answer a yes/no question about this instance in milliseconds. Good examples:

  • a BackgroundService writes lastHeartbeat; the liveness check fails if it is older than 2 minutes (the loop is stuck);
  • a start-up check reports Unhealthy until migrations and cache warm-up are done (startup tag);
  • a readiness check reports Degraded when an optional dependency is down so the app keeps serving with a fallback.

Bad examples: calling another service's health endpoint (cascades), running business queries, or checking things the instance can't fix.

4. Pushing results: the publisher

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.

5. Who calls the endpoints

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

6. .NET Aspire service defaults

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.

Try it yourself

  1. Create a dotnet new webapi, add AddHealthChecks().AddCheck("self", () => HealthCheckResult.Healthy(), tags: ["live"]) and map /health/live and /health/ready with predicates. Curl both.
  2. Add AddDbContextCheck<AppDbContext>(tags: ["ready"]), stop the database container and watch /health/ready go to 503 while /health/live stays 200.
  3. Write a check that sleeps 5 seconds, set timeout: TimeSpan.FromMilliseconds(500) and see the result.
  4. Add a custom ResponseWriter that writes JSON with each entry's status and duration, then protect it with RequireHost("*:8081").
  5. Run dotnet-counters monitor -n MyApi Microsoft.AspNetCore.Hosting while hitting /health/live in a loop, then add .DisableHttpMetrics() and compare.

💻 Code

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"));
}

⚠ Common mistakes

  • Mistake: Putting the database or another service in the liveness check. Why it is wrong: a shared dependency outage fails every pod's liveness and Kubernetes restarts them all, turning a blip into an outage. Instead: keep liveness to in-process state; put dependencies in readiness.
  • Mistake: Using one /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.
  • Mistake: Health checks that run real business queries. Why it is wrong: probes run every few seconds on every instance, so the check becomes load. Instead: SELECT 1 / CanConnectAsync, short timeouts, or a publisher with a cached result.
  • Mistake: No per-check timeout. Why it is wrong: one hung dependency makes the endpoint exceed the probe timeout and the instance looks dead. Instead: set timeout: on each dependency check, shorter than the probe timeout.
  • Mistake: Exposing the detailed JSON (server names, exception messages) on the public internet. Why it is wrong: it hands attackers your topology and versions. Instead: plain status publicly, details on a management port or behind RequireAuthorization(), and never connection strings or exception messages in the output.
  • Mistake: Marking optional dependencies as Unhealthy. Why it is wrong: the instance is pulled from rotation even though it could serve with a fallback. Instead: use failureStatus: HealthStatus.Degraded.
  • Mistake: Calling another service's health endpoint from your check. Why it is wrong: one unhealthy service cascades through every caller. Instead: check only what this instance owns; rely on resilience policies for downstream calls.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions liveness and readiness or Kubernetes probes. Why: Checks they can design truthful health checks for a whole fleet, including startup checks and cascade risks.
    How to 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.

  2. When: Candidate puts the database in the readiness check. Why: Checks they see the risk of every instance failing readiness together when a shared dependency is down.
    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.

  3. When: Candidate mentions removing instances from traffic or deployments. Why: Checks they connect readiness to graceful shutdown and connection draining during rollouts.
    How to answer

    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.

↩ Usually asked after

More in Health and Alerts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me