{"id":29406327,"url":"https://github.com/gregyjames/leaderelection","last_synced_at":"2026-07-03T22:00:38.902Z","repository":{"id":303184766,"uuid":"1014660337","full_name":"gregyjames/LeaderElection","owner":"gregyjames","description":"An easy-to-use C# implementation of the distributed leader election pattern, leveraging common infrastructure tools like Azure Blob Storage, Redis, and others.","archived":false,"fork":false,"pushed_at":"2026-06-08T09:29:05.000Z","size":585,"stargazers_count":8,"open_issues_count":6,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-06-19T05:32:07.299Z","etag":null,"topics":["blob-storage","coordination","coordinator-pattern","csharp","distributed","distributed-computing","distributed-systems","dotnet","dotnet-core","instances","kubernetes","kubernetes-cluster","leader-election","leadership","microservice","microservices","redis","s3"],"latest_commit_sha":null,"homepage":"https://www.nuget.org/packages/LeaderElection","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gregyjames.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-07-06T06:45:41.000Z","updated_at":"2026-06-07T20:13:29.000Z","dependencies_parsed_at":"2025-07-06T08:02:55.127Z","dependency_job_id":"2611bc4c-0712-4861-9481-4ab01baf318e","html_url":"https://github.com/gregyjames/LeaderElection","commit_stats":null,"previous_names":["gregyjames/leaderelection"],"tags_count":24,"template":false,"template_full_name":null,"purl":"pkg:github/gregyjames/LeaderElection","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gregyjames%2FLeaderElection","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gregyjames%2FLeaderElection/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gregyjames%2FLeaderElection/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gregyjames%2FLeaderElection/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gregyjames","download_url":"https://codeload.github.com/gregyjames/LeaderElection/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gregyjames%2FLeaderElection/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":35102742,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-07-03T02:00:05.635Z","response_time":110,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["blob-storage","coordination","coordinator-pattern","csharp","distributed","distributed-computing","distributed-systems","dotnet","dotnet-core","instances","kubernetes","kubernetes-cluster","leader-election","leadership","microservice","microservices","redis","s3"],"created_at":"2025-07-10T23:19:58.882Z","updated_at":"2026-07-03T22:00:38.896Z","avatar_url":"https://github.com/gregyjames.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![.NET](https://github.com/gregyjames/LeaderElection/actions/workflows/dotnet.yml/badge.svg)](https://github.com/gregyjames/LeaderElection/actions/workflows/dotnet.yml)\n[![codecov](https://codecov.io/gh/gregyjames/LeaderElection/graph/badge.svg?token=3Fmj814UkK)](https://codecov.io/gh/gregyjames/LeaderElection)\n![NuGet Version](https://img.shields.io/nuget/v/LeaderElection?style=flat\u0026label=LeaderElection\u0026link=https%3A%2F%2Fwww.nuget.org%2Fpackages%2FLeaderElection)\n![NuGet Version](https://img.shields.io/nuget/v/LeaderElection.BlobStorage?style=flat\u0026label=LeaderElection.BlobStorage\u0026link=https%3A%2F%2Fwww.nuget.org%2Fpackages%2FLeaderElection.BlobStorage)\n![NuGet Version](https://img.shields.io/nuget/v/LeaderElection.Redis?style=flat\u0026label=LeaderElection.Redis\u0026link=https%3A%2F%2Fwww.nuget.org%2Fpackages%2FLeaderElection.Redis)\n![NuGet Version](https://img.shields.io/nuget/v/LeaderElection.DistributedCache?style=flat\u0026label=LeaderElection.DistributedCache\u0026link=https%3A%2F%2Fwww.nuget.org%2Fpackages%2FLeaderElection.DistributedCache)\n![NuGet Version](https://img.shields.io/nuget/v/LeaderElection.FusionCache?style=flat\u0026label=LeaderElection.FusionCache\u0026link=https%3A%2F%2Fwww.nuget.org%2Fpackages%2FLeaderElection.FusionCache)\n![NuGet Version](https://img.shields.io/nuget/v/LeaderElection.S3?style=flat\u0026label=LeaderElection.S3\u0026link=https%3A%2F%2Fwww.nuget.org%2Fpackages%2FLeaderElection.S3)\n![NuGet Version](https://img.shields.io/nuget/v/LeaderElection.Postgres?style=flat\u0026label=LeaderElection.Postgres\u0026link=https%3A%2F%2Fwww.nuget.org%2Fpackages%2FLeaderElection.Postgres)\n\n# Leader Election\n\nAn easy-to-use C# implementation of the distributed leader election pattern, leveraging common\ninfrastructure tools like Azure Blob Storage, Redis, and others.\n\n## Features\n\n- **Async/Await Support**: Full async/await pattern support for better performance and scalability\n- **Comprehensive Error Handling**: Robust error handling with retry logic and exponential backoff\n- **Structured Logging**: Integration with Microsoft.Extensions.Logging for observability\n- **Configuration Options**: Flexible configuration through options pattern\n- **Event-Driven**: Leadership change and error events for reactive programming\n- **Graceful Shutdown**: Proper cleanup and resource disposal\n- **Thread Safety**: Thread-safe operations with proper synchronization\n\n## Currently Supported Stores\n\n- Redis \u0026rarr; [LeaderElection.Redis](https://www.nuget.org/packages/LeaderElection.Redis)\n- FusionCache \u0026rarr;\n  [LeaderElection.FusionCache](https://www.nuget.org/packages/LeaderElection.FusionCache)\n- DistributedCache \u0026rarr;\n  [LeaderElection.DistributedCache](https://www.nuget.org/packages/LeaderElection.DistributedCache)\n- Azure Blob Storage (blob leases) \u0026rarr;\n  [LeaderElection.BlobStorage](https://www.nuget.org/packages/LeaderElection.BlobStorage)\n- S3 (minio) \u0026rarr; [LeaderElection.S3](https://www.nuget.org/packages/LeaderElection.S3)\n- Postgres \u0026rarr; [LeaderElection.Postgres](https://www.nuget.org/packages/LeaderElection.Postgres)\n\n## Quick Start\n\n### 1. Install the Package\n\n```bash\ndotnet add package LeaderElection\ndotnet add package LeaderElection.Redis\n```\n\n### 2. Configure Services\n\nLook in LeaderElectionTester for a full example.\n\n```csharp\nusing LeaderElection.Redis;\n\nvar builder = WebApplication.CreateBuilder(args);\n\n// Add Redis connection\nbuilder.Services.AddSingleton\u003cIConnectionMultiplexer\u003e(sp =\u003e\n{\n    return ConnectionMultiplexer.Connect(\"localhost:6379\");\n});\n\n// Add leader election with configuration\nbuilder.Services.AddRedisLeaderElection(settings =\u003e\n{\n    settings.LockKey = \"leader_election_tester\";\n    settings.LockExpiry = TimeSpan.FromSeconds(30);\n    settings.RenewInterval = TimeSpan.FromSeconds(10);\n    settings.RetryInterval = TimeSpan.FromSeconds(5);\n    settings.EnableGracefulShutdown = true;\n});\n```\n\n### 3. Use in Your Service\n\nIf you execute this program below, you will notice that leadership is automatically transfered\nacross instances once the current leader is killed!\n\n```csharp\npublic class MyService : BackgroundService\n{\n    private readonly ILeaderElection _leaderElection;\n    private readonly ILogger\u003cMyService\u003e _logger;\n\n    public MyService(ILeaderElection leaderElection, ILogger\u003cMyService\u003e logger)\n    {\n        _leaderElection = leaderElection;\n        _logger = logger;\n    }\n\n    protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n    {\n        // Subscribe to events\n        _leaderElection.LeadershipChanged += OnLeadershipChanged;\n        _leaderElection.ErrorOccurred += OnErrorOccurred;\n\n        try\n        {\n            // Start leader election\n            await _leaderElection.StartAsync(stoppingToken);\n\n            // Run leader tasks\n            while (!stoppingToken.IsCancellationRequested)\n            {\n                await _leaderElection.RunTaskIfLeaderAsync(async ct =\u003e\n                {\n                    _logger.LogInformation(\"Executing leader task\");\n                    await DoLeaderWorkAsync(ct);\n                }, stoppingToken);\n\n                _logger.LogInformation(\"Executing normal task\");\n\n                await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);\n            }\n        }\n        finally\n        {\n            // Cleanup\n            _leaderElection.LeadershipChanged -= OnLeadershipChanged;\n            _leaderElection.ErrorOccurred -= OnErrorOccurred;\n            await _leaderElection.StopAsync(stoppingToken);\n        }\n    }\n\n    private void OnLeadershipChanged(object? sender, bool isLeader)\n    {\n        _logger.LogInformation(\"Leadership changed: {IsLeader}\", isLeader);\n    }\n\n    private void OnErrorOccurred(object? sender, Exception exception)\n    {\n        _logger.LogError(exception, \"Leader election error\");\n    }\n}\n```\n\n## API Reference\n\n### Methods\n\n- `StartAsync(CancellationToken)` - Start the leader election process\n- `StopAsync(CancellationToken)` - Stop the leader election process\n- `TryAcquireLeadershipAsync(CancellationToken)` - Manually attempt to acquire leadership\n- `RunTaskIfLeaderAsync(Func\u003cCancellationToken, Task\u003e, CancellationToken)` - Execute a task only if\n  this instance is the leader\n- `RunTaskIfLeaderAsync(Action\u003cCancellationToken\u003e, CancellationToken)` - Execute a synchronous task\n  only if this instance is the leader\n\n### Properties\n\n- `IsLeader` - Returns true if this instance is currently the leader\n- `LastLeadershipRenewal` - Date/Time of the last accquisition of leadership\n\n### Events\n\n- `LeadershipChanged` - Fired when leadership status changes\n- `ErrorOccurred` - Fired when an error occurs during leader election\n\n## Contributing\n\n1. Fork the repository\n2. Run `./build.ps1 bootstrap`\\* to set up the development environment.\n3. Create a feature branch\n4. Make your changes\n5. Add tests\n6. Review test coverage using `./build.ps1 coverage`.\n7. Submit a pull request\n\nSee `./build.ps1 list` for other common tasks.\n\n_\\* Requires [PowerShell 7.4](https://aka.ms/powershell) or later._\n\n## License\n\nMIT License\n\nCopyright (c) 2025 Greg James\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and\nassociated documentation files (the \"Software\"), to deal in the Software without restriction,\nincluding without limitation the rights to use, copy, modify, merge, publish, distribute,\nsublicense, and/or sell copies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial\nportions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES\nOR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n## Icon\n\n[\"Business icon pack leader icon\"](https://cdn0.iconfinder.com/data/icons/business-1797/32/19-512.png)\nby [mr icons](https://www.iconfinder.com/mr-icons-1) is licensed under\n[CC BY 4.0](http://creativecommons.org/licenses/by/4.0)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgregyjames%2Fleaderelection","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgregyjames%2Fleaderelection","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgregyjames%2Fleaderelection/lists"}