jsocol / django-ratelimit

Cache-based rate-limiting for Django
https://django-ratelimit.readthedocs.io/en/latest/
Other
1.07k stars 187 forks source link

Is sliding time window rate limiting supported? #317

Open Dlvnkenye opened 7 months ago

Dlvnkenye commented 7 months ago

it seems like rate limiting is only base on fixed time window algorithm. this approach can allow Burt request which in my case such burst is costly. I have some services where each request cost me money. Is there a way using djano-ratelimit to enforce a sliding time window rate limiting? or is there a way to implement custom sliding rate limiting?

benjaoming commented 7 months ago

Can you explain what you mean by "sliding time window"? The rate limiting does "slide", as in if you say "10 requests per minute", then it's the previous 10 minutes. You can then apply several rate limiting rules:

@ratelimit(rate="10/m", ...)
@ratelimit(rate="5/s", ...)

or is there a way to implement custom sliding rate limiting?

If that doesn't work, check the callable rates: https://django-ratelimit.readthedocs.io/en/stable/rates.html#callables

Dlvnkenye commented 7 months ago

The sliding window rate limiting algorithm is based on a dynamic time window that moves with time, allowing for more flexibility in managing bursts of traffic which is in contrast to fixed window rate limiting algorithm. For instance applying the following rate limits :

@ratelimit(rate="10/m", ...)
@ratelimit(rate="5/s", ...)

This will only partially mitigate the burst of requests. cause during the last 2 seconds of a time window and the first 2 seconds of the subsequent time window a bad actor can send send 20 request under 4 seconds. this may not be that much in terms of CPU cycles but for some services where each request cost money, this becomes an issue.

benjaoming commented 7 months ago

Did you read about callable rates?

Can you imagine how you would like your decorators too look? (pretend django-ratelimit had the feature that you are looking for)