What is Rate Limiting in an API?
In general, rate limiting means restricting how often something can happen in a given time. In software development, it means limiting the number of incoming requests to an application. In simple words, we define how many times a user can access the application in a specific time frame. For example, we may want to stop a user from opening the login page more than 5 times in an hour.
Rate limiting restricts how many requests a client can make in a given time window. A client can call /api/login only 5 times per minute. Rate limiting can be used for managing the flow of incoming requests to an application.
Implementing rate limiting in an ASP.NET Core app can help maintain stability, security, and performance, ensuring a reliable and efficient service for all users.
Why do we need rate limiting?
To secure our application's resources and prevent overuse, we use rate limiting. It is a very efficient technique in API development. Below are a few reasons why we need rate limiters in our APIs.
- Brute-force login attempts
- API scraping
- DDoS attacks
- Accidental traffic spikes
- Unfair consumption of resources
Install the AspNetCoreRateLimit package from the NuGet Package Manager, as shown in the image below.
After installing the packages your Solution Explorer will look like the image below.
Now add the IpRateLimiting configuration to the appsettings.json file, as shown in the code and image below.
Now register the IP rate-limiting services and middleware in the Program.cs file, as shown in the code and image below.
Now run the API and call one of the endpoints more than 5 times. It returns a response code 429 with the default message "API Calls Quota exceeded!Maximum attempted 5 per 1h". In the image below you can see the response from the API after it was called more than 5 times. This is the default response message; we can customise it based on our requirements.
In the result above, the limit applies to all resources/endpoints. If you want to set a limit on specific endpoints, configure those endpoints in the appsettings.json file, as you can see in the image below. To set a limit on the "/api/BoothMaster/GetAllBooths" endpoint, the appsettings.json file looks like this: