/basic-redis-rate-limiting-demo-csharp-dot-net

Basic redis rate limiting demo written in C# .net

Primary LanguageC#MIT LicenseMIT

Rate Limiting app in .NET using Redis

This demo shows how how to use Redis in .NET 5 to implement IP Rate limiting to prevent excessive calls to your app from a single client.

Technical Stack

  • Frontend: ASP.NET Core MVC
  • Backend: ASP.NET Core MVC / Redis

How it works?

1. How the data is stored:

  • New responses are added key-ip: SETNX your_ip:PING limit_amount

  • Set a timeout on key: EXPIRE your_ip:PING timeout

2. How the data is accessed:

  • Next responses are get bucket: GET your_ip:PING

  • Next responses are changed bucket: DECRBY your_ip:PING amount

Code used for configuring rate limiting

When configuring constructing our app's middleware in Startup.cs, we initialize the cache client and inject it into our services. We then pull from the configuration the IpRateLimit section, and use that as the configuration for IpRateLimitOptions

using AspNetCoreRateLimit;
// ...

services.AddStackExchangeRedisCache(options =>
{
    options.ConfigurationOptions = ConfigurationOptions.Parse(redisConnectionUrl);
});

services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimit"));
services.AddSingleton<IIpPolicyStore, DistributedCacheIpPolicyStore>();
services.AddSingleton<IRateLimitCounterStore, DistributedCacheRateLimitCounterStore>();
services.AddSingleton<IRateLimitConfiguration,RateLimitConfiguration>();

//...
app.UseIpRateLimiting();

The IpRateLimit section is from the appsettings.json file:

"IpRateLimit": {
  "EnableEndpointRateLimiting": true,
  "StackBlockedRequests": false,
  "RealIPHeader": "X-Real-IP",
  "ClientIdHeader": "X-ClientId",
  "HttpStatusCode": 429,
  "GeneralRules": [
    {
      "Endpoint": "*:/api/*",
      "Period": "10s",
      "Limit": 10
    }
  ]
}

This section dictates the period the path which limitations will be applied to, Endpoint, the period over which restrictions are considered, Period, and the Limit for the number of requests permitted in that period Limit


How to run it locally?

git clone https://github.com/redis-developer/basic-redis-rate-limiting-demo-csharp-dot-net.git

Write in environment variable or Dockerfile actual connection to Redis:

   REDIS_ENDPOINT_URL = "Redis server URI:PORT"
   REDIS_PASSWORD = "Password to the server"

Run backend

dotnet run

Static content runs automatically with the backend part.

Try it out

Deploy to Heroku

Deploy to Heorku

Deploy to Google Cloud

Run on Google Cloud