How would you set a per-check timeout to prevent one slow or hanging dependency check from blocking the entire /health endpoint response indefinitely?
Short answer
Wrap the health check's actual work with a CancellationTokenSource-based timeout (either handled manually inside CheckHealthAsync using the passed CancellationToken combined with a timeout token, or via HealthCheckOptions.Timeout at the overall endpoint level) so a single…
Advertisement
AModel answer
Wrap the health check's actual work with a CancellationTokenSource-based timeout (either handled manually inside CheckHealthAsync using the passed CancellationToken combined with a timeout token, or via HealthCheckOptions.Timeout at the overall endpoint level) so a single unresponsive dependency (like a database under heavy load) times out and reports Unhealthy for that specific check rather than causing the entire /health endpoint request to hang indefinitely waiting for a response that may never come.
public class SlowDependencyHealthCheck : IHealthCheck {
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default) {
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeoutCts.CancelAfter(TimeSpan.FromSeconds(3));
try {
await _dependency.PingAsync(timeoutCts.Token);
return HealthCheckResult.Healthy();
} catch (OperationCanceledException) {
return HealthCheckResult.Unhealthy("Dependency check timed out after 3s");
}
}
}Real-world example
A health check for a flaky third-party API is given an explicit 3-second timeout, ensuring that when the third-party API hangs for 30+ seconds, the overall /health endpoint still responds promptly reporting that one specific check as Unhealthy, rather than the entire endpoint (and any load balancer probing it) hanging indefinitely.
Likely follow-ups
- What's the difference between a per-check timeout and the overall HealthCheckOptions timeout at the endpoint level?
- How should a Kubernetes probe's own timeout setting relate to the application's internal health check timeouts?
Related topics