| 1 | # ratelimit |
| 2 | |
| 3 | Token-bucket rate limiting. |
| 4 | |
| 5 | ## API |
| 6 | |
| 7 | ```python |
| 8 | from ratelimit import TokenBucket |
| 9 | |
| 10 | bucket = TokenBucket(capacity=3, refill_per_sec=1) |
| 11 | bucket.allow(timestamp) # -> bool |
| 12 | ``` |
| 13 | |
| 14 | Semantics: |
| 15 | |
| 16 | - The bucket starts **full** (`capacity` tokens) at the timestamp of the first |
| 17 | `allow` call. |
| 18 | - On every `allow(t)` call the bucket first refills: |
| 19 | `tokens = min(capacity, tokens + (t - last_t) * refill_per_sec)`, then |
| 20 | records `last_t = t`. The refill happens **whether or not the call is |
| 21 | admitted**. |
| 22 | - If `tokens >= 1` after the refill, one token is consumed and `allow` |
| 23 | returns `True`; otherwise it returns `False` and the (fractional) tokens |
| 24 | are kept. |
| 25 | - Timestamps must be monotonically non-decreasing. |
| 26 |