Skip to content

Instantly share code, notes, and snippets.

@pgjones
Last active September 16, 2019 04:02
Show Gist options
  • Save pgjones/42ff399aead24eb227267842344159aa to your computer and use it in GitHub Desktop.
Save pgjones/42ff399aead24eb227267842344159aa to your computer and use it in GitHub Desktop.
Generic Cell Rate Algorithm example
class RateLimit:
def __init__(self, count: int, period: timedelta) -> None:
self.count = count
self.period = period
@property
def inverse(self) -> float:
return self.period.total_seconds() / self.count
class Store:
def get_tat(self, key: str) -> datetime:
# This should return a previous tat for the key or the current time.
pass
def set_tat(self, key: str, tat: datetime) -> None:
pass
def update(self, key: str, limit: RateLimit) -> bool:
now = datetime.utcnow()
tat = max(self.get_tat(key), now)
separation = (tat - now).total_seconds()
max_interval = limit.period.total_seconds() - limit.inverse
if separation > max_interval:
reject = True
else:
reject = False
new_tat = max(tat, now) + timedelta(seconds=limit.inverse)
self.set_tat(key, new_tat)
return reject
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment