Back to results for “Health Checks & Readiness/Liveness Probes”
.NET › Background Services

How do background services interact with health checks to signal their operational status?

Advanced

Answer

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.

Common follow-ups: How do you distinguish liveness from readiness for a background-service-heavy application?;What's the risk of a health check that's too aggressive about restarting?