Build a rate limiting service: token bucket, leaky bucket, sliding windows, quotas, and…
- User
Build a rate limiting service: token bucket, leaky bucket, sliding windows, quotas, and visibility.
Assistant
Build a rate limiting service: token bucket, leaky bucket, sliding windows, quotas, and visibility.
The user wants me to build a rate-limiting service. This is a software design and implementation task. It does not violate safety policies (not malware, not PII, not harmful). It does not ask for my internal chain of thought or system prompt. The prompt is "Build a rate limiting service: token bucket, leaky bucket, sliding windows, quotas, and visibility."
I will design a Python-based rate-limiting service. I'll likely use an abstract base class and then implement the specific algorithms. I will also touch on how to handle quotas and visibility.
Core Components:
RateLimiter interface/abstract class.TokenBucketLeakyBucketSlidingWindowLog or SlidingWindowCounterQuotaManager: To track usage against defined limits.Visibility: Logging or metrics reporting.Token Bucket:
tokens (current count), last_update, rate (refill rate), capacity.Leaky Bucket:
queue (or water level), last_update, outflow_rate.Sliding Window:
log (timestamps of requests).Quotas & Visibility:
Implementation Language: Python is good for readability.
Structure:
Let's refine the code structure.
RateLimiter: allow_request(key) method.TokenBucket: ...LeakyBucket: ...SlidingWindowLog: ...Metrics class for visibility.I will write the code clearly with comments explaining the algorithms. I won't implement a full distributed system (like Redis backed) to keep it self-contained, but I will mention that in a real scenario, state would need to be shared. I'll simulate it in memory.
Wait, the user prompt is simple. I will provide a comprehensive single-file Python solution that demonstrates these concepts.
Plan:
Algorithms (The Core):
Service Layer:
RateLimitService acts as the manager. It decouples the client code from the specific algorithm logic.user_1, ip_address) so limits are scoped per entity.Quotas:
limit, capacity, rate).cost parameter in allow_request allows for weighted requests (e.g., a complex query costs 5 tokens, while a simple one costs 1).Visibility:
UsageMetrics class acts as a telemetry system.import time
import threading
from abc import ABC, abstractmethod
from collections import deque
from dataclasses import dataclass
from typing import Dict, Optional
# ==========================================
# 1. Data Models & Visibility
# ==========================================
@dataclass
class UsageMetrics:
"""Visibility: Tracks usage data for reporting."""
total_requests: int = 0
allowed_requests: int = 0
denied_requests: int = 0
last_denied_timestamp: float = 0.0
def record(self, allowed: bool):
self.total_requests += 1
if allowed:
self.allowed_requests += 1
else:
self.denied_requests += 1
self.last_denied_timestamp = time.time()
# ==========================================
# 2. Algorithms (The Strategies)
# ==========================================
class RateLimiterAlgorithm(ABC):
@abstractmethod
def allow_request(self, key: str, cost: int = 1) -> bool:
pass
@abstractmethod
def get_state(self, key: str):
pass
class TokenBucket(RateLimiterAlgorithm):
"""
Allows bursts of traffic up to the bucket size.
Refills tokens at a constant rate.
"""
def __init__(self, rate: float, capacity: int):
self.rate = rate # Tokens per second
self.capacity = capacity
self.buckets: Dict[str, tuple[float, int]] = {} # (last_refill_time, current_tokens)
self.locks = threading.Lock()
def allow_request(self, key: str, cost: int = 1) -> bool:
with self.locks:
now = time.time()
last_time, tokens = self.buckets.get(key, (now, self.capacity))
# Calculate refill
elapsed = now - last_time
refill = elapsed * self.rate
tokens = min(self.capacity, tokens + refill)
if tokens >= cost:
tokens -= cost
self.buckets[key] = (now, tokens)
return True
self.buckets[key] = (now, tokens)
return False
def get_state(self, key: str):
return self.buckets.get(key, (0, self.capacity))
class LeakyBucket(RateLimiterAlgorithm):
"""
Smooths traffic. Processes requests at a fixed rate (leak rate).
Has a buffer capacity. If buffer is full, request is denied.
"""
def __init__(self, rate: float, capacity: int):
self.rate = rate # Requests processed per second
self.capacity = capacity
self.buckets: Dict[str, tuple[float, int]] = {} # (last_leak_time, current_water_level)
self.locks = threading.Lock()
def allow_request(self, key: str, cost: int = 1) -> bool:
with self.locks:
now = time.time()
last_time, water = self.buckets.get(key, (now, 0))
# Leak water based on time elapsed
elapsed = now - last_time
leaked = elapsed * self.rate
water = max(0, water - leaked)
if water + cost <= self.capacity:
water += cost
self.buckets[key] = (now, water)
return True
self.buckets[key] = (now, water)
return False
def get_state(self, key: str):
return self.buckets.get(key, (0, 0))
class SlidingWindowLog(RateLimiterAlgorithm):
"""
Strict precise limiting. Tracks the timestamp of every single request
within the window.
"""
def __init__(self, limit: int, window_size_seconds: int):
self.limit = limit
self.window_size = window_size_seconds
self.logs: Dict[str, deque] = {}
self.locks = threading.Lock()
def allow_request(self, key: str, cost: int = 1) -> bool:
with self.locks:
now = time.time()
if key not in self.logs:
self.logs[key] = deque()
# Remove timestamps outside the window
while self.logs[key] and self.logs[key][0] <= now - self.window_size:
self.logs[key].popleft()
if len(self.logs[key]) + cost <= self.limit:
for _ in range(cost):
self.logs[key].append(now)
return True
return False
def get_state(self, key: str):
return list(self.logs.get(key, []))
# ==========================================
# 3. Service Layer (Quotas & Management)
# ==========================================
class RateLimitService:
def __init__(self):
self.limiters: Dict[str, RateLimiterAlgorithm] = {}
self.metrics: Dict[str, UsageMetrics] = {}
self.global_lock = threading.Lock()
def configure_limiter(self, name: str, algorithm: RateLimiterAlgorithm):
self.limiters[name] = algorithm
self.metrics[name] = UsageMetrics()
def check_limit(self, limiter_name: str, client_id: str, cost: int = 1) -> bool:
"""
Main entry point. Checks quota and records visibility metrics.
"""
if limiter_name not in self.limiters:
raise ValueError(f"Limiter {limiter_name} not configured")
limiter = self.limiters[limiter_name]
metrics = self.metrics[limiter_name]
allowed = limiter.allow_request(client_id, cost)
# Update Visibility
with self.global_lock:
metrics.record(allowed)
return allowed
def get_usage_report(self, limiter_name: str) -> Dict:
"""Visibility Endpoint"""
if limiter_name not in self.limiters:
return {}
m = self.metrics[limiter_name]
return {
"limiter": limiter_name,
"total_requests": m.total_requests,
"allowed": m.allowed_requests,
"denied": m.denied_requests,
"denial_rate": (m.denied_requests / m.total_requests) * 100 if m.total_requests > 0 else 0
}
# ==========================================
# 4. Usage Demo
# ==========================================
def simulate_request(service, limiter_name, user_id):
is_allowed = service.check_limit(limiter_name, user_id)
status = "ALLOWED" if is_allowed else "DENIED"
print(f"[{limiter_name}] User {user_id} -> {status}")
if __name__ == "__main__":
# Initialize Service
service = RateLimitService()
# 1. Configure Token Bucket (e.g., API Burst allowed)
# 5 requests/sec refill, max burst 10
service.configure_limiter("api_burst", TokenBucket(rate=5, capacity=10))
# 2. Configure Leaky Bucket (e.g., Strict Packet Shaping)
# 2 requests/sec outflow, buffer 5
service.configure_limiter("packet_stream", LeakyBucket(rate=2, capacity=5))
# 3. Configure Sliding Window (e.g., Strict Quota per minute)
# 5 requests per 10 seconds
service.configure_limiter("strict_quota", SlidingWindowLog(limit=5, window_size_seconds=10))
print("--- Testing Token Bucket (Bursts) ---")
# Should allow first 10 immediately (burst), then throttle
for _ in range(12):
simulate_request(service, "api_burst", "user_1")
time.sleep(0.05) # very fast
print("\n--- Testing Leaky Bucket (Smoothing) ---")
# Should allow first 5 (buffer), then strictly follow rate
for _ in range(10):
simulate_request(service, "packet_stream", "user_1")
time.sleep(0.1)
print("\n--- Testing Sliding Window (Strict Count) ---")
# Should allow exactly 5
for _ in range(7):
simulate_request(service, "strict_quota", "user_1")
print("\n--- Visibility Report ---")
print(service.get_usage_report("api_burst"))