Path: redb-route/redb.Route/Processors/LoadBalancer/FailoverStrategy.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Processors/LoadBalancer/FailoverStrategy.cs
----
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using redb.Route.Abstractions;
namespace redb.Route.Processors.LoadBalancer;
///
/// Failover load balancer strategy.
/// Selects the first healthy endpoint from an ordered list.
/// Tracks failures per endpoint and allows recovery after a configurable timeout.
/// Thread-safe via .
///
public sealed class FailoverStrategy : ILoadBalancerStrategy
{
private readonly int _maxFailures;
private readonly TimeSpan _recoveryTimeout;
private readonly ConcurrentDictionary _failures = new(StringComparer.Ordinal);
///
/// Creates a failover strategy.
///
/// Number of consecutive failures before an endpoint is considered unhealthy.
/// Time after which a failed endpoint is retried (probing).
public FailoverStrategy(int maxFailures = 3, TimeSpan? recoveryTimeout = null)
{
_maxFailures = maxFailures > 0 ? maxFailures : throw new ArgumentOutOfRangeException(nameof(maxFailures));
_recoveryTimeout = recoveryTimeout ?? TimeSpan.FromSeconds(30);
if (_recoveryTimeout < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(recoveryTimeout), "Recovery timeout must be non-negative.");
}
///
public string Select(IExchange exchange, IReadOnlyList endpoints)
{
if (endpoints.Count == 0)
throw new InvalidOperationException("No endpoints configured for load balancer.");
foreach (var ep in endpoints)
{
if (!_failures.TryGetValue(ep, out var record))
return ep;
if (record.Count < _maxFailures)
return ep;
// Recovery probe: if enough time passed since last failure, try again
if (DateTimeOffset.UtcNow - record.LastFailure > _recoveryTimeout)
return ep;
}
// All endpoints failed — return first and let it fail with proper exception
return endpoints[0];
}
///
public void ReportFailure(string endpoint, Exception exception)
{
_failures.AddOrUpdate(
endpoint,
_ => new FailureRecord(1, DateTimeOffset.UtcNow),
(_, old) => new FailureRecord(old.Count + 1, DateTimeOffset.UtcNow));
}
///
public void ReportSuccess(string endpoint)
{
_failures.TryRemove(endpoint, out _);
}
private sealed record FailureRecord(int Count, DateTimeOffset LastFailure);
}