TExcelTAD
Home › ASP.NET Core › Health Checks

Health Checks

A health check is an endpoint that answers one question: "is this instance able to do its job right now?". Load balancers, Kubernetes, Docker and monitoring tools call it every few seconds and stop sending traffic to — or restart — instances that report trouble.

The simplest health check

The health checks services are part of the shared framework, so no package is needed for the basics:

csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHealthChecks();

var app = builder.Build();
app.MapHealthChecks("/healthz");
app.Run();
bash · try it yourself
$ curl -i localhost:5000/healthz
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel
Cache-Control: no-store, no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Pragma: no-cache
Transfer-Encoding: chunked

Healthy

With no checks registered, the endpoint simply proves that the process is up and the pipeline answers requests.

Health statuses

Each check returns a HealthCheckResult. The overall report takes the worst status of all checks:

Status Default HTTP code Meaning
Healthy 200 everything works
Degraded 200 working, but slower or with a non-critical dependency down
Unhealthy 503 cannot serve requests properly

Writing a custom check

Implement IHealthCheck and register it with a name, an optional failure status and tags:

csharp
public class DiskSpaceHealthCheck : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, CancellationToken ct = default)
    {
        var drive = new DriveInfo("/");
        double freeGb = drive.AvailableFreeSpace / 1024d / 1024 / 1024;
        var data = new Dictionary<string, object> { ["freeGb"] = Math.Round(freeGb, 1) };

        return Task.FromResult(freeGb switch
        {
            < 1 => HealthCheckResult.Unhealthy("Less than 1 GB free", data: data),
            < 5 => HealthCheckResult.Degraded("Disk space is low", data: data),
            _   => HealthCheckResult.Healthy("Enough disk space", data),
        });
    }
}

builder.Services.AddHealthChecks()
    .AddCheck<DiskSpaceHealthCheck>("disk", tags: ["ready"])
    .AddCheck("self", () => HealthCheckResult.Healthy(), tags: ["live"])
    .AddDbContextCheck<NotesDb>("database", tags: ["ready"]); // Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore

Community packages (the AspNetCore.HealthChecks.* family) add ready-made checks for SQL Server, PostgreSQL, Redis, RabbitMQ, URLs and more.

How the report is aggregated

The aggregation logic is simple enough to model in plain C#: run every check, keep the worst status, map it to an HTTP code.

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var checks = new List<(string Name, string[] Tags, Func<(Status, string)> Run)>
{
    ("self",     new[] { "live" },  () => (Status.Healthy,  "ok")),
    ("database", new[] { "ready" }, () => (Status.Healthy,  "query took 4 ms")),
    ("disk",     new[] { "ready" }, () => (Status.Degraded, "3.2 GB free")),
    ("payments", new[] { "ready" }, () => (Status.Unhealthy, "timeout after 2 s")),
};

void Report(string path, Func<string[], bool> predicate)
{
    var results = checks.Where(c => predicate(c.Tags))
                        .Select(c => (c.Name, Result: c.Run()))
                        .ToList();
    var overall = results.Count == 0 ? Status.Healthy : results.Min(r => r.Result.Item1);
    int http = overall == Status.Unhealthy ? 503 : 200;
    Console.WriteLine(
quot;GET {path} -> {http} {overall}"); foreach (var r in results) Console.WriteLine(
quot; {r.Name,-9} {r.Result.Item1,-9} {r.Result.Item2}"); } Report("/healthz/live", tags => tags.Contains("live")); Report("/healthz/ready", tags => tags.Contains("ready")); // Lower value = worse, so Min() picks the worst status (same order as the real enum) enum Status { Unhealthy = 0, Degraded = 1, Healthy = 2 }
GET /healthz/live -> 200 Healthy
  self      Healthy   ok
GET /healthz/ready -> 503 Unhealthy
  database  Healthy   query took 4 ms
  disk      Degraded  3.2 GB free
  payments  Unhealthy timeout after 2 s

Liveness vs readiness

Orchestrators such as Kubernetes distinguish two probes, and tags let one app expose both:

Probe Question If it fails… What to include
Liveness Is the process stuck? the container is restarted only cheap self-checks — never external dependencies
Readiness Can it take traffic now? traffic is paused until it recovers database, cache, required downstream services
Startup Has it finished starting? liveness is delayed warm-up work, migrations
csharp
app.MapHealthChecks("/healthz/live", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("live"),
});

app.MapHealthChecks("/healthz/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready"),
    ResponseWriter = WriteJson,
}).RequireHost("*:5001");      // only reachable on the internal port

Note: Putting the database check in the liveness probe is a classic mistake: a short database outage would make Kubernetes restart every healthy pod at once.

A JSON response

The default body is just the status word. A custom ResponseWriter can return details for dashboards:

csharp
static Task WriteJson(HttpContext http, HealthReport report)
{
    http.Response.ContentType = "application/json";
    return http.Response.WriteAsJsonAsync(new
    {
        status = report.Status.ToString(),
        totalMs = report.TotalDuration.TotalMilliseconds,
        checks = report.Entries.Select(e => new
        {
            name = e.Key,
            status = e.Value.Status.ToString(),
            description = e.Value.Description,
        }),
    });
}
bash · try it yourself
$ curl -s localhost:5000/healthz/ready
{"status":"Degraded","totalMs":12.4471,"checks":[{"name":"disk","status":"Degraded","description":"Disk space is low"},{"name":"database","status":"Healthy","description":null}]}

Tip: Health endpoints can leak information (versions, hostnames, dependency names). Keep detailed output on an internal port, or protect it with RequireAuthorization(), and keep the public probe terse.

Test yourself

With default options, which HTTP status does an Unhealthy report return?

  1. 200
  2. 500
  3. 404
  4. 503

Which checks belong in a liveness probe?

  1. Only cheap checks that the process itself is responsive
  2. Every external dependency
  3. The database and Redis
  4. None — liveness probes must always fail

Three checks report Healthy, Degraded and Healthy. What is the overall status?

  1. Healthy
  2. Degraded
  3. Unhealthy
  4. Unknown