A request limiter based on the Leaky Bucket algorithm
This package is available via install the NuGet:
Install-Package Nancy.LeakyBucketThen, you can enable LeakyBucket rate limiting by enabling the LeakyBucketRateLimiter in your Bootstrapper class:
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
LeakyBucketRateLimiter.Enable(pipelines, new LeakyBucketRateLimiterConfiguration
{
MaxNumberOfRequests = 100,
RefreshRate = TimeSpan.FromSeconds(1)
});
base.ApplicationStartup(container, pipelines);
}
}- When a request comes in it will extract the
IClientIdentifierfrom theNancyContextwith the function specified in the configuration. - It will check for any requests that have passed the specified
RefreshRateand remove them from theIRequestStore. - It will then add the new request to the
IRequestStore. - It will check how many requests are remaining.
- If it exceeds the
MaxNumberOfRequeststhen it will return a 429 Too Many Requests status code, otherwise it will continue on with the request.
The LeakyBucketRateLimiterConfiguration can specifiy an IRequestStore, that is set to the DefaultRequestStore by default, which is responsible for holding the current number of requests for each client.
The LeakyBucketRateLimiterConfiguration can specifies a function that determines what a client is. By default it creates a DefaultClientIdentifier that holds a reference to the remote address.