Course contentsShow
← C#
Lesson 1813 of 1,90816. Performance and DiagnosticsFree lesson

Implementing Custom Health Checks

Learners will build diagnostic endpoints to expose internal state for load balancer monitoring.

In this lesson, you will learn how to build custom health check endpoints in ASP.NET Core to allow load balancers to accurately determine if your service is ready to process traffic.

The Role of Health Checks in Distributed Systems

When running services in containerized environments, a process might be "up" (running) but not necessarily "healthy" (ready to work). For example, your application might be waiting for a database connection to initialize or a cache to warm up. A load balancer needs to know exactly when your service is truly capable of handling requests, otherwise, it might route traffic to a service that is about to crash or return 500 errors.

Creating a Custom Health Check

To implement a custom check, you implement the IHealthCheck interface. This requires you to define a CheckHealthAsync method that returns a HealthCheckResult. You can return Healthy, Degraded, or Unhealthy based on your internal logic.

public class DatabaseHealthCheck : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default)
    {
        bool isDbAvailable = CheckDatabaseConnection(); // Your logic here
        
        if (isDbAvailable)
            return Task.FromResult(HealthCheckResult.Healthy("Database is responding."));
        
        return Task.FromResult(HealthCheckResult.Unhealthy("Database connection failed."));
    }
}

Registering and Exposing the Endpoint

Once you have your class, you register it in your Program.cs via the AddHealthChecks() service. You then map it to a specific URL path, such as /health.

builder.Services.AddHealthChecks()
    .AddCheck<DatabaseHealthCheck>("sql_server_check");

// In the request pipeline:
app.MapHealthChecks("/health");

When your load balancer pings /health, it receives a simple response. If the check returns Unhealthy, the load balancer will remove your container from the rotation automatically. This is essential for zero-downtime deployments and self-healing infrastructure.

By decoupling the "process status" from the "application readiness," you gain the ability to signal the orchestration layer to restart or reroute traffic before a minor internal failure cascades into a full-scale outage.

Key Takeaway: Custom health checks allow you to expose internal application state to load balancers, ensuring traffic is only routed to instances that are fully initialized and capable of operation.