-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnaive_rate_limiting.py
38 lines (31 loc) · 1.04 KB
/
naive_rate_limiting.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env python
# __author__ = "Ronie Martinez"
# __copyright__ = "Copyright 2019, Ronie Martinez"
# __credits__ = ["Ronie Martinez"]
# __license__ = "MIT"
# __maintainer__ = "Ronie Martinez"
# __email__ = "[email protected]"
import time
from client import get_redis_client
from exceptions import RateLimitExceeded
def rate_per_second(function, count):
client = get_redis_client()
key = f"rate-limit:{int(time.time())}"
if int(client.incr(key)) > count:
raise RateLimitExceeded
if client.ttl(key) == -1: # timeout is not set
client.expire(key, 1) # expire in 1 second
return function()
def my_function():
pass # do something
if __name__ == '__main__':
success = fail = 0
for i in range(2000):
try:
rate_per_second(my_function, 100) # example: 100 requests per second
success += 1
except RateLimitExceeded:
fail += 1
time.sleep(5/1000) # sleep every 5 milliseconds
print(f"Success count = {success}")
print(f"Fail count = {fail}")