An easy-to-use C# implementation of the distributed leader election pattern, leveraging common infrastructure tools like Azure Blob Storage, Redis, and others.
$ dotnet add package LeaderElection.FusionCacheA C# implementaion of the distributed leader election pattern using common paradigms.
dotnet add package LeaderElection
dotnet add package LeaderElection.Redis
Look in LeaderElectionTester for a full example.
using LeaderElection.Redis;
var builder = WebApplication.CreateBuilder(args);
// Add Redis connection
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
{
return ConnectionMultiplexer.Connect("localhost:6379");
});
// Add leader election with configuration
builder.Services.AddRedisLeaderElection(settings =>
{
settings.LockKey = "leader_election_tester";
settings.LockExpiry = TimeSpan.FromSeconds(30);
settings.RenewInterval = TimeSpan.FromSeconds(10);
settings.RetryInterval = TimeSpan.FromSeconds(5);
settings.MaxRetryAttempts = 3;
settings.EnableGracefulShutdown = true;
});
public class MyService : BackgroundService
{
private readonly RedisLeaderElection _leaderElection;
private readonly ILogger<MyService> _logger;
public MyService(ILeaderElection leaderElection, ILogger<MyService> logger)
{
_leaderElection = leaderElection;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Subscribe to events
_leaderElection.LeadershipChanged += OnLeadershipChanged;
_leaderElection.ErrorOccurred += OnErrorOccurred;
try
{
// Start leader election
await _leaderElection.StartAsync(stoppingToken);
// Run leader tasks
while (!stoppingToken.IsCancellationRequested)
{
await _leaderElection.RunTaskIfLeaderAsync(async () =>
{
_logger.LogInformation("Executing leader task");
await DoLeaderWorkAsync();
}, stoppingToken);
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
finally
{
// Cleanup
_leaderElection.LeadershipChanged -= OnLeadershipChanged;
_leaderElection.ErrorOccurred -= OnErrorOccurred;
await _leaderElection.StopAsync(stoppingToken);
}
}
private void OnLeadershipChanged(object? sender, bool isLeader)
{
_logger.LogInformation("Leadership changed: {IsLeader}", isLeader);
}
private void OnErrorOccurred(object? sender, Exception exception)
{
_logger.LogError(exception, "Leader election error");
}
}
StartAsync(CancellationToken) - Start the leader election processStopAsync(CancellationToken) - Stop the leader election processTryAcquireLeadershipAsync(CancellationToken) - Manually attempt to acquire leadershipRunTaskIfLeaderAsync(Func<Task>, CancellationToken) - Execute a task only if this instance is the leaderRunTaskIfLeaderAsync(Action, CancellationToken) - Execute a synchronous task only if this instance is the leaderIsLeader - Returns true if this instance is currently the leaderLastLeadershipRenewal - Date/Time of the last accquisition of leadershipLeadershipChanged - Fired when leadership status changesErrorOccurred - Fired when an error occurs during leader electionMIT License
Copyright (c) 2025 Greg James
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"Business icon pack leader icon" by mr icons is licensed under CC BY 4.0