Path: redb-route/redb.Route/Processors/LoadBalancer/WeightedStrategy.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/WeightedStrategy.cs
----
using System;
using System.Collections.Generic;
using System.Threading;
using redb.Route.Abstractions;
namespace redb.Route.Processors.LoadBalancer;
///
/// Weighted round-robin load balancer strategy.
/// Endpoints with higher weights receive proportionally more traffic.
/// Thread-safe via lock-free .
///
public sealed class WeightedStrategy : ILoadBalancerStrategy
{
private readonly string[] _expandedEndpoints;
private int _index = -1;
///
/// Creates a weighted strategy from endpoint-weight pairs.
///
/// Tuples of (uri, weight). Weight must be > 0.
public WeightedStrategy(IReadOnlyList<(string Uri, int Weight)> endpointWeights)
{
ArgumentNullException.ThrowIfNull(endpointWeights);
if (endpointWeights.Count == 0)
throw new ArgumentException("At least one endpoint is required.", nameof(endpointWeights));
// Expand into weighted array: (A:3, B:1) → [A, A, A, B]
var expanded = new List();
foreach (var (uri, weight) in endpointWeights)
{
if (weight <= 0)
throw new ArgumentException($"Weight for '{EndpointUri.Sanitize(uri)}' must be positive, got {weight}.", nameof(endpointWeights));
for (var i = 0; i < weight; i++)
expanded.Add(uri);
}
_expandedEndpoints = expanded.ToArray();
}
///
/// Selects the next endpoint using weighted round-robin.
/// Note: the parameter is intentionally unused;
/// weights and their corresponding URIs are fixed at construction time.
///
public string Select(IExchange exchange, IReadOnlyList endpoints)
{
var idx = Interlocked.Increment(ref _index);
return _expandedEndpoints[((idx % _expandedEndpoints.Length) + _expandedEndpoints.Length) % _expandedEndpoints.Length];
}
}