NET Core Health Checks: A Comprehensive Guide

 

.NET Core Health Checks: A Comprehensive Guide

Introduction

In modern application development, ensuring system health and reliability is crucial. .NET Core Health Checks provide a built-in mechanism to monitor the health of applications and dependencies, helping developers detect failures before they impact users. This guide explores how to implement health checks in .NET Core, their benefits, and best practices for using them effectively.


What Are .NET Core Health Checks?

Health Checks in .NET Core are middleware components that allow applications to report their status. They help monitor critical components such as:

  • Database connections
  • External API availability
  • Memory and CPU usage
  • Message queues (e.g., RabbitMQ, Kafka)
  • Disk space availability

Developers can define custom health checks to ensure the system is functioning as expected.


Setting Up Health Checks in .NET Core

1. Install Required Packages

To use health checks, install the required NuGet package:

dotnet add package Microsoft.AspNetCore.Diagnostics.HealthChecks

For database checks (e.g., SQL Server), install additional dependencies:

dotnet add package AspNetCore.HealthChecks.SqlServer

2. Register Health Checks in Program.cs

In .NET 6/7/8, add health checks in the Program.cs file:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

// Add Health Checks
builder.Services.AddHealthChecks()
    .AddSqlServer("Server=your-server;Database=your-db;User Id=your-user;Password=your-password;")
    .AddCheck<CustomHealthCheck>("Custom Check");

var app = builder.Build();

app.UseRouting();

// Map Health Checks endpoint
app.MapHealthChecks("/health");

app.Run();

3. Creating a Custom Health Check

You can define custom logic to monitor specific application components by implementing the IHealthCheck interface.

Example: Custom Health Check for an External API

using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Diagnostics.HealthChecks;

public class CustomHealthCheck : IHealthCheck
{
    private readonly HttpClient _httpClient;

    public CustomHealthCheck(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        var response = await _httpClient.GetAsync("https://api.example.com/health");

        if (response.IsSuccessStatusCode)
        {
            return HealthCheckResult.Healthy("API is running");
        }
        return HealthCheckResult.Unhealthy("API is down");
    }
}

Then, register this custom check in Program.cs:

builder.Services.AddHttpClient<CustomHealthCheck>();
builder.Services.AddHealthChecks()
    .AddCheck<CustomHealthCheck>("External API Check");

Enhancing Health Checks with UI and Logging

1. Adding a JSON Response Format

By default, the response is plain text. To return JSON, modify the endpoint as follows:

app.MapHealthChecks("/health", new HealthCheckOptions
{
    ResponseWriter = async (context, report) =>
    {
        context.Response.ContentType = "application/json";
        var result = System.Text.Json.JsonSerializer.Serialize(
            new
            {
                status = report.Status.ToString(),
                checks = report.Entries.Select(e => new
                {
                    name = e.Key,
                    status = e.Value.Status.ToString(),
                    description = e.Value.Description
                }),
                duration = report.TotalDuration
            });
        await context.Response.WriteAsync(result);
    }
});

2. Using HealthChecks UI

To visualize health checks, install HealthChecks UI:

dotnet add package AspNetCore.HealthChecks.UI
dotnet add package AspNetCore.HealthChecks.UI.InMemory.Storage

Modify Program.cs to enable UI support:

builder.Services.AddHealthChecksUI()
    .AddInMemoryStorage();

app.UseHealthChecksUI(options => options.UIPath = "/health-ui");

app.Run();

Now, navigating to /health-ui in a browser will show a dashboard with health check results.




Best Practices for Using Health Checks

  1. Monitor Critical Services Only – Avoid unnecessary checks to reduce overhead.
  2. Use Caching for Expensive Health Checks – If a check is resource-intensive, implement caching to avoid frequent calls.
  3. Secure Health Endpoints – Restrict access to /health to prevent exposing internal details.
  4. Integrate with Monitoring Tools – Use Prometheus, Grafana, or Azure Monitor for alerts and dashboards.
  5. Consider Liveness vs. Readiness Checks:
    • Liveness Check: Determines if the app is still running.
    • Readiness Check: Ensures the app is ready to serve requests (e.g., DB connections are healthy).

Conclusion

Health checks in .NET Core are essential for monitoring application health and improving reliability. By implementing built-in and custom health checks, integrating with dashboards, and following best practices, developers can proactively detect and resolve issues before they impact users.

Would you like help setting up health checks in a specific scenario? Let me know!

Comments

Popular posts from this blog

Maxpooling vs minpooling vs average pooling

Generative AI - Prompting with purpose: The RACE framework for data analysis

Best Practices for Storing and Loading JSON Objects from a Large SQL Server Table Using .NET Core