In this lesson, you will learn how to expose health status endpoints within a BackgroundService to ensure your load balancer knows exactly when your worker is ready to process tasks.
Why Background Hosts Need Health Checks
In a typical Web API, the framework automatically handles HTTP requests. However, when running a long-lived BackgroundService, the application might still be "running" even if its internal state is broken (e.g., a message queue connection has dropped or a database handle is stale). Load balancers or orchestrators like Kubernetes need a way to probe your background host to see if it should stay in the rotation or be restarted.
Implementing Health Checks in the Host
Even though your background host isn't serving typical web pages, you can add a lightweight HTTP listener to it using the built-in Microsoft.Extensions.Diagnostics.HealthChecks package.
First, you register the services in your Program.cs or host builder:
builder.Services.AddHealthChecks()
.AddCheck<QueueHealthCheck>("queue_status");
// Build your host
var host = builder.Build();
// Map the endpoint to your host configuration
host.MapHealthChecks("/health");
host.Run();
Inside your QueueHealthCheck class, you implement IHealthCheck. This is where you inject your dependencies—just like you've learned to do with your background tasks—to verify the internal health of your service:
public class QueueHealthCheck : IHealthCheck
{
private readonly IMyQueueService _queueService;
public QueueHealthCheck(IMyQueueService queueService)
=> _queueService = queueService;
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default)
{
return _queueService.IsConnected
? Task.FromResult(HealthCheckResult.Healthy())
: Task.FromResult(HealthCheckResult.Unhealthy("Queue connection lost."));
}
}
By exposing this endpoint, you provide a heartbeat for your background process. If IsConnected returns false, your orchestrator receives an HTTP 503 status, allowing it to signal a restart or divert traffic, preventing your background worker from running in a "zombie" state.
Key Takeaway: Integrating health checks into a background host allows your infrastructure to monitor internal component health and automate recovery for services that aren't traditional HTTP APIs.