import time
from collections import defaultdict, deque
from threading import Lock, Thread
from typing import Optional, Dict, Any
import logging
# Optional: Integrate with FastAPI for real-world use
# pip install fastapi uvicorn
# from fastapi import FastAPI, Request, HTTPException
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class TokenBucket:
"""
Leaky token bucket for per-client rate limiting.
"""
def __init__(self, rate: float, burst: float = None):
self.rate = rate # tokens per second (QPS)
self.capacity = burst or rate * 2 # burst capacity
self.tokens = self.capacity
self.last_update = time.time()
def consume(self) -> bool:
now = time.time()
# Refill tokens
delta = now - self.last_update
self.tokens = min(self.capacity, self.tokens + delta * self.rate)
self.last_update = now
if self.tokens >= 1.0:
self.tokens -= 1.0
return True
return False
def update_rate(self, new_rate: float, new_burst: Optional[float] = None):
self.rate = new_rate
if new_burst is not None:
self.capacity = new_burst
self.tokens = min(self.capacity, self.tokens)
class QPSAdmissionController:
"""
QPS Admission Controller with:
- Dynamic budgets: Adjusts per-client budgets based on total capacity,
active clients, and historical fairness (proportional to past peak usage).
- Fairness: Weighted proportional share (weights from historical peak QPS).
Falls back to equal share if no history.
- SLO-aware shedding: Monitors mock latency (replace with real metrics).
Sheds low-priority (bronze) requests first when overloaded.
Client key: e.g., 'user_id:123' or 'ip:10.0.0.1'.
SLO classes: 'gold' (critical, never shed), 'silver' (shed last), 'bronze' (shed first).
"""
def __init__(
self,
total_capacity: float = 1000.0, # Global QPS capacity
slo_latency_threshold: float = 0.100, # 100ms p99 SLO
history_window: int = 60, # seconds of history for weights
eviction_timeout: int = 300, # evict inactive clients after 5min
metrics_update_interval: float = 1.0 # update metrics every second
):
self.total_capacity = total_capacity
self.slo_latency_threshold = slo_latency_threshold
self.history_window = history_window
self.eviction_timeout = eviction_timeout
self.client_buckets: Dict[str, TokenBucket] = {}
self.client_last_seen: Dict[str, float] = {}
self.client_history: Dict[str, deque] = defaultdict(deque) # timestamped QPS samples
self.client_weights: Dict[str, float] = {} # derived from peak history
self.current_latency_p99 = 0.0 # Mock; replace with Prometheus/StatsD
self.global_qps = 0.0 # Track for logging
self.lock = Lock()
# Background thread for metrics and budget reallocation
self.running = True
self.metrics_thread = Thread(target=self._metrics_loop, args=(metrics_update_interval,))
self.metrics_thread.daemon = True
self.metrics_thread.start()
def _metrics_loop(self, interval: float):
"""Simulate latency monitoring and periodic budget reallocation."""
while self.running:
time.sleep(interval)
with self.lock:
# Mock: latency increases with load (replace with real metric)
load_factor = min(self.global_qps / self.total_capacity, 2.0)
self.current_latency_p99 = 0.05 + 0.1 * load_factor # 50-250ms mock
# Evict inactive clients
now = time.time()
to_evict = [
client for client, last in self.client_last_seen.items()
if now - last > self.eviction_timeout
]
for client in to_evict:
del self.client_buckets[client]
del self.client_last_seen[client]
self.client_history[client].clear()
logger.info(f"Evicted inactive client: {client}")
# Reallocate budgets dynamically
self._allocate_budgets()
logger.debug(f"Reallocated budgets. Latency p99: {self.current_latency_p99:.3f}s, Global QPS: {self.global_qps:.1f}")
def _allocate_budgets(self):
"""Dynamic budget allocation with fairness."""
active_clients = list(self.client_buckets.keys())
if not active_clients:
return
# Compute weights from historical peak QPS (fairness)
total_weight = 0.0
for client in active_clients:
history_qps = [qps for ts, qps in self.client_history[client] if time.time() - ts < self.history_window]
peak_qps = max(history_qps) if history_qps else 1.0
self.client_weights[client] = peak_qps
total_weight += peak_qps
if total_weight == 0:
total_weight = len(active_clients) # Fallback to equal
# Dynamic total capacity: scale down if approaching SLO violation
dynamic_capacity = self.total_capacity * max(0.5, 1.0 - (self.current_latency_p99 / (self.slo_latency_threshold * 2)))
for client in active_clients:
weight_share = self.client_weights[client] / total_weight
client_rate = dynamic_capacity * weight_share
burst = client_rate * 2 # Allow small burst
self.client_buckets[client].update_rate(client_rate, burst)
def admit(self, client_key: str, slo_class: str = 'bronze') -> bool:
"""
Admit request. Returns True if admitted, False if rate-limited or shed.
Call this before processing the request.
"""
if not client_key:
logger.warning("No client key provided; denying")
return False
now = time.time()
admitted = False
with self.lock:
self.client_last_seen[client_key] = now
# Lazy-init bucket
if client_key not in self.client_buckets:
self.client_buckets[client_key] = TokenBucket(0.0) # Starts at 0, allocates on next cycle
logger.info(f"New client: {client_key}")
# SLO-aware shedding
overloaded = self.current_latency_p99 > self.slo_latency_threshold
if overloaded:
if slo_class == 'bronze':
logger.info(f"Shedding bronze request from {client_key} (overloaded)")
return False
elif slo_class == 'silver' and self.current_latency_p99 > self.slo_latency_threshold * 1.5:
logger.info(f"Shedding silver request from {client_key} (critically overloaded)")
return False
# Gold never shed
# Consume token
bucket = self.client_buckets[client_key]
admitted = bucket.consume()
if admitted:
self.global_qps += 1
# Record for history (sampled)
if len(self.client_history[client_key]) == 0 or now - self.client_history[client_key][-1][0] > 10:
self.client_history[client_key].append((now, bucket.rate)) # Use allocated rate as proxy
# Trim history
while self.client_history[client_key] and now - self.client_history[client_key][0][0] > self.history_window:
self.client_history[client_key].popleft()
if not admitted:
logger.warning(f"Rate limited {client_key} (SLO: {slo_class})")
# Decay global QPS (approximate)
if admitted:
Thread(target=self._decay_global_qps, daemon=True).start()
return admitted
def _decay_global_qps(self):
time.sleep(1.0)
with self.lock:
self.global_qps = max(0, self.global_qps - 1)
def shutdown(self):
"""Call on shutdown."""
self.running = False
self.metrics_thread.join(timeout=2.0)
def get_stats(self) -> Dict[str, Any]:
"""Get controller stats."""
with self.lock:
return {
'total_capacity': self.total_capacity,
'dynamic_capacity_used': self.global_qps,
'latency_p99': self.current_latency_p99,
'slo_threshold': self.slo_latency_threshold,
'overloaded': self.current_latency_p99 > self.slo_latency_threshold,
'active_clients': len(self.client_buckets),
'client_budgets': {k: {'rate': v.rate, 'tokens': v.tokens} for k, v in self.client_buckets.items()}
}
# Example integration with FastAPI
"""
from fastapi import FastAPI, Request, HTTPException
app = FastAPI()
controller = QPSAdmissionController(total_capacity=100.0)
@app.middleware("http")
async def admission_middleware(request: Request, call_next):
client_key = request.headers.get("X-Client-ID", request.client.host)
slo_class = request.headers.get("X-SLO-Class", "bronze")
if controller.admit(client_key, slo_class):
response = await call_next(request)
return response
else:
raise HTTPException(status_code=429, detail="Rate limited or shed")
@app.get("/stats")
def stats():
return controller.get_stats()
# Run: uvicorn yourfile:app --reload
"""
# Demo usage
if __name__ == "__main__":
controller = QPSAdmissionController(total_capacity=50.0)
print("Demo: Simulating 10 clients...")
for i in range(10):
client_key = f"user_{i}"
slo_class = "gold" if i % 3 == 0 else "bronze" if i % 2 == 0 else "silver"
admitted = controller.admit(client_key, slo_class)
print(f"Client {client_key} (SLO: {slo_class}): {'Admitted' if admitted else 'Denied'}")
print("\nStats:", controller.get_stats())
# Simulate load to trigger overload
import time
for _ in range(200):
controller.admit("high_load_user", "bronze")
time.sleep(0.01)
print("\nPost-load stats:", controller.get_stats())
time.sleep(5)
controller.shutdown()
Key Features Explained
1. Dynamic Budgets
Global scaling: Total capacity scales down when latency approaches SLO (e.g., from 1000 to 500 QPS).
Per-client allocation: Reallocates every second among active clients.
Burst support: Allows 2x rate burst.
2. Fairness
Historical weighting: Weights based on peak QPS in last 60s (proportional share).
Fallback: Equal share if no history.
Active-only: Evicts idle clients (>5min) to free budget.
3. SLO-Aware Shedding
Mock latency: Simulates p99 latency based on load (replace with real metrics, e.g., Prometheus quantile).
Priority tiers:
Class
Shed Threshold
gold
Never
silver
>1.5x SLO (150ms)
bronze
>SLO (100ms)
Sheds before token check for efficiency.
Customization
Real metrics: Hook current_latency_p99 to your observability (e.g., prometheus_client).
Client key: Extract from JWT, API key, or IP.
Production: Use Redis for shared state in distributed setups; asyncio locks for async.
Tuning: Adjust total_capacity, history_window based on benchmarks.
This is production-ready for a single process; scales with sharding. Test under load with Locust or Artillery! Let me know if you need Kubernetes webhook, Go version, or extensions.