Last active
January 16, 2021 15:29
-
-
Save jshahbazi/71affdc693f8b474f632748613d57040 to your computer and use it in GitHub Desktop.
Async Token Bucket implementation
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
class AsyncTokenBucket(object): | |
"""Implementation of an awaitable token bucket that defaults to a single token at a time. | |
Based on https://code.activestate.com/recipes/511490-implementation-of-the-token-bucket-algorithm/""" | |
def __init__(self, max_tokens, fill_rate): | |
self.max_tokens = float(max_tokens) | |
self.current_tokens = float(max_tokens) | |
self.fill_rate = float(fill_rate) | |
self.wait_time = (1.0 / self.fill_rate) | |
self.timestamp = time.time() | |
async def consume(self, num_tokens=1): | |
while True: | |
now = time.time() | |
if self.current_tokens < self.max_tokens: | |
delta = self.fill_rate * (now - self.timestamp) | |
self.current_tokens = min(self.max_tokens, self.current_tokens + delta) | |
self.timestamp = now | |
if self.current_tokens > num_tokens: | |
self.current_tokens -= num_tokens | |
break | |
else: | |
await asyncio.sleep(self.wait_time) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment