AspNetCoreRateLimit icon indicating copy to clipboard operation
AspNetCoreRateLimit copied to clipboard

How to order rules so that more specific rules override more general rules

Open jslaybaugh opened this issue 2 years ago • 2 comments

I have a more complicated setup, but I've simplified it for the purposes of this question.

Imagine that I want every endpoint to be limited to 5 per 20s. I configure as follows:

options.GeneralRules = new List<RateLimitRule>
{
	new RateLimitRule { Endpoint = "*", Period = "20s", Limit = 5 }
};

And that works fine. However, now I want a specific endpoint to be limited either more or less than that. I presumed I would either place it before or after it in the list. However, I cannot seem to get any combination of all/some of these to work. They all result in "Quota exceeded. Maximum allowed: 5 per 20s. Please try again in 11 second(s)." because it appears it is always applying the * rule:

options.GeneralRules = new List<RateLimitRule>
{
	new RateLimitRule { Endpoint = "get:foo/bar", 	Period = "20s", Limit = 1 },
	new RateLimitRule { Endpoint = "get:foo/bar", 	Period = "20s", Limit = 10 },
	new RateLimitRule { Endpoint = "*", 			Period = "20s", Limit = 5 },
	new RateLimitRule { Endpoint = "get:foo/bar", 	Period = "20s", Limit = 1 },
	new RateLimitRule { Endpoint = "get:foo/bar", 	Period = "20s", Limit = 10 },
};

How can I have a general catch-all rule, and then provide exceptions that are either more strict or more loose?

jslaybaugh avatar Apr 18 '23 21:04 jslaybaugh

Anyone have any suggestions on how to accomplish this?

jslaybaugh avatar May 02 '23 14:05 jslaybaugh

Based on the source code, the logic is to use the most restrictive limit for each period. This allows you to define a general catch-all rule and more strict rules for specific endpoints. However, you cannot override the general rule with more loose rules for specific endpoints.

I think the endpoint should be defined as get:/foo/bar.

BalintBanyasz avatar Apr 24 '24 10:04 BalintBanyasz