ASP.NET Core › Background Tasks & Hosted Services
How do background services interact with health checks to signal their operational status to an orchestrator like Kubernetes?
AdvancedAnswer
A background service can expose its health via a custom IHealthCheck that inspects shared state (like a 'last successful run' timestamp the service updates on each cycle), letting the health endpoint report unhealthy if the background work has stalled or crashed -- crucial because a web server can still respond to HTTP requests perfectly fine even while its background processing has silently died, so relying solely on basic liveness (process is running) wouldn't catch this failure mode.
public class QueueProcessorHealthCheck : IHealthCheck {
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct) {
var elapsed = DateTime.UtcNow - QueueProcessor.LastSuccessfulRun;
return Task.FromResult(elapsed < TimeSpan.FromMinutes(5)
? HealthCheckResult.Healthy()
: HealthCheckResult.Unhealthy("Queue processor stalled"));
}
}
builder.Services.AddHealthChecks().AddCheck<QueueProcessorHealthCheck>("queue-processor");Real-world example A Kubernetes liveness probe automatically restarts a pod whose background queue processor has been silently stuck for over 5 minutes, detected via a custom health check monitoring the processor's last successful iteration timestamp.