ASP.NET Core cookbook · Beginner

Expose liveness and readiness health checks

Orchestrators restart healthy pods or route traffic to instances whose database is down.

Create a free account to save this page, take notes and track your progress. Sign in

Approach

Register checks with tags, map a liveness endpoint that runs no dependency checks and a readiness endpoint that checks the database with a timeout, and write a JSON summary.

Solution

using System.Text.Json;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHealthChecks()
    .AddCheck<DatabaseHealthCheck>("database", tags: ["ready"], timeout: TimeSpan.FromSeconds(2));
var app = builder.Build();

app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready"),
    ResponseWriter = (ctx, report) => ctx.Response.WriteAsync(JsonSerializer.Serialize(new
    {
        status = report.Status.ToString(),
        checks = report.Entries.ToDictionary(e => e.Key, e => e.Value.Status.ToString()),
    })),
});
app.Run();

public class DatabaseHealthCheck(IConfiguration config) : IHealthCheck
{
    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default)
    {
        try
        {
            await Task.Delay(10, ct);   // replace with a real "SELECT 1" using your connection
            return HealthCheckResult.Healthy();
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy("database unreachable", ex);
        }
    }
}

Pitfalls

  • Dependency checks in liveness probes; a database outage then restarts every pod.
  • Expensive checks run on every probe; keep them cheap or cache results briefly.
  • Exposing detailed health output (connection strings, exception messages) publicly.

Variations

  • The AspNetCore.HealthChecks.* packages provide ready-made checks for PostgreSQL, Redis and more.
  • Publish health status to monitoring with IHealthCheckPublisher.

Further reading: Health checks

Reference: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks

More ASP.NET Core recipes

Was this page helpful?