Created
September 3, 2024 21:52
-
-
Save link2xt/dd06897e93d9786f14119802bad2f3db to your computer and use it in GitHub Desktop.
Exponential rate limiter with a single variable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
"""Implementation of exponential rate limiter from <https://dotat.at/@/2024-09-02-ewma.html>, | |
but using a single variable `next-time` to store the state.""" | |
import time | |
import math | |
class RateLimiter: | |
def __init__(self, window, limit): | |
self.next_time = 0.0 | |
self.window = window | |
self.limit = limit | |
def rate_at(self, t): | |
return self.limit * math.exp((self.next_time - t) / self.window) | |
def can_send_at(self, t): | |
return t >= self.next_time | |
def can_send(self): | |
return can_send_at(time.time()) | |
def send_at(self, t): | |
self.next_time = t + self.window * math.log( | |
(math.exp((self.next_time - t) / self.window) + 1 / self.limit) | |
) | |
def send(self): | |
self.send_at(time.time()) | |
def main(): | |
rate_limiter = RateLimiter(window=60, limit=30) | |
while True: | |
now = time.time() | |
if now < rate_limiter.next_time: | |
print("sleeping for", rate_limiter.next_time - now) | |
time.sleep(rate_limiter.next_time - now) | |
rate_limiter.send() | |
print(".") | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment