ASP.NET Core MVC Intermediate

Health checks

Health checks give load balancers, containers and monitoring tools a simple URL that says whether your app works. This lesson sets up liveness and readiness endpoints, checks the database, and writes a custom check.

How a health check is used
  1. StartLoad balancerCalls /healthz/ready every few seconds
  2. Step 2Checks runDatabase and payment gateway
  3. Step 3HealthyInstance keeps receiving traffic
  4. Step 4UnhealthyInstance removed until it recovers
  5. EndLiveness failsContainer or app is restarted

Why

A load balancer or Kubernetes calls a health URL every few seconds. If the app stops answering, traffic moves to healthy instances or the container is restarted. Uptime monitors use the same URL to alert you.

Liveness asks "is the process running?" and readiness asks "can it serve requests right now?", for example with the database reachable.

Setting it up

C#
builder.Services.AddHealthChecks()
    .AddDbContextCheck<ShopContext>("database", tags: ["ready"])   // package: ...Diagnostics.HealthChecks.EntityFrameworkCore
    .AddCheck<PaymentGatewayCheck>("payments", tags: ["ready"]);

var app = builder.Build();

// Liveness: no dependencies, just "the app responds"
app.MapHealthChecks("/healthz/live", new HealthCheckOptions { Predicate = _ => false });

// Readiness: run the checks tagged ready
app.MapHealthChecks("/healthz/ready", new HealthCheckOptions
{
    Predicate = c => c.Tags.Contains("ready")
});

A custom check

C#
public class PaymentGatewayCheck(HttpClient http) : IHealthCheck
{
    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default)
    {
        try
        {
            using var res = await http.GetAsync("status", ct);
            return res.IsSuccessStatusCode
                ? HealthCheckResult.Healthy()
                : HealthCheckResult.Degraded($"Gateway returned {(int)res.StatusCode}");
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy("Gateway unreachable", ex);
        }
    }
}

Good habits

  • Keep checks fast and cheap; they run often.
  • Do not put slow external dependencies in liveness, or a third-party outage restarts your app for nothing.
  • Return only Healthy, Degraded or Unhealthy publicly; detailed output can leak internals, so protect it with RequireAuthorization or a host filter.
  • Azure App Service has a Health check setting that removes failing instances from the load balancer.

Interview question

What is the difference between a liveness and a readiness health check?

Liveness says whether the process is alive and responding; if it fails, the orchestrator restarts the app. Readiness says whether the app can serve traffic now, including its dependencies such as the database; if it fails, the instance is taken out of the load balancer but not restarted. Keeping dependencies out of liveness avoids pointless restarts.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.