ASP.NET Core Health Checks: Designing Liveness and Readiness Endpoints Correctly

ASP.NET Core Health Checks: Designing Liveness and Readiness Endpoints Correctly

An ASP.NET Core application being alive does not necessarily mean that it is ready to serve traffic. The process may still be running while the application cannot reach its database, has not completed a required startup task, or is unable to contact a critical external service. Health checks make these conditions observable through standard HTTP endpoints.

The most important design distinction is between liveness and readiness. Liveness answers whether the process is still functioning and may need to be restarted. Readiness answers whether the application is currently prepared to receive traffic. Combining both concerns into one endpoint can cause unnecessary restarts or route traffic to an instance that is not ready.

What ASP.NET Core health checks provide

ASP.NET Core provides AddHealthChecks for registering health check services and MapHealthChecks for exposing checks through an HTTP endpoint. If no specific checks are registered, the endpoint primarily indicates that the application can respond. Database, cache, queue, and external service checks must be registered separately.

Health endpoints are commonly called by load balancers, monitoring systems, Docker, or Kubernetes. Because they may be called frequently, health check code should be fast, predictable, and focused on operationally meaningful conditions.

Create a basic health endpoint

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

var app = builder.Build();

app.MapHealthChecks("/healthz");

app.Run();

By default, healthy results map to HTTP 200 and unhealthy results map to HTTP 503. The default response is a simple status representation. This basic configuration can be sufficient for a local-only liveness probe that checks whether the application responds.

Why liveness and readiness should be separate

Liveness should indicate whether the process is running well enough to remain alive. It should normally be local and inexpensive. Examples include confirming that the process responds and that its basic execution path is not stuck.

Readiness indicates whether the instance should receive traffic. During startup, an application might be downloading configuration, warming a cache, applying a required initialization step, or waiting for a dependency to become available. The process is alive during this period, but it may not yet be ready.

Putting a database dependency in the liveness probe is often risky. A temporary database outage may cause the orchestrator to restart an otherwise healthy process. If the same dependency is evaluated as part of readiness, the instance can be removed from traffic without creating a restart loop.

Use tags to create separate groups

Tags allow health checks to be grouped by purpose. In the following example, the database check belongs to the readiness group while the local check belongs to the liveness group:

builder.Services
    .AddHealthChecks()
    .AddCheck("self", () =>
        Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult.Healthy(),
        tags: new[] { "live" })
    .AddCheck("database", () =>
        Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult.Healthy(),
        tags: new[] { "ready" });

var app = builder.Build();

app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("live")
});

app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready")
});

In a production application, the database check should use an appropriate provider or a custom IHealthCheck implementation rather than always returning Healthy. The example demonstrates the endpoint separation and filtering model.

Implement a custom IHealthCheck

When a dependency requires application-specific rules, implement IHealthCheck. The check should be asynchronous and should pass the cancellation token to the underlying operation.

public sealed class CacheHealthCheck : IHealthCheck
{
    private readonly IDistributedCache _cache;

    public CacheHealthCheck(IDistributedCache cache)
    {
        _cache = cache;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        try
        {
            await _cache.GetStringAsync("health-check", cancellationToken);
            return HealthCheckResult.Healthy();
        }
        catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
        {
            throw;
        }
        catch (Exception exception)
        {
            return HealthCheckResult.Unhealthy(
                "The cache is unavailable.", exception);
        }
    }
}

Register the check with an explicit name and tag:

builder.Services.AddHealthChecks()
    .AddCheck<CacheHealthCheck>(
        "cache",
        tags: new[] { "ready" });

Health check implementations are commonly registered as singleton services. However, the lifetime of the check and the thread-safety of every dependency it uses should be reviewed together before choosing a service lifetime.

Control timeout, cost, and side effects

A health check should not be slower or more expensive than the dependency it measures. Heavy queries executed on every probe can create additional load precisely when the system is under pressure. Apply the following principles:

  • Keep each check small and focused.
  • Use short timeouts for remote calls.
  • Propagate cancellation tokens to lower layers.
  • Avoid data-changing operations in health checks.
  • Keep detailed failure information in logs rather than exposing sensitive details in the HTTP response.

You do not always need to execute a complete business workflow to test an external service. A low-cost connectivity or metadata request may be enough. Identify the dependencies that are operationally critical and avoid registering every possible subsystem if the result would be noisy or expensive.

HTTP status codes and endpoint security

HealthCheckOptions can filter checks and customize status code mappings, cache behavior, and response output. Health responses generally should not be cached because a cached result may hide a current failure. The default middleware behavior prevents common response caching.

Consider whether the endpoint should be publicly accessible. Detailed internal checks should not automatically be exposed to the internet. Depending on the hosting model, restrict the endpoint by network, management port, host, or authorization policy. If an orchestrator must access the endpoint, design the network and authentication model together rather than disabling security without analysis.

What should the response contain?

A JSON response can make internal monitoring easier, especially when it includes an overall status and the duration of individual checks. However, connection strings, access tokens, exception stacks, and personal data should never be returned to unauthenticated callers. Public endpoints should expose only the minimum information needed by the monitoring component.

Do not rely only on the HTTP status code for observability. Record which check failed, how long it took, how often it fails, and whether the failure is transient. This helps distinguish a short network interruption from a persistent configuration or deployment problem.

Using health checks with Docker and Kubernetes

Docker can use a HEALTHCHECK instruction to call an application health endpoint. Kubernetes can connect separate readiness and liveness probes to different endpoints. When readiness fails, a pod can be removed from service traffic. When liveness fails, the orchestrator may restart the container.

For this reason, the liveness endpoint should generally avoid variable dependencies such as databases, queues, and external APIs. The readiness endpoint should represent the dependencies that are genuinely required for the instance to perform its intended work.

Practical design checklist

  1. Expose separate liveness and readiness endpoints.
  2. Keep liveness local and inexpensive.
  3. Place dependency checks in the readiness group.
  4. Use tags and predicates to filter checks.
  5. Design timeout, cancellation, and exception handling explicitly.
  6. Do not expose secrets or internal stack traces in responses.
  7. Protect endpoints with suitable network, host, or authorization rules.
  8. Agree with the operations team on the meaning of each status code.

Conclusion

ASP.NET Core Health Checks are more than adding a single /health route. Their real value comes from modeling the difference between being alive and being ready to receive traffic. Simple liveness checks, dependency-aware readiness checks, tag-based filtering, and carefully limited responses create predictable behavior on traditional hosts as well as container platforms.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published