Distributed.RateLimit.Redis.AspNetCore 1.1.0

dotnet add package Distributed.RateLimit.Redis.AspNetCore --version 1.1.0
                    
NuGet\Install-Package Distributed.RateLimit.Redis.AspNetCore -Version 1.1.0
                    
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="Distributed.RateLimit.Redis.AspNetCore" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Distributed.RateLimit.Redis.AspNetCore" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="Distributed.RateLimit.Redis.AspNetCore" />
                    
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 Distributed.RateLimit.Redis.AspNetCore --version 1.1.0
                    
#r "nuget: Distributed.RateLimit.Redis.AspNetCore, 1.1.0"
                    
#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 Distributed.RateLimit.Redis.AspNetCore@1.1.0
                    
#: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=Distributed.RateLimit.Redis.AspNetCore&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=Distributed.RateLimit.Redis.AspNetCore&version=1.1.0
                    
Install as a Cake Tool

Distributed Rate Limit By Redis

A distributed rate limiting solution for ASP.NET Core applications using Redis as a backend. This package ensures consistent rate limiting across multiple pods/instances behind a load balancer.

Problem Solved

The standard ASP.NET Core rate limiter doesn't work effectively in distributed environments with multiple pods. When requests are distributed across pods by a load balancer, each pod maintains its own rate limit counter, allowing clients to exceed the intended limit by spreading requests across different pods.

This package solves this by using Redis as a centralized rate limiting store, ensuring consistent enforcement across all instances.

Installation

Install the package via NuGet:

dotnet add package Distributed.RateLimit.Redis
dotnet add package Distributed.RateLimit.Redis.AspNetCore

Usage

  1. Configure the Rate Limiter In your Program.cs or startup configuration:
using DistributedRateLimiting.Redis;

var builder = WebApplication.CreateBuilder(args);

// Add Redis connection multiplexer
var connectionMultiplexer = ConnectionMultiplexer.Connect("your_redis_connection_string");

builder.Services.AddRateLimiter(options =>
{
	options.AddRedisFixedWindowLimiter(RateLimitationConstants.WeatherForecastRateLimit,
		(opt) =>
		{
			opt.ConnectionMultiplexerFactory = () => connectionMultiplexer;
			opt.PermitLimit = 1;
			opt.Window = TimeSpan.FromSeconds(10);
		}, context =>
		{
			var hashKey = "";

			//Create hash from Bearer token
			if (context.Request.Headers.TryGetValue("Authorization", out var authHeader) &&
				!StringValues.IsNullOrEmpty(authHeader))
			{
				var authHeaderValue = authHeader.ToString();
				if (authHeaderValue.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
				{
					hashKey = authHeaderValue.GetSha256Hash();
				}
			}
			else
			{
				// Fall back to remote IP if header not present
				hashKey = (context.Connection.RemoteIpAddress?.ToString() ?? "unknown").GetSha256Hash();
			}

			return hashKey;
		});

    options.OnRejected = (context, cancellationToken) =>
    {
        context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
        return new ValueTask();
    };
});

var app = builder.Build();

app.UseRateLimiter();
  1. Apply Rate Limiting to Endpoints Apply rate limiting to your controllers or actions using the [EnableRateLimiting] attribute:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    [EnableRateLimiting(RateLimitationConstants.WeatherForecastRateLimit)]
    public IEnumerable<WeatherForecast> Get()
    {
        // Your action logic
    }
}

Configuration Options

The AddRedisFixedWindowLimiter method accepts the following configuration:

ConnectionMultiplexerFactory: Factory function to get Redis connection

PermitLimit: Maximum number of requests allowed in the time window

Window: Time window duration

QueueLimit (optional): Maximum number of requests that can be queued when the limit is reached

AutoReplenishment (optional): Whether to auto-replenish permits

The partition key function determines how to identify clients. The example uses the X-Forwarded-For header (common in load-balanced environments) with a fallback to the remote IP address.

Performance Considerations

Redis operations are fast, but network latency should be considered

For high-traffic applications, ensure your Redis instance is properly scaled

The library minimizes Redis operations by using efficient Lua scripts

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

License

MIT License.

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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 174 4/9/2025
1.0.1 149 3/17/2025
1.0.0 145 3/17/2025

Initial release.