LeaderElection.S3
1.0.1
dotnet add package LeaderElection.S3 --version 1.0.1
NuGet\Install-Package LeaderElection.S3 -Version 1.0.1
<PackageReference Include="LeaderElection.S3" Version="1.0.1" />
<PackageVersion Include="LeaderElection.S3" Version="1.0.1" />
<PackageReference Include="LeaderElection.S3" />
paket add LeaderElection.S3 --version 1.0.1
#r "nuget: LeaderElection.S3, 1.0.1"
#:package LeaderElection.S3@1.0.1
#addin nuget:?package=LeaderElection.S3&version=1.0.1
#tool nuget:?package=LeaderElection.S3&version=1.0.1
LeaderElection.S3
An S3-backed implementation of the distributed leader election pattern for .NET. This implementation uses S3 conditional PUT operations (ETags) to ensure safe, atomic leadership acquisition and renewal.
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.S3
2. Configure Services
using LeaderElection.S3;
using Minio; // S3 compatible client
var builder = WebApplication.CreateBuilder(args);
// 1. Register your MinIO S3 client
builder.Services.AddSingleton<IMinioClient>(sp =>
{
return new MinioClient()
.WithEndpoint("localhost:9000")
.WithCredentials("accessKey", "secretKey")
.Build();
});
// 2. Add S3 leader election
builder.Services.AddS3LeaderElection(options =>
{
options.BucketName = "my-app-locks";
options.ObjectKey = "leader-lock.json";
options.LeaseDuration = TimeSpan.FromSeconds(30);
options.RenewInterval = TimeSpan.FromSeconds(10);
});
3. Use in Your Service
public class Worker : BackgroundService
{
private readonly ILeaderElection _leaderElection;
private readonly ILogger<Worker> _logger;
public Worker(ILeaderElection leaderElection, ILogger<Worker> logger)
{
_leaderElection = leaderElection;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Start the background election loop
await _leaderElection.StartAsync(stoppingToken);
while (!stoppingToken.IsCancellationRequested)
{
// Only runs if this instance currently holds the S3 lease
await _leaderElection.RunTaskIfLeaderAsync(async () =>
{
_logger.LogInformation("Instance is leader. Doing work...");
await Task.Delay(1000, stoppingToken);
}, stoppingToken);
await Task.Delay(5000, stoppingToken);
}
}
}
Configuration (S3Settings)
| Property | Default | Description |
|---|---|---|
BucketName |
leader-election |
The S3 bucket to store the lease file. |
ObjectKey |
(required) |
The path/name of the lease JSON file. |
InstanceId |
Environment.MachineName |
Unique ID for this node. |
LeaseDuration |
30s |
How long the lock is valid without a heartbeat. |
RenewInterval |
10s |
How often the leader sends a heartbeat. |
EnableGracefulShutdown |
true |
If true, expires the lease immediately on stop. |
S3 Specifics
This implementation writes a small JSON file to your bucket. To ensure safety:
- It uses
If-None-Match: *when creating a new lock. - It uses
If-Match: [etag]when renewing or taking over an expired lock.
This ensures that even if two instances try to become the leader at the exact same millisecond, S3 will only allow one of them to succeed based on the ETag mismatch protection.
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- 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 | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. 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 is compatible. 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. |
| .NET Core | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.1 is compatible. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.1
- LeaderElection (>= 1.0.1)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.5)
- Microsoft.Extensions.Options (>= 10.0.5)
- Minio (>= 7.0.0)
-
net10.0
- LeaderElection (>= 1.0.1)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.5)
- Microsoft.Extensions.Options (>= 10.0.5)
- Minio (>= 7.0.0)
-
net8.0
- LeaderElection (>= 1.0.1)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.5)
- Microsoft.Extensions.Options (>= 10.0.5)
- Minio (>= 7.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.