Skip to main content

Lesson 6 of 8

Health Checks & Application Readiness

Health checks expose /health endpoints that Kubernetes, load balancers, and monitoring systems query to determine if your app is alive and ready for traffic. ASP.NET Core has a built-in health check framework with checks for DB, Redis, and custom business logic.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Liveness & Readiness Health Checks

Liveness & Readiness Health Checks
using Microsoft.Extensions.Diagnostics.HealthChecks;

// ━━ Register health checks ━━
builder.Services
    .AddHealthChecks()
    .AddSqlServer(                                    // DB connectivity
        builder.Configuration.GetConnectionString("DefaultConnection")!,
        name: "database",
        tags: ["db", "ready"])
    .AddRedis(                                        // Redis connectivity
        builder.Configuration.GetConnectionString("Redis")!,
        name: "redis",
        tags: ["cache", "ready"])
    .AddCheck<ExternalApiHealthCheck>(                // custom check
        "payment-gateway",
        tags: ["external", "ready"]);

// ━━ Map endpoints ━━
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    // Liveness: is the process alive? Only check process-level health
    Predicate = _ => false, // no checks - if process is running, it's alive
    ResponseWriter = WriteHealthResponse
});

app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    // Readiness: can the app serve traffic? Check all dependencies
    Predicate = check => check.Tags.Contains("ready"),
    ResponseWriter = WriteHealthResponse
});

// ━━ Custom health check ━━
public class ExternalApiHealthCheck(IHttpClientFactory httpClientFactory) : IHealthCheck
{
    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        try
        {
            var client = httpClientFactory.CreateClient();
            var response = await client.GetAsync(
                "https://api.stripe.com/v1/customers?limit=1", cancellationToken);

            return response.IsSuccessStatusCode
                ? HealthCheckResult.Healthy("Payment gateway is reachable")
                : HealthCheckResult.Degraded($"Payment gateway returned {response.StatusCode}");
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy("Payment gateway unreachable", ex);
        }
    }
}

static Task WriteHealthResponse(HttpContext ctx, HealthReport report)
{
    ctx.Response.ContentType = "application/json";
    return ctx.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(new
    {
        status = report.Status.ToString(),
        duration = report.TotalDuration.TotalMilliseconds,
        checks = report.Entries.Select(e => new
        {
            name = e.Key,
            status = e.Value.Status.ToString(),
            duration = e.Value.Duration.TotalMilliseconds,
            error = e.Value.Exception?.Message
        })
    }));
}

Tip

Tip

Practice Health Checks Application Readiness in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Health Checks Application Readiness from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Health Checks Application Readiness is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done