Implementing API Rate Limiting in DotNetCore APIs

What is Rate Limiting:

APIs use rate limitation to control and limit the amount of requests a client can make within a specified time range. It guarantees that the API stays stable and accessible to all users, preventing misuse or overuse that could impact its performance.

Why need Rate Limit:

  1. Protection against DoS Attacks: Rate limiting can protect your API endpoints from Distributed Denial-of-Service (DDoS) attacks by reducing the amount of requests per client. This keeps your server infrastructure from becoming overburdened and assures smooth operation even under high-traffic conditions.
  2. Prevents overloading of servers or applications: By establishing rate limitations, you can efficiently manage and utilize your server resources. It aids in the prevention of resource exhaustion and provides optimal performance for all API users by preventing any single client from monopolizing available resources.

1. Configuring Rate Limiting:

  1. Add Nuggets: Before we start implementing rate limiting, we should install the AspNetCoreRateLimit packages in your project. You can install them either from the NuGet Package Manager tool inside Visual Studio or, from the NuGet Package Manager console using the following commands:

Article content
Install above package

2. Configure Rate Limiting Options and adding Dependencies:

To configure the rate limit you need to go to Program.cs and before the var app = builder.Build(); you need to add the IpRateLimitOptions configuration.

I will add a simple configuration, like below:

 builder.Services.AddMemoryCache();
 builder.Services.AddInMemoryRateLimiting();    
 builder.Services.Configure<IpRateLimitOptions>(option =>
 {
     option.EnableEndpointRateLimiting = true;
     option.StackBlockedRequests = false;
     option.HttpStatusCode = 429;
     option.EndpointWhitelist = new List<string>() { "GET:/api/Demo/GetEmployee" };  
     option.IpWhitelist = new List<string> { "127.0.0.1" };
     option.GeneralRules = new List<RateLimitRule>
     {
         new RateLimitRule
         {
          Endpoint = "*",
          Period = "6s",
          Limit = 2,
      }

     };
 });
 builder.Services.Configure<IpRateLimitPolicies>(builder.Configuration.GetSection("IpRateLimitPolicies"));
 builder.Services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
 builder.Services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
 builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
 builder.Services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();        

The code in the preceding section configures the rate-limiting parameters for an asp.net Core application. It specifies the IpRateLimitOptions class, which is part of the AspNetCoreRateLimit package, using the Configure function. The IpRateLimitOptions class contains properties for configuring IP address rate limiting.

A new list of RateLimitRule objects is added to the GeneralRules property. A rate limit rule that applies to a given endpoint is represented by the RateLimitRule class. The Endpoint property is set to "*" in this case, indicating that the rate limit restriction applies to all endpoints.

The Period attribute is set to "6s," indicating the period for which the rate limit is in effect. In this scenario, the rate limit is applied over 6 seconds.

We may also white-list the endpoint by supplying it to the "EndpointWhitelist" property, for example, I passed this "GET:/api/Demo/GetEmployee" endpoint so that the rate limit would not be applied to this rate limit.

We can apply for whitelisting the an IP address by passing the IP address list to the "IP whitelist" property as above.

Each line of code does the following:

  • builder.Services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>():The MemoryCacheIpPolicyStore class is registered as a singleton service for storing IP address policies in this line of code. This service stores the policies that determine whether or not a given IP address should be rate-limited.
  • builder.Services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(): The MemoryCacheRateLimitCounterStore class is registered as a singleton service for storing rate limit counters in this line of code. This service records the amount of queries made by each IP address during a specified period.
  • builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>(): Registers the RateLimitConfiguration class as a singleton service for configuring rate limit settings. This service is used to configure the application's general and endpoint-specific rate limit restrictions.
  • builder.Services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>(): This line of code registers the AsyncKeyLockProcessingStrategy class as a singleton service for processing rate-limiting requests. This service is used to handle concurrent rate limit requests, ensuring that only one request is processed at a time.

3. Configure Rate Limiting Middleware :

There is one last step for everything to be configured as expected, and that is to add IpRateLimiting as part of the HTTP request pipeline.

For that, you can use the following line:

  • app.UseIpRateLimiting();

4. Testing:

I've set it up so that if we use the GetEmpoyee api more than twice in a 6-second period, we will receive the following error.


Article content

There are more ways we can setup the Rate Limit i am share the link as below.






Good explanation with simple example. Keep it up Ankit.

Like
Reply

To view or add a comment, sign in

More articles by Ankit Panwar

Explore content categories