DEV Community

Julia Shevchenko
Julia Shevchenko

Posted on

Health Check setup for .NET application

What is a Health Check?

A Health Check is an indicator of service availability. For web applications, it's an endpoint that returns the current state of the application - usually, it could be Healthy, Degraded, or Unhealthy. Health checks can be configured for any type of service, such as a database or a message broker, or can be set to track any crucial part of the application.
It is frequently used in CD pipelines to observe if the service has any issues and restart it if needed. 

Basic Health Check configuration

To add a basic health check, you need to do two things:

  1. Register a health check in the DI: builder.Services.AddHealthChecks();
  2. Add a middleware and set a path to the health check endpoint: app.UseHealthChecks("/health")

That's it - if your application is able to start, then /health endpoint will return 200 OK and a plain text response with the string "Healthy". Everything else is considered Unhealthy.
However, with this basic configuration, it won't track any major problems. For example, if the database becomes unavailable, the health check will still indicate a Healthy state.

Tuning Health Checks

To define custom logic for health check - just implement IHealthCheck interface and then register the implemented health check like this:

builder.Services.AddHealthChecks()
    .AddCheck<CustomeHealthCheck>("Sample");
Enter fullscreen mode Exit fullscreen mode

However, there are plenty of ready-to-use extensions to cover most of your needs - database management systems, message brokers, check for system info like disk storage, network status, and even a ui tool to observe all this information.

The example usage:

builder.Services.AddHealthChecks()
    .AddSqlServer(
        connectionString: "your-connection-string",
        healthQuery: "SELECT 1;",
        name: "sqlserver",
        failureStatus: HealthStatus.Unhealthy);
Enter fullscreen mode Exit fullscreen mode

Practical usage

Having a health check but not tracking its status doesn't make sense.
The possible options for it are:

  • UI dashboard, which will be accessible by some url inside your application
  • Kubernetes / Docker Health Probes, which allow to configure automatic recovery
  • Add as a metric to Application Insights / Grafana / other tools

Adding a health check will help keep your service available and prevent you from missing any issues.


Thanks for reading,
Wishing you successful deployments and enjoy your coding!

Top comments (1)

Collapse
 
igor_sh_dev profile image
Igor Igor

A lot of developers ignore such a helpful thing.