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 3 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,63 @@
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;

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 sw = System.Diagnostics.Stopwatch.StartNew();
try
{
using var redis = await ConnectionMultiplexer.ConnectAsync(_settings.Redis.ConnectionString);
var timeout = 15000;

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

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

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

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

return HealthCheckResult.Healthy("Redis connection is healthy.");
}
catch (RedisTimeoutException ex)
{
_logger.LogWarning("Redis connection timed out ({Elapsed:N1}s).", sw.Elapsed.TotalSeconds);
return HealthCheckResult.Unhealthy("Redis connection timed out.", 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)
{
_logger.LogError(ex, "An unexpected error occurred while checking Redis health.");
return HealthCheckResult.Unhealthy("An unexpected error occurred while checking Redis health.", exception: ex);
}
finally
{
sw.Stop();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,28 @@ public async Task<HealthCheckResult> CheckHealthAsync(
{
try
{
var response = await client.GetAsync(url, cancellationToken);
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(40));

var sw = System.Diagnostics.Stopwatch.StartNew();
var response = await client.GetAsync(url, cts.Token);
sw.Stop();

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 (sw.Elapsed > TimeSpan.FromSeconds(5))
{
_logger.LogWarning("Health check response was slow for endpoint: {Url}. Elapsed time: {Elapsed:N1}s", url, sw.Elapsed.TotalSeconds);
unhealthyEndpoints.Add($"{url} (Degraded - Response time: {sw.Elapsed.TotalSeconds:N1}s)");
}
}
catch (OperationCanceledException)
{
_logger.LogWarning("Health check timed out for endpoint: {Url}", url);
unhealthyEndpoints.Add($"{url} (Timeout after 40s)");
}
catch (Exception ex)
{
Expand Down
Loading