-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrate_limiter.py
More file actions
444 lines (355 loc) · 14.3 KB
/
rate_limiter.py
File metadata and controls
444 lines (355 loc) · 14.3 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
"""
Rate Limiting Library - Python Implementation
Provides multiple rate limiting algorithms:
- Token Bucket
- Leaky Bucket
- Fixed Window Counter
- Sliding Window Log
- Sliding Window Counter
"""
import time
import threading
from collections import deque
from abc import ABC, abstractmethod
from typing import Optional, Dict, List
from dataclasses import dataclass
@dataclass
class RateLimitResult:
"""Result of a rate limit check"""
allowed: bool
limit: int
remaining: int
reset_at: float
retry_after: Optional[float] = None
class RateLimiter(ABC):
"""Abstract base class for rate limiters"""
@abstractmethod
def allow_request(self, tokens: int = 1) -> RateLimitResult:
"""Check if request is allowed"""
pass
@abstractmethod
def reset(self):
"""Reset the rate limiter"""
pass
class TokenBucketLimiter(RateLimiter):
"""
Token Bucket Algorithm
Tokens are added at a constant rate. Each request consumes tokens.
Allows bursts up to bucket capacity.
Args:
capacity: Maximum number of tokens in bucket
refill_rate: Tokens added per second
"""
def __init__(self, capacity: int, refill_rate: float):
self.capacity = capacity
self.refill_rate = refill_rate
self.tokens = float(capacity)
self.last_refill = time.time()
self.lock = threading.Lock()
def _refill(self):
"""Add tokens based on elapsed time"""
now = time.time()
elapsed = now - self.last_refill
tokens_to_add = elapsed * self.refill_rate
self.tokens = min(self.capacity, self.tokens + tokens_to_add)
self.last_refill = now
def allow_request(self, tokens: int = 1) -> RateLimitResult:
with self.lock:
self._refill()
if self.tokens >= tokens:
self.tokens -= tokens
return RateLimitResult(
allowed=True,
limit=self.capacity,
remaining=int(self.tokens),
reset_at=time.time() + (self.capacity - self.tokens) / self.refill_rate
)
else:
# Calculate when enough tokens will be available
tokens_needed = tokens - self.tokens
retry_after = tokens_needed / self.refill_rate
return RateLimitResult(
allowed=False,
limit=self.capacity,
remaining=0,
reset_at=time.time() + retry_after,
retry_after=retry_after
)
def reset(self):
with self.lock:
self.tokens = float(self.capacity)
self.last_refill = time.time()
class LeakyBucketLimiter(RateLimiter):
"""
Leaky Bucket Algorithm
Requests are added to a queue and processed at a constant rate.
Enforces strict output rate.
Args:
capacity: Maximum queue size
leak_rate: Requests processed per second
"""
def __init__(self, capacity: int, leak_rate: float):
self.capacity = capacity
self.leak_rate = leak_rate
self.queue = deque()
self.last_leak = time.time()
self.lock = threading.Lock()
def _leak(self):
"""Process requests from queue"""
now = time.time()
elapsed = now - self.last_leak
requests_to_leak = int(elapsed * self.leak_rate)
for _ in range(min(requests_to_leak, len(self.queue))):
self.queue.popleft()
self.last_leak = now
def allow_request(self, tokens: int = 1) -> RateLimitResult:
with self.lock:
self._leak()
if len(self.queue) + tokens <= self.capacity:
for _ in range(tokens):
self.queue.append(time.time())
return RateLimitResult(
allowed=True,
limit=self.capacity,
remaining=self.capacity - len(self.queue),
reset_at=time.time() + len(self.queue) / self.leak_rate
)
else:
return RateLimitResult(
allowed=False,
limit=self.capacity,
remaining=0,
reset_at=time.time() + (len(self.queue) - self.capacity) / self.leak_rate,
retry_after=(len(self.queue) - self.capacity + tokens) / self.leak_rate
)
def reset(self):
with self.lock:
self.queue.clear()
self.last_leak = time.time()
class FixedWindowLimiter(RateLimiter):
"""
Fixed Window Counter Algorithm
Counts requests in fixed time windows.
Simple but has boundary spike issues.
Args:
window_size: Window size in seconds
limit: Maximum requests per window
"""
def __init__(self, window_size: int, limit: int):
self.window_size = window_size
self.limit = limit
self.window_start = 0
self.count = 0
self.lock = threading.Lock()
def _current_window(self) -> int:
"""Get current window start time"""
return int(time.time() // self.window_size) * self.window_size
def allow_request(self, tokens: int = 1) -> RateLimitResult:
with self.lock:
now = time.time()
current_window = self._current_window()
# Reset if in new window
if current_window != self.window_start:
self.window_start = current_window
self.count = 0
if self.count + tokens <= self.limit:
self.count += tokens
return RateLimitResult(
allowed=True,
limit=self.limit,
remaining=self.limit - self.count,
reset_at=self.window_start + self.window_size
)
else:
return RateLimitResult(
allowed=False,
limit=self.limit,
remaining=0,
reset_at=self.window_start + self.window_size,
retry_after=self.window_start + self.window_size - now
)
def reset(self):
with self.lock:
self.window_start = self._current_window()
self.count = 0
class SlidingWindowLogLimiter(RateLimiter):
"""
Sliding Window Log Algorithm
Maintains a log of all request timestamps.
Most accurate but memory intensive.
Args:
window_size: Window size in seconds
limit: Maximum requests per window
"""
def __init__(self, window_size: int, limit: int):
self.window_size = window_size
self.limit = limit
self.requests = deque()
self.lock = threading.Lock()
def _remove_old_requests(self, now: float):
"""Remove requests outside the current window"""
cutoff = now - self.window_size
while self.requests and self.requests[0] <= cutoff:
self.requests.popleft()
def allow_request(self, tokens: int = 1) -> RateLimitResult:
with self.lock:
now = time.time()
self._remove_old_requests(now)
if len(self.requests) + tokens <= self.limit:
for _ in range(tokens):
self.requests.append(now)
return RateLimitResult(
allowed=True,
limit=self.limit,
remaining=self.limit - len(self.requests),
reset_at=self.requests[0] + self.window_size if self.requests else now + self.window_size
)
else:
# Calculate when oldest request will expire
retry_after = (self.requests[0] + self.window_size) - now if self.requests else 0
return RateLimitResult(
allowed=False,
limit=self.limit,
remaining=0,
reset_at=self.requests[0] + self.window_size if self.requests else now,
retry_after=max(0, retry_after)
)
def reset(self):
with self.lock:
self.requests.clear()
class SlidingWindowCounterLimiter(RateLimiter):
"""
Sliding Window Counter Algorithm
Hybrid approach using two fixed windows.
Good balance of accuracy and efficiency.
Args:
window_size: Window size in seconds
limit: Maximum requests per window
"""
def __init__(self, window_size: int, limit: int):
self.window_size = window_size
self.limit = limit
self.current_window = {'start': 0, 'count': 0}
self.previous_window = {'start': 0, 'count': 0}
self.lock = threading.Lock()
def _estimate_count(self, now: float) -> float:
"""Calculate estimated count using sliding window"""
elapsed = now - self.current_window['start']
overlap_pct = max(0, (self.window_size - elapsed) / self.window_size)
return (self.previous_window['count'] * overlap_pct +
self.current_window['count'])
def allow_request(self, tokens: int = 1) -> RateLimitResult:
with self.lock:
now = time.time()
window_start = int(now // self.window_size) * self.window_size
# Move to new window if needed
if window_start != self.current_window['start']:
self.previous_window = self.current_window.copy()
self.current_window = {'start': window_start, 'count': 0}
estimated_count = self._estimate_count(now)
if estimated_count + tokens <= self.limit:
self.current_window['count'] += tokens
return RateLimitResult(
allowed=True,
limit=self.limit,
remaining=max(0, int(self.limit - estimated_count - tokens)),
reset_at=self.current_window['start'] + self.window_size
)
else:
return RateLimitResult(
allowed=False,
limit=self.limit,
remaining=0,
reset_at=self.current_window['start'] + self.window_size,
retry_after=self.current_window['start'] + self.window_size - now
)
def reset(self):
with self.lock:
now = time.time()
window_start = int(now // self.window_size) * self.window_size
self.current_window = {'start': window_start, 'count': 0}
self.previous_window = {'start': 0, 'count': 0}
class ConcurrentRequestsLimiter(RateLimiter):
"""
Concurrent Requests Limiter
Limits the number of simultaneous active requests.
Args:
max_concurrent: Maximum concurrent requests
"""
def __init__(self, max_concurrent: int):
self.max_concurrent = max_concurrent
self.active_requests = 0
self.lock = threading.Lock()
self.condition = threading.Condition(self.lock)
def allow_request(self, tokens: int = 1) -> RateLimitResult:
with self.lock:
if self.active_requests + tokens <= self.max_concurrent:
self.active_requests += tokens
return RateLimitResult(
allowed=True,
limit=self.max_concurrent,
remaining=self.max_concurrent - self.active_requests,
reset_at=0 # N/A for concurrent limiter
)
else:
return RateLimitResult(
allowed=False,
limit=self.max_concurrent,
remaining=0,
reset_at=0,
retry_after=None # Unknown
)
def release(self, tokens: int = 1):
"""Release tokens when request completes"""
with self.lock:
self.active_requests = max(0, self.active_requests - tokens)
self.condition.notify_all()
def reset(self):
with self.lock:
self.active_requests = 0
class MultiTierLimiter:
"""
Multi-tier rate limiter with multiple limits
Example: 10 req/sec AND 1000 req/hour
"""
def __init__(self, limiters: List[RateLimiter]):
self.limiters = limiters
def allow_request(self, tokens: int = 1) -> RateLimitResult:
"""Check all limiters - all must pass"""
results = []
for limiter in self.limiters:
result = limiter.allow_request(tokens)
results.append(result)
if not result.allowed:
# Rollback successful limiters
for prev_limiter in self.limiters[:len(results)-1]:
if hasattr(prev_limiter, 'rollback'):
prev_limiter.rollback(tokens)
return result
# Return most restrictive result
return min(results, key=lambda r: r.remaining)
# Example usage and testing
if __name__ == "__main__":
print("Rate Limiting Library - Python Implementation")
print("=" * 50)
# Token Bucket Example
print("\n1. Token Bucket (capacity=10, rate=2/sec)")
tb = TokenBucketLimiter(capacity=10, refill_rate=2)
for i in range(12):
result = tb.allow_request()
print(f"Request {i+1}: {'✓' if result.allowed else '✗'} "
f"(remaining: {result.remaining})")
# Fixed Window Example
print("\n2. Fixed Window (60s window, 5 req limit)")
fw = FixedWindowLimiter(window_size=60, limit=5)
for i in range(7):
result = fw.allow_request()
print(f"Request {i+1}: {'✓' if result.allowed else '✗'} "
f"(remaining: {result.remaining})")
# Sliding Window Counter Example
print("\n3. Sliding Window Counter (60s window, 10 req limit)")
swc = SlidingWindowCounterLimiter(window_size=60, limit=10)
for i in range(12):
result = swc.allow_request()
print(f"Request {i+1}: {'✓' if result.allowed else '✗'} "
f"(remaining: {result.remaining})")