Course contentsShow
← C#
Lesson 1525 of 1,90814. Background Work and MessagingFree lesson

Monitoring Worker Health with HealthChecks

Expose worker service status through the .NET HealthChecks API for container orchestration.

In this lesson, you will learn how to expose the internal state of your background workers to container orchestrators like Kubernetes using the .NET HealthChecks API.

When running background services in production, simply checking if the process is "alive" isn't enough; you need to know if the worker is actually processing tasks or stuck in an error loop. By integrating Microsoft.Extensions.Diagnostics.HealthChecks, we allow the orchestrator to perform liveness and readiness probes directly against our background service.

Implementing a Custom Health Check

To monitor a worker, we implement the IHealthCheck interface. This allows us to inject the state of our service—such as the status of a message queue consumer or a database connection—into the health check report.

public class WorkerHealthCheck : IHealthCheck
{
    private readonly WorkerState _state;

    public WorkerHealthCheck(WorkerState state) => _state = state;

    public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default)
    {
        return _state.IsProcessing 
            ? Task.FromResult(HealthCheckResult.Healthy("Worker is active."))
            : Task.FromResult(HealthCheckResult.Unhealthy("Worker has stalled."));
    }
}

Exposing the Endpoint

Once defined, you register the check in your Program.cs or Startup.cs. Since background workers typically do not host an HTTP server, you often configure a secondary minimal Web API host within the same process specifically to serve the /health endpoint.

builder.Services.AddHealthChecks()
    .AddCheck<WorkerHealthCheck>("background-worker");

// Mapping the endpoint for the orchestrator to ping
app.MapHealthChecks("/health");

When your orchestrator (like Kubernetes) pings the /health endpoint, it receives an HTTP response based on your logic. If the WorkerHealthCheck returns Unhealthy, the orchestrator can automatically restart the container or pull it out of the load balancer rotation, preventing silent failures from impacting your wider system architecture. This proactive approach ensures that your infrastructure is always aware of the background service's operational reality, not just its process status.

Key Takeaway: HealthChecks provide an automated mechanism for container orchestrators to verify the operational logic of your background services beyond simple process availability.