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:
- Register a health check in the DI:
builder.Services.AddHealthChecks();
- 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");
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);
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)
A lot of developers ignore such a helpful thing.