How To Limit The API Calls (Throttling) In .Net Core API

.Net Core API

Nowadays everyone moving to API-based applications since we can reach different kinds of devices through our API. So now we are facing performance and security issues with too much API traffic so we are in the need of addressing these unwanted or too many API calls.

To limit the number of API calls in .Net core API we have an option. In this article, we are going to see that in detail with code samples,

Throttling 

Throttling is a technique used to limit the rate at which an API can be called by clients. This is important to ensure that the API can handle the load and prevent overuse, which can result in reduced performance or even complete downtime. In this article, I will provide an example of how to implement API throttling in .NET Core using middleware.

Throttling is the process of controlling the rate at which an API can be accessed by limiting the number of requests that can be made within a specific time interval. This helps to prevent overloading the API servers, maintain a stable performance, and prevent abuse and unauthorized access.

Here is an example of how to implement API throttling in .NET Core using the IpRateLimitMiddleware,

1. Install the IpRateLimitMiddleware NuGet package:

Install-Package IpRateLimit.Middleware -Version 1.2.0

2. Add the following code to the Startup.cs file to configure the middleware:

using IpRateLimit.Middleware;
public void ConfigureServices(IServiceCollection services) {
    services.AddIpRateLimiting();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
    app.UseIpRateLimiting();
    app.UseRouting();
    app.UseEndpoints(endpoints => {
        endpoints.MapControllers();
    });
}

3. Add the [Throttle] attribute to your API actions to specify the rate limit for each API endpoint:

[Route("api/[controller]")]
[ApiController]
public class ValuesController: ControllerBase {
    [HttpGet]
    [Throttle(Name = "TestThrottle", Seconds = 5, Requests = 5)]
    public ActionResult < IEnumerable < string >> Get() {
        return new string[] {
            "value1",
            "value2"
        };
    }
}

In the example above, the [Throttle] attribute sets a rate limit of 5 requests per 5 seconds for the Get method of the ValuesController. This means that if a client makes more than 5 requests within 5 seconds, subsequent requests will be blocked and a 429 (Too Many Requests) response will be returned.

You can also configure the rate limits globally using the appsettings.json file:

{
    "IpRateLimiting": {
        "GlobalRules": [{
            "Endpoint": "*",
            "Limit": 100,
            "Period": "5m"
        }],
        "ClientRules": [{
            "ClientId": "TestClient",
            "Limit": 50,
            "Period": "1h"
        }]
    }
}

In the example above, the global rule sets a rate limit of 100 requests per 5 minutes for all endpoints, while the client rule sets a rate limit of 50 requests per hour for clients with the TestClient ID.

This is just a basic example of how to implement API throttling in .NET Core using the IpRateLimitMiddleware. You can further customize the throttling behavior by modifying the settings and attributes as needed.

Thanks for reading my article.


Similar Articles