.NET › Background Services
How do background services interact with health checks to signal their operational status?
AdvancedAnswer
A background service can expose its health status by implementing a custom IHealthCheck that inspects shared state (like a 'last successful run' timestamp or an internal flag) the background service updates, letting the health check endpoint report unhealthy if the background service has stalled or crashed -- important for orchestrators like Kubernetes to detect and restart a container whose background processing has silently died even if the web server is still responding.
public class QueueProcessorHealthCheck : IHealthCheck {
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct) {
var timeSinceLastRun = DateTime.UtcNow - QueueProcessor.LastSuccessfulRun;
return Task.FromResult(timeSinceLastRun < 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.