Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add timeout for health checks #1388

Merged
merged 4 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,34 +1,65 @@
using System.Diagnostics;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using StackExchange.Redis;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;

namespace Digdir.Domain.Dialogporten.Infrastructure.HealthChecks;

internal sealed class RedisHealthCheck : IHealthCheck
{
private readonly InfrastructureSettings _settings;
private readonly ILogger<RedisHealthCheck> _logger;
private const int DegradationThresholdInSeconds = 5;

public RedisHealthCheck(IOptions<InfrastructureSettings> options)
public RedisHealthCheck(IOptions<InfrastructureSettings> options, ILogger<RedisHealthCheck> logger)
{
_settings = options?.Value ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
var startTime = Stopwatch.GetTimestamp();
try
{
using var redis = await ConnectionMultiplexer.ConnectAsync(_settings.Redis.ConnectionString);
const int timeout = 15_000;

var options = ConfigurationOptions.Parse(_settings.Redis.ConnectionString);

options.AsyncTimeout = timeout;
options.ConnectTimeout = timeout;
options.SyncTimeout = timeout;

await using var redis = await ConnectionMultiplexer.ConnectAsync(options);
var db = redis.GetDatabase();
await db.PingAsync();

var responseTime = Stopwatch.GetElapsedTime(startTime);

if (responseTime > TimeSpan.FromSeconds(DegradationThresholdInSeconds))
{
_logger.LogWarning("Redis connection is slow ({Elapsed:N1}s).", responseTime.TotalSeconds);
return HealthCheckResult.Degraded($"Redis connection is slow ({responseTime.TotalSeconds:N1}s).");
}

return HealthCheckResult.Healthy("Redis connection is healthy.");
}
catch (RedisTimeoutException ex)
{
var responseTime = Stopwatch.GetElapsedTime(startTime);
_logger.LogWarning("Redis connection timed out ({Elapsed:N1}s).", responseTime.TotalSeconds);
return HealthCheckResult.Unhealthy($"Redis connection timed out after {responseTime.TotalSeconds:N1}s.", exception: ex);
}
catch (RedisConnectionException ex)
{
_logger.LogWarning(ex, "Unable to connect to Redis.");
return HealthCheckResult.Unhealthy("Unable to connect to Redis.", exception: ex);
}
catch (Exception ex)
{
return HealthCheckResult.Unhealthy("An unexpected error occurred while checking Redis health.", exception: ex);
_logger.LogError(ex, "An unexpected error occurred while checking Redis' health.");
return HealthCheckResult.Unhealthy("An unexpected error occurred while checking Redis' health.", exception: ex);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Collections.Concurrent;
using System.Diagnostics;

namespace Digdir.Library.Utils.AspNet.HealthChecks;

Expand All @@ -10,6 +11,8 @@ internal sealed class EndpointsHealthCheck : IHealthCheck
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<EndpointsHealthCheck> _logger;
private readonly List<string> _endpoints;
private const int DegradationThresholdInSeconds = 5;
private const int TimeoutInSeconds = 40;

public EndpointsHealthCheck(
IHttpClientFactory httpClientFactory,
Expand All @@ -32,12 +35,28 @@ public async Task<HealthCheckResult> CheckHealthAsync(
{
try
{
var response = await client.GetAsync(url, cancellationToken);
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(TimeoutInSeconds));

var startTime = Stopwatch.GetTimestamp();
var response = await client.GetAsync(url, cts.Token);
var responseTime = Stopwatch.GetElapsedTime(startTime);

if (!response.IsSuccessStatusCode)
{
_logger.LogWarning("Health check failed for endpoint: {Url}. Status Code: {StatusCode}", url, response.StatusCode);
unhealthyEndpoints.Add($"{url} (Status Code: {response.StatusCode})");
}
else if (responseTime > TimeSpan.FromSeconds(DegradationThresholdInSeconds))
{
_logger.LogWarning("Health check response was slow for endpoint: {Url}. Elapsed time: {Elapsed:N1}s", url, responseTime.TotalSeconds);
unhealthyEndpoints.Add($"{url} (Degraded - Response time: {responseTime.TotalSeconds:N1}s)");
}
}
catch (OperationCanceledException)
{
_logger.LogWarning("Health check timed out for endpoint: {Url}", url);
unhealthyEndpoints.Add($"{url} (Timeout after {TimeoutInSeconds}s)");
}
catch (Exception ex)
{
Expand Down
Loading