Skip to content

Swevo/PollyRateLimiter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PollyRateLimiter

NuGet NuGet Downloads Build License: MIT

Convenience extension methods for Polly v8 resilience pipelines.

Polly v8 ships with AddConcurrencyLimiter out of the box, but leaves FixedWindow, SlidingWindow, and TokenBucket as bring-your-own. This package fills that gap with one-liner extension methods for all three strategies on top of System.Threading.RateLimiting.

Install

dotnet add package PollyRateLimiter

Usage

using PollyRateLimiter;

// Fixed window: 100 requests per second
var pipeline = new ResiliencePipelineBuilder()
    .AddFixedWindowRateLimiter(permitLimit: 100, window: TimeSpan.FromSeconds(1))
    .Build();

// Sliding window: 100 requests per second, smoothed into 4 segments
var pipeline = new ResiliencePipelineBuilder()
    .AddSlidingWindowRateLimiter(permitLimit: 100, window: TimeSpan.FromSeconds(1), segmentsPerWindow: 4)
    .Build();

// Token bucket: burst up to 200, replenish 50 per second
var pipeline = new ResiliencePipelineBuilder()
    .AddTokenBucketRateLimiter(tokenLimit: 200, tokensPerPeriod: 50, replenishmentPeriod: TimeSpan.FromSeconds(1))
    .Build();

Queue limit

By default, executions that exceed the limit are rejected immediately (queueLimit: 0). Pass a positive value to queue them instead:

var pipeline = new ResiliencePipelineBuilder()
    .AddFixedWindowRateLimiter(permitLimit: 10, window: TimeSpan.FromSeconds(1), queueLimit: 5)
    .Build();

OnRejected callback

Use the optional configure callback to attach an OnRejected handler or change other RateLimiterStrategyOptions:

var pipeline = new ResiliencePipelineBuilder()
    .AddTokenBucketRateLimiter(
        tokenLimit: 100,
        tokensPerPeriod: 20,
        replenishmentPeriod: TimeSpan.FromSeconds(1),
        configure: opts => opts.OnRejected = args =>
        {
            logger.LogWarning("Rate limit exceeded. RetryAfter: {RetryAfter}", args.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retry) ? retry : TimeSpan.Zero);
            return ValueTask.CompletedTask;
        })
    .Build();

Generic builder

All methods work with ResiliencePipelineBuilder<T> too:

var pipeline = new ResiliencePipelineBuilder<HttpResponseMessage>()
    .AddFixedWindowRateLimiter(permitLimit: 50, window: TimeSpan.FromSeconds(1))
    .AddRetry(new RetryStrategyOptions<HttpResponseMessage>())
    .Build();

Comparison with Polly built-ins

Strategy Polly built-in PollyRateLimiter
Concurrency AddConcurrencyLimiter(maxConcurrency)
Fixed window AddFixedWindowRateLimiter(permits, window)
Sliding window AddSlidingWindowRateLimiter(permits, window)
Token bucket AddTokenBucketRateLimiter(capacity, perPeriod, period)

Support

If PollyRateLimiter simplifies your rate limiting setup, consider supporting the project:

Sponsor

💼 Need .NET resilience help? Visit solidqualitysolutions.com for consulting and architecture services.

| PollyMailKit | MailKit SMTP email client | | PollyAzureQueueStorage | Azure Queue Storage QueueClient | | PollyHangfire | Hangfire IBackgroundJobClient |

Also by the same author

🌐 swevo.github.io

Package Description
AutoLog.Generator Compile-time high-performance logging — [Log(Level, Message)] generates LoggerMessage.Define. AOT-safe.
AutoHttpClient.Generator Compile-time typed HTTP client — [HttpClient] on an interface generates a strongly-typed client. AOT-safe Refit alternative.
AutoDispatch.Generator Compile-time CQRS dispatcher — [Handler] generates a strongly-typed IDispatcher. MediatR alternative.
AutoWire Compile-time DI auto-registration — [Scoped]/[Singleton]/[Transient] generates IServiceCollection registration code.
AutoMap.Generator Compile-time object mapping — [Map(typeof(Dto))] generates ToDto() extension methods. AutoMapper alternative.

Related Packages

Package Downloads Description
PollyHealthChecks Downloads ASP.NET Core health checks for Polly v8 circuit breakers — expose circuit-breaker state (Closed, HalfOpen, Open, Isolated) as /health endpoint responses
PollyOpenTelemetry Downloads OpenTelemetry instrumentation for Polly v8 resilience pipelines
PollyBackoff Downloads Backoff delay strategies for Polly v8 resilience pipelines
PollyEFCore Downloads Polly v8 resilience pipelines for Entity Framework Core — wrap every EF Core query and SaveChanges with retry, timeout and circuit-breaker via a single AddPollyResilience() call
PollyRabbitMQ Downloads Polly v8 resilience for RabbitMQ.Client v7+ — retry, circuit-breaker, and timeout for IChannel operations, with built-in RabbitMqTransientErrors predicate covering AlreadyClosedException, BrokerUnreachableException, OperationInterruptedException, and ConnectFailureException
PollyMongo Downloads Polly v8 resilience pipelines for MongoDB.Driver — wrap Find, InsertOne, UpdateOne, DeleteOne and other IMongoCollection calls with retry, timeout, circuit-breaker, and more using a single ResilientMongoCollection decorator
PollyDapper Downloads Polly v8 resilience pipelines for Dapper — wrap QueryAsync, ExecuteAsync, and other Dapper calls with retry, timeout, circuit-breaker, and more using a single ResilientDbConnection decorator
PollyMediatR Downloads Polly v8 resilience pipelines for MediatR — add retry, timeout, circuit-breaker, rate-limiting, hedging, and chaos engineering to any MediatR request handler with a single line of DI registration
PollySqlClient Downloads Polly v8 resilience pipelines for Microsoft.Data.SqlClient (SQL Server and Azure SQL) — retry, timeout, and circuit-breaker for SqlConnection queries and commands, plus a built-in SqlServerTransientErrors predicate covering all common SQL Server and Azure SQL transient error numbers
PollyRedis Downloads Polly v8 resilience for StackExchange.Redis

License

MIT

About

Polly v8 rate limiter integration — easy AddFixedWindow, AddTokenBucket, AddSlidingWindow, AddConcurrency extension methods for ResiliencePipelineBuilder

Topics

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors

Languages