import time
import threading
from collections import defaultdict
class TokenBucket:
"""
A thread-safe Token Bucket implementation.
"""
def __init__(self, rate, capacity):
"""
:param rate: Refill rate (tokens per second).
:param capacity: Maximum bucket size.
"""
self.rate = rate
self.capacity = capacity
self.tokens = capacity
self.last_refill = time.monotonic()
self.lock = threading.Lock()
def _refill(self):
"""Calculates how many tokens to add based on elapsed time."""
now = time.monotonic()
elapsed = now - self.last_refill
refill_amount = elapsed * self.rate
if refill_amount > 0:
self.tokens = min(self.capacity, self.tokens + refill_amount)
self.last_refill = now
def consume(self, tokens=1):
"""
Attempts to consume tokens.
Returns True if successful, False if rate limit exceeded.
"""
with self.lock:
self._refill()
if self.tokens >= tokens:
self.tokens -= tokens
return True
return False
class FairRateLimiter:
"""
Implements Fairness using Hierarchical Rate Limiting.
Combines a Global Limiter with Per-User Limiters.
"""
def __init__(self, global_rate, global_capacity, user_rate, user_capacity):
"""
:param global_rate: Total requests/sec the server handles.
:param global_capacity: Burst capacity of the server.
:param user_rate: Requests/sec allowed per user.
:param user_capacity: Burst capacity per user.
"""
# The Global Bucket (The "Fairness" Enforcer)
self.global_limiter = TokenBucket(global_rate, global_capacity)
# User Configuration
self.user_rate = user_rate
self.user_capacity = user_capacity
# Dictionary to hold user buckets: { 'user_id': TokenBucket }
self.user_limiters = defaultdict(
lambda: TokenBucket(self.user_rate, self.user_capacity)
)
# Lock for thread-safe access to the dictionary itself
self.dictionary_lock = threading.Lock()
def allow_request(self, user_id):
"""
Checks if a request is allowed for a specific user.
Order of checks is crucial for fairness:
1. Check User Limit (Prevent one user hogging resources).
2. Check Global Limit (Prevent server overload).
"""
# 1. Get or create the user's specific limiter
# We use a lock here to ensure thread-safe creation of new user buckets
with self.dictionary_lock:
user_bucket = self.user_limiters[user_id]
# 2. Check User Limit (Micro-Fairness)
# If the user has exceeded their personal limit, reject immediately.
# This ensures one user cannot spam the API even if the Global limit is empty.
if not user_bucket.consume():
return False, "User Rate Limit Exceeded"
# 3. Check Global Limit (Macro-Protection)
# If the server is overloaded, reject.
# Note: We already deducted a token from the user, but conceptually
# the request stops here. In strict production systems, you might
# implement a 2-phase commit or refund logic, but usually,
# "User Limit < Global Limit" prevents significant drift.
if not self.global_limiter.consume():
return False, "Global Service Unavailable (Overloaded)"
return True, "OK"
# --- Simulation of Fairness ---
def simulate_user(limiter, user_id, requests_to_send):
success_count = 0
fail_count = 0
for _ in range(requests_to_send):
allowed, msg = limiter.allow_request(user_id)
if allowed:
success_count += 1
else:
fail_count += 1
# Simulate network latency/processing time
time.sleep(0.01)
return success_count, fail_count
if __name__ == "__main__":
# Configuration:
# Server handles 50 requests/sec total.
# Each user is capped at 5 requests/sec.
limiter = FairRateLimiter(
global_rate=50,
global_capacity=50,
user_rate=5,
user_capacity=5
)
print("--- Starting Fairness Simulation ---")
print("Config: Global Limit 50/sec | Per-User Limit 5/sec")
print("-" * 40)
# Scenario: 3 users trying to send 20 requests each simultaneously
# Total demand: 60 requests.
# Expected: Each user succeeds 5 times (Total 15 success).
# The Global limit (50) is high enough to handle the aggregate user limits (15).
threads = []
results = {}
users = ["Alice", "Bob", "Charlie"]
def worker(user_id):
s, f = simulate_user(limiter, user_id, 20)
results[user_id] = (s, f)
for user in users:
t = threading.Thread(target=worker, args=(user,))
threads.append(t)
t.start()
for t in threads:
t.join()
total_success = 0
for user, (s, f) in results.items():
print(f"{user}: Success={s}, Failed={f}")
total_success += s
print("-" * 40)
print(f"Total Processed: {total_success}")
print("Conclusion: Notice how no single user could exceed 5 requests, ")
print("preserving fairness even though the server could handle 50.")