See also the CHANGELOG <../CHANGELOG>.
From <=0.4 to 0.5¶
- Rate limits are now counted against fixed, instead of sliding, windows.
- Rate limits are no longer shared between methods by default.
- A key must always be specified. If using without an explicit key, add
skip_ifto a callable
rate=<callable>method (see Rates.
RatelimitMixin(note the lowercase
Before 0.5, rates were counted against a sliding window, so if the
rate limit was
1/m, and three requests came in:
188.8.131.52 [09/Sep/2014:12:25:03] ... 184.108.40.206 [09/Sep/2014:12:25:53] ... <RATE LIMITED> 220.127.116.11 [09/Sep/2014:12:25:59] ... <RATE LIMITED>
Even though the third request came nearly two minutes after the first request, the second request moved the window. Good actors could easily get caught in this, even trying to implement reasonable back-offs.
Starting in 0.5, windows are fixed, and staggered throughout a given period based on the key value, so the third request, above would not be rate limited (it’s possible neither would the second one).
That means that given a rate of
X/u, you may see up to
2 * X
requests in a short period of time. Make sure to set
accordingly if this is an issue.
This change still limits bad actors while being far kinder to good actors.
To avoid a situation where all limits expire at the top of the hour, windows are automatically staggered throughout their period based on the key value. So if, for example, two IP addresses are hitting hourly limits, instead of both of those limits expiring at 06:00:00, one might expire at 06:13:41 (and subsequently at 07:13:41, etc) and the other might expire at 06:48:13 (and 07:48:13, etc).
Using multiple decorators¶
@ratelimit decorator used to be able to ratelimit against
multiple keys, e.g., before 0.5:
@ratelimit(ip=True, field='username', keys=mykeysfunc) def someview(request): # ...
To simplify both the internals and the question of what limits apply, each decorator now tracks exactly one rate, but decorators can be more reliably stacked (c.f. some examples in the section above).
The pre-0.5 example above would need to become four decorators:
@ratelimit(key='ip') @ratelimit(key='post:username') @ratelimit(key='get:username') @ratelimit(key=mykeysfunc) def someview(request): # ...
As documented above, however, this allows powerful new uses, like burst limits and distinct GET/POST limits.