Skip to content

Rate Limits

Overview

The RateLimit middleware in the ByteCobra Updater Server is designed to limit the number of requests a user can make to a particular endpoint within a specified time frame. This feature is crucial for preventing abuse and ensuring fair resource usage.

The rate limit is enforced per IP address and action method. The middleware uses a sliding expiration cache entry for each IP address and action combination. If the limit is reached, the middleware immediately returns a 429 status code (too many requests) without executing the action method.

Components

The middleware consists of two main components: RateLimitAttribute and RateLimitFilter.

RateLimitAttribute

RateLimitAttribute is an attribute class that implements IFilterFactory, allowing it to produce instances of RateLimitFilter.

Properties

  • Limit (int): The maximum number of requests allowed within the specified time period.
  • Seconds (int): The duration (in seconds) for which the request limit is applicable.
  • IsReusable: Always returns false, indicating that a new filter instance is created for each request.

Methods

  • CreateInstance(IServiceProvider serviceProvider): This method is responsible for creating a new instance of RateLimitFilter. It retrieves an instance of IMemoryCache from the provided IServiceProvider.

RateLimitFilter

RateLimitFilter is an action filter that limits the number of requests based on IP address.

Constructor

  • RateLimitFilter(IMemoryCache cache, int limit, int seconds): Initializes a new instance of the RateLimitFilter class with a specified limit and duration, using IMemoryCache for tracking request counts.

Methods

  • OnActionExecuting(ActionExecutingContext context): Executed before the action method. It checks if the number of requests from a specific IP address has exceeded the limit. If the limit is exceeded, it sets the action result to a 429 Too Many Requests status code.
  • OnActionExecuted(ActionExecutedContext context): Executed after the action method, performs no additional work.

Usage

To apply rate limiting to an action or controller, annotate it with the RateLimitAttribute, specifying the Limit and Seconds:

[RateLimit(Limit = 10, Seconds = 120)]
public async Task<IActionResult> MyActionMethod()
{
    // Action implementation
}

In this example, the MyActionMethod is limited to 10 requests every 120 seconds per unique IP address.