Last active
September 28, 2023 15:49
-
-
Save gtors/ba0f1d02e5982d9297c02a0c06766086 to your computer and use it in GitHub Desktop.
simple per second rate limiter
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
def rate_limit_per_second(rate: int): | |
last_request = time.time() | |
lock = asyncio.Lock() | |
@contextlib.asynccontextmanager | |
async def rate_limiter(): | |
nonlocal last_request, lock | |
async with lock: | |
now = time.time() | |
elapsed = now - last_request | |
to_sleep = 1 / rate - elapsed | |
if to_sleep > 0.0: | |
await asyncio.sleep(to_sleep) | |
last_request = max(now + to_sleep, last_request) | |
else: | |
last_request = max(now, last_request) | |
yield None | |
return rate_limiter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment