Skip to content

Instantly share code, notes, and snippets.

@whiler
Last active June 8, 2022 21:19
Show Gist options
  • Save whiler/c27d60e23025a07cafbb1dd62e66c9aa to your computer and use it in GitHub Desktop.
Save whiler/c27d60e23025a07cafbb1dd62e66c9aa to your computer and use it in GitHub Desktop.
simplest rate limiting algorithm in python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Ref. https://stackoverflow.com/questions/667508/whats-a-good-rate-limiting-algorithm#answer-668327
import time
def limit(rate, burst=0.0):
unit = 1.0
while rate < 1.0:
rate *= 10
unit *= 10
mem = dict(
last = time.time(),
allowance = burst
)
def wrap():
cur = time.time()
elapsed = cur - mem['last']
mem['last'] = cur
mem['allowance'] += elapsed * rate / unit
if mem['allowance'] > rate:
mem['allowance'] = rate
if mem['allowance'] < 1.0:
return False
else:
mem['allowance'] -= 1.0
return True
return wrap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment