Skip to content

Instantly share code, notes, and snippets.

@gtors
Last active September 28, 2023 15:49
Show Gist options
  • Save gtors/ba0f1d02e5982d9297c02a0c06766086 to your computer and use it in GitHub Desktop.
Save gtors/ba0f1d02e5982d9297c02a0c06766086 to your computer and use it in GitHub Desktop.
simple per second rate limiter
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