LeaderElection 1.0.3

dotnet add package LeaderElection --version 1.0.3
                    
NuGet\Install-Package LeaderElection -Version 1.0.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="LeaderElection" Version="1.0.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="LeaderElection" Version="1.0.3" />
                    
Directory.Packages.props
<PackageReference Include="LeaderElection" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add LeaderElection --version 1.0.3
                    
#r "nuget: LeaderElection, 1.0.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package LeaderElection@1.0.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=LeaderElection&version=1.0.3
                    
Install as a Cake Addin
#tool nuget:?package=LeaderElection&version=1.0.3
                    
Install as a Cake Tool

Leader Election

A C# implementaion of the distributed leader election pattern using common paradigms.

Features

  • Async/Await Support: Full async/await pattern support for better performance and scalability
  • Comprehensive Error Handling: Robust error handling with retry logic and exponential backoff
  • Structured Logging: Integration with Microsoft.Extensions.Logging for observability
  • Configuration Options: Flexible configuration through options pattern
  • Event-Driven: Leadership change and error events for reactive programming
  • Graceful Shutdown: Proper cleanup and resource disposal
  • Thread Safety: Thread-safe operations with proper synchronization

Quick Start

1. Install the Package

dotnet add package LeaderElection
dotnet add package LeaderElection.Redis

2. Configure Services

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;
});

3. Use in Your Service

public class MyService : BackgroundService
{
    private readonly ILeaderElection _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");
    }
}

API Reference

Methods

  • StartAsync(CancellationToken) - Start the leader election process
  • StopAsync(CancellationToken) - Stop the leader election process
  • TryAcquireLeadershipAsync(CancellationToken) - Manually attempt to acquire leadership
  • RunTaskIfLeaderAsync(Func<Task>, CancellationToken) - Execute a task only if this instance is the leader
  • RunTaskIfLeaderAsync(Action, CancellationToken) - Execute a synchronous task only if this instance is the leader

Properties

  • IsLeader - Returns true if this instance is currently the leader
  • LastLeadershipRenewal - Date/Time of the last accquisition of leadership

Events

  • LeadershipChanged - Fired when leadership status changes
  • ErrorOccurred - Fired when an error occurs during leader election

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

MIT 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.

Icon

"Business icon pack leader icon" by mr icons is licensed under CC BY 4.0

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on LeaderElection:

Package Downloads
LeaderElection.BlobStorage

Package Description

LeaderElection.Redis

Package Description

LeaderElection.DistributedCache

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.3 160 7/9/2025
1.0.2 128 7/6/2025
1.0.1 124 7/6/2025
1.0.0 134 7/6/2025