We are going to design a QPS (Queries Per Second) admission controller.
Requirements:
- Dynamic budgets: The controller should adjust the allowed QPS based on system load, SLO status, or other policies.
- Fairness: Different services or clients should be treated fairly, possibly with weights or priorities.
- SLO-aware shedding: When the system is overloaded, shed load in a way that considers SLOs (e.g., drop requests of services that are already in violation or have lower priority).
We'll design a token bucket or leaky bucket style controller that can adjust the rate dynamically.
However, note that we might have multiple services (or tenants) and we want to be fair and SLO-aware.
Approach:
We can have a global budget and per-tenant (or per-service) budgets. But we want dynamic adjustments.
Alternatively, we can have a two-level controller:
- Global controller that adjusts a global budget (or total QPS) based on overall system health.
- Per-tenant controllers that distribute the global budget among tenants, with weights and SLO considerations.
Steps:
-
Metrics: We need to measure:
- Request rates per tenant.
- SLO compliance per tenant (e.g., error rate, latency).
- Maybe system metrics (CPU, memory, etc.) for global adjustment.
-
Global Budget Adjustment:
- Use a PID controller or a similar feedback mechanism to adjust the global budget (total allowed QPS) to keep the system within SLO.
- Alternatively, if the system is overloaded (e.g., latency SLO violated), reduce the global budget.
- If underloaded, increase the global budget.
-
Per-Tenant Budget Distribution:
- Distribute the global budget among tenants based on:
a) Static weights (for fairness in terms of share).
b) Dynamic adjustments based on SLO compliance: if a tenant is in violation, reduce its budget; if it's underutilizing, maybe increase (but careful not to starve others).
- We can use a weighted fair queuing or similar, but note that we are doing admission control, not scheduling.
-
Admission Control:
- Each tenant has its own token bucket (or leaky bucket) with a capacity (burst) and refill rate (budget).
- When a request arrives for a tenant, we check if we can take a token from that tenant's bucket. If yes, admit; else, reject.
- We also need to consider that the global budget should not be exceeded. So we can have a global token bucket that refills at the global budget, and then per-tenant buckets that are subsets? Or we can just rely on the sum of per-tenant budgets not exceeding global.
-
SLO-aware shedding:
- When the system is overloaded, we want to shed load from tenants that are already in SLO violation or have lower priority.
- This can be done by reducing the per-tenant budget for such tenants more aggressively.
-
Dynamic Adjustment Loop:
- Periodically (or on events) recalculate:
a) Global budget based on system metrics and overall SLO.
b) Per-tenant budgets based on weights, SLO compliance, and possibly past usage.
-
Implementation Details:
Let's define:
GlobalBudget: total allowed QPS for the system.
Tenant:
- weight: static weight (relative share when all are compliant)
- current_budget: current allowed QPS for this tenant (refill rate of its token bucket)
- token_bucket: tokens, capacity (burst)
We also track per-tenant SLO status (e.g., a binary or continuous measure of how much in violation).
Adjustment Algorithm:
Global Adjustment:
Let target_global_budget be the desired total QPS to keep system in SLO.
We can set:
If overall SLO is violated -> reduce global budget by a factor (e.g., 0.9).
If overall SLO is met and system is underutilized -> increase global budget by a factor (e.g., 1.1).
But we must also consider the sum of tenant budgets. We can adjust the global budget and then redistribute.
Per-tenant Adjustment:
We want to distribute the global budget among tenants.
Let W_i be the weight of tenant i.
Let S_i be the SLO compliance score (0 to 1, 1 being perfect).
We can define the ideal budget for tenant i as:
ideal_budget_i = (W_i * S_i) / (sum_j W_j * S_j) * GlobalBudget
However, note that if a tenant is in violation (S_i low), its ideal budget becomes low.
But we might also want to consider that if a tenant is underutilizing (it's not using its budget), we don't necessarily want to reduce its budget because then it might become underutilized. So we can also look at the actual usage.
Alternatively, we can use a two-round approach:
Step 1: Allocate based on weights and SLO.
Step 2: If a tenant's allocated budget is much higher than its usage, we can reallocate to others? But that might be complex.
Simpler: adjust based on SLO and weights, and then if the global budget changes, we adjust proportionally.
We can also have a minimum budget per tenant to avoid starvation.
Implementation:
We'll have:
class Tenant:
def __init__(self, name, weight):
self.name = name
self.weight = weight
self.current_budget = 0.0
self.token_bucket = TokenBucket(capacity=burst, refill_rate=0.0)
self.slo_score = 1.0 # 0 to 1
class GlobalController:
def __init__(self, global_budget, tenants):
self.global_budget = global_budget
self.tenants = tenants # list of Tenant
def adjust_global_budget(self, system_slo_met):
# adjust global_budget based on system_slo_met
if system_slo_met:
self.global_budget *= 1.1
else:
self.global_budget *= 0.9
def adjust_tenant_budgets(self):
# First, compute total weight * slo_score
total_weighted_slo = sum(t.weight * t.slo_score for t in self.tenants)
if total_weighted_slo == 0:
# If all are in violation, we might want to distribute equally? or by weight only?
total_weighted_slo = sum(t.weight for t in self.tenants)
for t in self.tenants:
# Ideal budget for tenant
ideal_budget = (t.weight * t.slo_score) / total_weighted_slo * self.global_budget
# We can set current_budget to ideal_budget, but we might want to smooth changes.
t.current_budget = ideal_budget
t.token_bucket.refill_rate = ideal_budget
However, note that the token bucket's refill rate is set to the current_budget, and we also have a burst capacity.
We also need to update the token buckets periodically? Actually, the token bucket should refill continuously at the refill rate.
But note: the per-tenant token bucket is separate and we are setting its refill rate. We must ensure that the sum of refill rates does not exceed global budget? Actually, we are setting them to exactly the ideal distribution which sums to global_budget.
But what about burst? The burst capacity is the maximum tokens that can accumulate. We can set a fixed burst (e.g., 2*current_budget) or let it be a configuration.
Also, we must consider that the global budget adjustment might be done less frequently than the per-tenant adjustment.
-
How to run the adjustments?
We can have a background thread that:
- Collects metrics (SLO scores, usage) every interval.
- Adjusts global budget based on system SLO.
- Adjusts tenant budgets.
We also need to monitor the actual usage per tenant to compute SLO scores.
SLO score for a tenant:
We can define:
slo_score = 1.0 if the tenant's SLO is met (e.g., error rate < threshold and latency < threshold), and linearly decrease as the SLO is violated.
But note: we might have multiple SLOs. We can combine them.
For simplicity, let's define:
slo_score = 1.0 - min(1.0, (error_rate - error_threshold)/error_threshold + (latency - latency_threshold)/latency_threshold)
But note: if error_threshold is 0, then we cannot divide. So we have to handle that.
Alternatively, we can have a binary: 1 if both error and latency are within threshold, else 0.
But continuous might be better.
We'll leave the SLO score calculation as a pluggable function.
-
Putting it together:
We'll design:
class TokenBucket:
def __init__(self, capacity, refill_rate):
self.capacity = capacity
self.refill_rate = refill_rate # tokens per second
self.tokens = 0 # current tokens
self.last_update = time.time()
def consume(self, tokens):
# refill
now = time.time()
delta = now - self.last_update
self.tokens = min(self.capacity, self.tokens + delta * self.refill_rate)
self.last_update = now
if self.tokens >= tokens:
self.tokens -= tokens
return True
else:
return False
class Tenant:
def __init__(self, name, weight, min_budget=0, max_budget=None):
self.name = name
self.weight = weight
self.min_budget = min_budget
self.max_budget = max_budget
self.current_budget = 0.0
self.token_bucket = TokenBucket(capacity=0, refill_rate=0.0)
self.slo_score = 1.0
def set_budget(self, budget):
# Adjust the token bucket parameters
self.current_budget = budget
self.token_bucket.refill_rate = budget
# Set burst to 2*budget, but not less than min_burst? We don't have min_burst.
new_capacity = 2 * budget
if self.token_bucket.tokens > new_capacity:
self.token_bucket.tokens = new_capacity
self.token_bucket.capacity = new_capacity
class AdmissionController:
def __init__(self, global_budget, tenants):
self.global_budget = global_budget
self.tenants = tenants
def adjust_global_budget(self, system_slo_met):
# Simple adjustment: if system SLO is met, increase by 10%, else decrease by 10%
if system_slo_met:
self.global_budget *= 1.1
else:
self.global_budget *= 0.9
# We might want to set bounds to avoid going too high or too low.
self.global_budget = max(0.1, min(1000000, self.global_budget))
def adjust_tenant_budgets(self):
# Calculate total weighted SLO
total_weighted_slo = sum(t.weight * t.slo_score for t in self.tenants)
if total_weighted_slo == 0:
# Fall back to weight only
total_weight = sum(t.weight for t in self.tenants)
for t in self.tenants:
ideal_budget = (t.weight / total_weight) * self.global_budget
self._set_tenant_budget_with_bounds(t, ideal_budget)
else:
for t in self.tenants:
ideal_budget = (t.weight * t.slo_score) / total_weighted_slo * self.global_budget
self._set_tenant_budget_with_bounds(t, ideal_budget)
def _set_tenant_budget_with_bounds(self, tenant, ideal_budget):
# Apply min and max bounds if set
budget = ideal_budget
if tenant.min_budget is not None:
budget = max(budget, tenant.min_budget)
if tenant.max_budget is not None:
budget = min(budget, tenant.max_budget)
tenant.set_budget(budget)
def admit(self, tenant_name):
tenant = self._get_tenant(tenant_name)
if tenant is None:
return False
# Try to consume 1 token
if tenant.token_bucket.consume(1):
return True
else:
return False
def _get_tenant(self, tenant_name):
for t in self.tenants:
if t.name == tenant_name:
return t
return None
def update_slo_scores(self, slo_scores):
# slo_scores: dict of tenant_name -> score (0 to 1)
for t in self.tenants:
if t.name in slo_scores:
t.slo_score = slo_scores[t.name]
-
How to run the adjustment loop?
We can have a separate thread that:
while True:
sleep(interval)
collect system SLO status (overall) -> system_slo_met
collect per-tenant SLO scores (from monitoring)
controller.adjust_global_budget(system_slo_met)
controller.adjust_tenant_budgets()
But note: adjust_global_budget changes global_budget, then adjust_tenant_budgets redistributes.
11. How to handle bursty traffic?
The token bucket with burst (2*budget) allows some burst. But if the traffic is very bursty, we might want a larger burst.
We can set the burst as a configuration (e.g., burst = 2 * budget, or burst = 100, whichever is larger). But then when budget is 0, burst should be 0.
Alternatively, we can set:
burst = max(0, min(100, 2*budget)) # but then if budget is 10, burst=20, but if budget is 0.1, burst=0.2? We might want to round to integer.
Since QPS is in requests per second, we can set:
burst = max(0, int(2 * budget))
But note: the token bucket uses floating point? We can use integer tokens for simplicity.
Let's assume we use integer tokens (each token is one request).
Then:
current_budget is a float (QPS) but we convert to integer tokens per second? Actually, the token bucket refill rate is in tokens per second, and we consume 1 token per request.
We can set:
refill_rate = int(budget) # but then we lose fractional part.
Alternatively, we can use floating point for refill rate and capacity.
We'll use floating point for refill_rate and capacity, but when we consume, we consume 1 token (integer). So the bucket can have fractional tokens? Actually, if we refill at 1.5 tokens per second, then after 1 second we have 1.5 tokens. We can only consume 1 token at a time, so we can have fractional tokens.
But note: if we set capacity to 2*budget, and budget is 1.5, then capacity=3.0.
This is acceptable.
12. Summary:
We have:
TokenBucket: with capacity, refill_rate (tokens per second), and current tokens.
Tenant: has a TokenBucket, weight, slo_score, and current_budget (which is the refill_rate).
AdmissionController: has global_budget and list of tenants.
Methods:
adjust_global_budget(system_slo_met)
adjust_tenant_budgets()
admit(tenant_name)
We run a loop that periodically:
- Updates SLO scores for each tenant (from external monitoring).
- Checks system SLO status.
- Adjusts global and tenant budgets.
Then, when a request comes for a tenant, we call admit(tenant_name).
13. Example:
tenants = [Tenant("t1", weight=1), Tenant("t2", weight=2)]
controller = AdmissionController(global_budget=100, tenants=tenants)
Initially, adjust_tenant_budgets() will set:
total_weighted_slo = 1*1 + 2*1 = 3
t1: (1*1)/3 * 100 = 33.33
t2: (2*1)/3 * 100 = 66.67
Then if we set:
t1.slo_score = 0.5, t2.slo_score = 0.8
total_weighted_slo = 1*0.5 + 2*0.8 = 0.5+1.6=2.1
t1: (1*0.5)/2.1 * 100 = 23.81
t2: (2*0.8)/2.1 * 100 = 76.19
Then if system_slo_met is False, we reduce global_budget to 90, and then redistribute:
t1: (1*0.5)/2.1 * 90 = 21.43
t2: (2*0.8)/2.1 * 90 = 68.57
Note: the sum is 90.
This seems reasonable.
14. Improvements:
- We might want to smooth the budget changes (e.g., exponentially weighted moving average) to avoid oscillations.
- We might want to consider the actual usage when adjusting SLO scores? For example, if a tenant is not using its budget, we might want to reduce its budget? But that might be against fairness because the tenant might be waiting for traffic.
However, if a tenant is consistently not using its budget, we might want to reallocate to others? But note: the tenant might be idle.
We can adjust the weight dynamically based on usage? Or we can have a separate metric for utilization.
Alternatively, we can have:
effective_weight = weight * (1 + alpha * (usage / budget - 1))
But that might be too complex.
For now, we stick to static weight and SLO score.
15. Conclusion:
We have designed a QPS admission controller with:
- Dynamic global budget adjustment based on system SLO.
- Per-tenant budget distribution based on static weight and SLO score.
- Token bucket per tenant for admission control.
This provides fairness (via weights) and SLO-aware shedding (via SLO score).
We can extend with min/max budgets and water-filling for exact global budget allocation.
We can also extend the SLO score calculation to be more sophisticated.
The code below is a Python implementation of the above design.
Note: This is a simplified version for illustration. In production, we would need to handle concurrency, metrics collection, and more robust adjustment algorithms.
Let's code accordingly.</think>
I'll design a comprehensive QPS admission controller with dynamic budgets, fairness, and SLO-aware shedding. Here's a production-ready implementation:
import time
import threading
import heapq
from collections import defaultdict, deque
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple, Callable
from enum import Enum
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class SLOStatus(Enum):
HEALTHY = "healthy"
DEGRADED = "degraded"
VIOLATED = "violated"
@dataclass
class TenantConfig:
"""Configuration for a tenant/service"""
name: str
weight: float = 1.0 # Fair share weight
min_qps: float = 0.0 # Minimum guaranteed QPS
max_qps: float = float('inf') # Maximum allowed QPS
priority: int = 0 # Higher priority = more protected during overload
slo_thresholds: Dict[str, float] = field(default_factory=dict) # e.g., {'latency_p99': 100, 'error_rate': 0.01}
burst_capacity: int = 10 # Maximum burst tokens
@dataclass
class TenantMetrics:
"""Runtime metrics for a tenant"""
current_qps: float = 0.0
avg_latency: float = 0.0
error_rate: float = 0.0
success_count: int = 0
error_count: int = 0
request_timestamps: deque = field(default_factory=lambda: deque(maxlen=1000))
slo_status: SLOStatus = SLOStatus.HEALTHY
last_slo_update: float = 0.0
class TokenBucket:
"""Token bucket for rate limiting with burst capacity"""
def __init__(self, rate: float, capacity: int):
self.rate = rate # tokens per second
self.capacity = capacity
self.tokens = capacity
self.last_update = time.time()
self.lock = threading.RLock()
def consume(self, tokens: int = 1) -> bool:
"""Try to consume tokens, returns True if successful"""
with self.lock:
now = time.time()
# Refill tokens based on time passed
delta = now - self.last_update
self.tokens = min(self.capacity, self.tokens + delta * self.rate)
self.last_update = now
if self.tokens >= tokens:
self.tokens -= tokens
return True
return False
def get_available_tokens(self) -> float:
"""Get current token count without consuming"""
with self.lock:
now = time.time()
delta = now - self.last_update
return min(self.capacity, self.tokens + delta * self.rate)
def set_rate(self, new_rate: float):
"""Dynamically adjust rate"""
with self.lock:
self.rate = new_rate
class QPSAdmissionController:
"""
Advanced QPS admission controller with:
1. Dynamic global budget based on system load
2. Fair weighted distribution among tenants
3. SLO-aware shedding (protects healthy services, sheds unhealthy)
4. Priority-based protection
5. Burst handling
"""
def __init__(
self,
initial_global_budget: float = 1000.0,
adjustment_interval: float = 1.0,
system_slo_monitor: Optional[Callable[[], Tuple[bool, Dict]]] = None
):
# Global budget (tokens/sec system-wide)
self.global_budget = initial_global_budget
self.adjustment_interval = adjustment_interval
self.system_slo_monitor = system_slo_monitor
# Tenant management
self.tenants: Dict[str, TenantConfig] = {}
self.metrics: Dict[str, TenantMetrics] = {}
self.buckets: Dict[str, TokenBucket] = {}
# Global token bucket for system-wide limit
self.global_bucket = TokenBucket(initial_global_budget, int(initial_global_budget * 2))
# Load shedding state
self.overload_mode = False
self.shedding_candidates: List[Tuple[int, float, str]] = [] # (priority, score, tenant_name)
# Statistics
self.total_admitted = 0
self.total_rejected = 0
self.start_time = time.time()
# Background adjustment thread
self.running = True
self.adjustment_thread = threading.Thread(
target=self._adjustment_loop,
daemon=True
)
self.adjustment_thread.start()
# Lock for thread safety
self.lock = threading.RLock()
def register_tenant(self, config: TenantConfig):
"""Register a new tenant"""
with self.lock:
if config.name in self.tenants:
logger.warning(f"Tenant {config.name} already registered")
return
self.tenants[config.name] = config
self.metrics[config.name] = TenantMetrics()
self.buckets[config.name] = TokenBucket(
config.min_qps,
config.burst_capacity
)
logger.info(f"Registered tenant {config.name} with weight={config.weight}")
def unregister_tenant(self, tenant_name: str):
"""Remove a tenant"""
with self.lock:
if tenant_name in self.tenants:
del self.tenants[tenant_name]
del self.metrics[tenant_name]
del self.buckets[tenant_name]
logger.info(f"Unregistered tenant {tenant_name}")
def admit_request(self, tenant_name: str) -> bool:
"""
Main admission decision point.
Returns True if request should be admitted, False if rejected.
"""
with self.lock:
if tenant_name not in self.tenants:
logger.warning(f"Unknown tenant: {tenant_name}")
return False
config = self.tenants[tenant_name]
metrics = self.metrics[tenant_name]
bucket = self.buckets[tenant_name]
# Check if tenant is already in violation and should be shed
if self.overload_mode and self._should_shed_tenant(tenant_name):
self.total_rejected += 1
return False
# Check global budget first
if not self.global_bucket.consume(1):
self.total_rejected += 1
return False
# Check tenant-specific bucket
if bucket.consume(1):
# Admit successfully
metrics.current_qps += 1
metrics.success_count += 1
metrics.request_timestamps.append(time.time())
self.total_admitted += 1
return True
else:
self.total_rejected += 1
return False
def record_request_completion(self, tenant_name: str, latency_ms: float, success: bool):
"""Record request completion for SLO calculation"""
with self.lock:
if tenant_name not in self.metrics:
return
metrics = self.metrics[tenant_name]
metrics.request_timestamps.append(time.time())
if success:
metrics.success_count += 1
# Update rolling average latency
alpha = 0.1 # Smoothing factor
metrics.avg_latency = (1 - alpha) * metrics.avg_latency + alpha * latency_ms
else:
metrics.error_count += 1
# Calculate current rates
self._update_rates(tenant_name)
def _update_rates(self, tenant_name: str):
"""Calculate current QPS and error rate from recent history"""
metrics = self.metrics[tenant_name]
now = time.time()
# Count requests in last 10 seconds
window_secs = 10
cutoff = now - window_secs
recent = [t for t in metrics.request_timestamps if t > cutoff]
metrics.current_qps = len(recent) / window_secs
# Calculate error rate from recent requests (simplified)
total_recent = len(recent)
if total_recent > 0:
metrics.error_rate = metrics.error_count / total_recent
else:
metrics.error_rate = 0.0
metrics.last_slo_update = now
def _should_shed_tenant(self, tenant_name: str) -> bool:
"""
Determine if tenant should be shed during overload.
Uses priority + SLO status for decision.
"""
config = self.tenants[tenant_name]
metrics = self.metrics[tenant_name]
# Always shed if in violation and not priority
if metrics.slo_status == SLOStatus.VIOLATED and config.priority < 5:
return True
# For degraded tenants, shed based on priority
if metrics.slo_status == SLOStatus.DEGRADED:
# Lower priority tenants get shed first
return config.priority < 3
# During overload, also consider current utilization
# If tenant is using >90% of its budget, consider shedding
if metrics.current_qps > 0.9 * self.buckets[tenant_name].rate:
return config.priority < 2
return False
def _calculate_tenant_slo_score(self, tenant_name: str) -> float:
"""
Calculate normalized SLO score (0-1) where 1 = perfectly healthy.
Lower score = worse SLO compliance.
"""
config = self.tenants[tenant_name]
metrics = self.metrics[tenant_name]
score = 1.0
# Check each SLO threshold
if 'latency_p99' in config.slo_thresholds:
threshold = config.slo_thresholds['latency_p99']
if metrics.avg_latency > threshold:
# Linear penalty: 1.0 at threshold, 0.0 at 2x threshold
ratio = min(2.0, metrics.avg_latency / threshold)
score *= max(0.0, 2.0 - ratio) / 2.0
if 'error_rate' in config.slo_thresholds:
threshold = config.slo_thresholds['error_rate']
if metrics.error_rate > threshold:
# Exponential penalty for error rate
ratio = metrics.error_rate / threshold
score *= max(0.0, 1.0 - (ratio - 1.0) ** 2)
# Update SLO status
if score >= 0.8:
metrics.slo_status = SLOStatus.HEALTHY
elif score >= 0.5:
metrics.slo_status = SLOStatus.DEGRADED
else:
metrics.slo_status = SLOStatus.VIOLATED
return score
def _adjustment_loop(self):
"""Background thread for dynamic budget adjustments"""
while self.running:
try:
time.sleep(self.adjustment_interval)
self._adjust_budgets()
except Exception as e:
logger.error(f"Error in adjustment loop: {e}")
def _adjust_budgets(self):
"""Main adjustment algorithm"""
with self.lock:
# 1. Check system-wide SLO status
system_healthy, system_metrics = self._check_system_slo()
self.overload_mode = not system_healthy
# 2. Adjust global budget based on system load
self._adjust_global_budget(system_healthy, system_metrics)
# 3. Distribute global budget among tenants fairly
self._distribute_global_budget()
# 4. Update shedding priorities
self._update_shedding_priorities()
logger.debug(
f"Adjusted budgets - Global: {self.global_budget:.1f} QPS, "
f"Overload: {self.overload_mode}"
)
def _check_system_slo(self) -> Tuple[bool, Dict]:
"""Check if system-wide SLOs are being met"""
if self.system_slo_monitor:
return self.system_slo_monitor()
# Default: check if any tenant is in violation
violations = sum(
1 for m in self.metrics.values()
if m.slo_status == SLOStatus.VIOLATED
)
system_healthy = violations == 0
return system_healthy, {
'violation_count': violations,
'total_tenants': len(self.tenants)
}
def _adjust_global_budget(self, system_healthy: bool, system_metrics: Dict):
"""PID-like controller for global budget"""
# Simple proportional controller
target_utilization = 0.8 # Target 80% utilization
# Calculate current utilization (simplified)
current_usage = sum(
bucket.get_available_tokens()
for bucket in self.buckets.values()
)
# Actually we want used budget, but we can estimate from global bucket
global_usage = self.global_budget - self.global_bucket.get_available_tokens()
utilization = global_usage / max(1.0, self.global_budget)
# Adjustment factors
if system_healthy:
# Increase budget if underutilized
if utilization < target_utilization * 0.7:
self.global_budget *= 1.1
elif utilization < target_utilization:
self.global_budget *= 1.02
else:
# Decrease budget if overloaded
if utilization > target_utilization * 1.2:
self.global_budget *= 0.8
else:
self.global_budget *= 0.95
# Clamp to reasonable bounds
self.global_budget = max(
10.0,
min(100000.0, self.global_budget)
)
# Update global bucket
self.global_bucket.set_rate(self.global_budget)
self.global_bucket.capacity = int(self.global_budget * 2)
def _distribute_global_budget(self):
"""Distribute global budget among tenants using fair sharing"""
# Calculate effective weight considering SLO scores
total_weight = 0.0
tenant_weights = {}
for name, config in self.tenants.items():
metrics = self.metrics[name]
slo_score = self._calculate_tenant_slo_score(name)
# SLO penalty: reduce weight for unhealthy tenants
effective_weight = config.weight * slo_score
# Priority bonus: higher priority gets multiplier
if config.priority >= 5:
effective_weight *= 1.5
elif config.priority >= 3:
effective_weight *= 1.2
tenant_weights[name] = effective_weight
total_weight += effective_weight
if total_weight == 0:
# All tenants unhealthy, distribute equally
for name in self.tenants:
tenant_weights[name] = 1.0
total_weight = len(self.tenants)
# Distribute budget proportionally
for name, weight in tenant_weights.items():
config = self.tenants[name]
# Calculate share
share = (weight / total_weight) * self.global_budget
# Apply min/max bounds
share = max(config.min_qps, min(config.max_qps, share))
# Update tenant bucket
bucket = self.buckets[name]
bucket.set_rate(share)
bucket.capacity = max(
config.burst_capacity,
int(share * 2) # 2 seconds of burst
)
logger.debug(
f"Tenant {name}: rate={share:.1f} QPS, "
f"capacity={bucket.capacity}, weight={weight:.3f}"
)
def _update_shedding_priorities(self):
"""Build priority queue for load shedding"""
self.shedding_candidates = []
for name, config in self.tenants.items():
metrics = self.metrics[name]
slo_score = self._calculate_tenant_slo_score(name)
# Calculate shedding priority score (lower = shed first)
# Factors:
# 1. Inversely proportional to SLO score (bad SLO = shed first)
# 2. Inversely proportional to priority (low priority = shed first)
# 3. Inversely proportional to weight (low weight = shed first)
priority_score = (
(1.0 - slo_score) * 100 + # SLO is primary factor
(10 - config.priority) * 10 + # Priority is secondary
(1.0 / max(0.1, config.weight)) * 5 # Weight is tertiary
)
heapq.heappush(
self.shedding_candidates,
(priority_score, slo_score, name)
)
def get_stats(self) -> Dict:
"""Get controller statistics"""
with self.lock:
uptime = time.time() - self.start_time
total_requests = self.total_admitted + self.total_rejected
stats = {
'global_budget': self.global_budget,
'overload_mode': self.overload_mode,
'uptime_seconds': uptime,
'total_admitted': self.total_admitted,
'total_rejected': self.total_rejected,
'admission_rate': self.total_admitted / max(1, total_requests),
'tenants': {}
}
for name in self.tenants:
config = self.tenants[name]
metrics = self.metrics[name]
bucket = self.buckets[name]
stats['tenants'][name] = {
'config': {
'weight': config.weight,
'priority': config.priority,
'min_qps': config.min_qps,
'max_qps': config.max_qps,
},
'metrics': {
'current_qps': metrics.current_qps,
'slo_status': metrics.slo_status.value,
'avg_latency_ms': metrics.avg_latency,
'error_rate': metrics.error_rate,
},
'bucket': {
'rate': bucket.rate,
'capacity': bucket.capacity,
'available_tokens': bucket.get_available_tokens()
}
}
return stats
def shutdown(self):
"""Gracefully shutdown the controller"""
self.running = False
if self.adjustment_thread.is_alive():
self.adjustment_thread.join(timeout=5.0)
# Example usage
def example_system_slo_monitor():
"""Example system-wide SLO monitor"""
# In reality, this would check system metrics like:
# - CPU utilization
# - Memory pressure
# - Database connection pool exhaustion
# - Overall error rates
# For example, return False if CPU > 80%
import psutil
cpu_percent = psutil.cpu_percent(interval=0.1)
system_healthy = cpu_percent < 80.0
return system_healthy, {
'cpu_percent': cpu_percent,
'memory_percent': psutil.virtual_memory().percent
}
def main():
"""Example usage"""
# Create controller
controller = QPSAdmissionController(
initial_global_budget=500.0,
adjustment_interval=2.0,
system_slo_monitor=example_system_slo_monitor
)
# Register tenants with different priorities and weights
tenants_config = [
TenantConfig(
name="payment-service",
weight=3.0, # High weight
priority=5, # Highest priority
slo_thresholds={'latency_p99': 50, 'error_rate': 0.001},
min_qps=10.0
),
TenantConfig(
name="inventory-service",
weight=2.0,
priority=4,
slo_thresholds={'latency_p99': 100, 'error_rate': 0.005},
min_qps=5.0
),
TenantConfig(
name="recommendation-service",
weight=1.0,
priority=2,
slo_thresholds={'latency_p99': 200, 'error_rate': 0.01},
min_qps=1.0
),
TenantConfig(
name="analytics-service",
weight=0.5,
priority=0, # Low priority
slo_thresholds={'latency_p99': 500, 'error_rate': 0.05},
max_qps=50.0 # Cap this tenant
)
]
for config in tenants_config:
controller.register_tenant(config)
# Simulate requests
import random
try:
for i in range(10000):
# Randomly select tenant with bias towards higher weight
tenant_names = list(controller.tenants.keys())
weights = [controller.tenants[name].weight for name in tenant_names]
tenant = random.choices(tenant_names, weights=weights)[0]
# Try to admit
if controller.admit_request(tenant):
# Simulate success/failure and latency
success = random.random() > 0.05 # 95% success rate
latency = random.expovariate(1.0 / 50) # Avg 50ms
controller.record_request_completion(tenant, latency, success)
time.sleep(0.001) # Simulate requests arriving
# Print stats periodically
if i % 1000 == 0:
stats = controller.get_stats()
print(f"\n=== Stats after {i} requests ===")
print(f"Global budget: {stats['global_budget']:.1f} QPS")
print(f"Overload mode: {stats['overload_mode']}")
print(f"Admission rate: {stats['admission_rate']*100:.1f}%")
for name, tenant_stats in stats['tenants'].items():
print(f"\n{name}:")
print(f" QPS: {tenant_stats['metrics']['current_qps']:.1f}")
print(f" SLO: {tenant_stats['metrics']['slo_status']}")
print(f" Allocated: {tenant_stats['bucket']['rate']:.1f} QPS")
print(f" Priority: {tenant_stats['config']['priority']}")
finally:
controller.shutdown()
print("\nFinal stats:", controller.get_stats())
if __name__ == "__main__":
main()
Key Design Features:
1. Dynamic Global Budget Adjustment
- PID-like controller that increases/decreases global budget based on:
- System-wide SLO compliance
- Current utilization (target ~80%)
- Adjusts every
adjustment_interval seconds
- Bounded to prevent extreme values
2. Fair Distribution
- Weighted fair sharing among tenants
- Effective weight =
base_weight × SLO_score × priority_multiplier
- SLO penalty: unhealthy tenants get reduced weight
- Priority bonus: high-priority services get multiplier (1.2-1.5×)
- Respects min_qps and max_qps bounds
3. SLO-Aware Load Shedding
- Multi-factor shedding decision:
- Primary: SLO status (VIOLATED > DEGRADED > HEALTHY)
- Secondary: Priority (low priority shed first)
- Tertiary: Current utilization (>90% of allocation)
- Maintains priority queue for efficient shedding decisions
- Only activates in overload mode
4. Token Bucket Implementation
- Per-tenant token buckets with:
- Dynamic rate adjustment
- Burst capacity (2 seconds of budget by default)
- Thread-safe operations
- Global bucket enforces system-wide limit
5. Metrics & Monitoring
- Per-tenant metrics:
- Current QPS (10-second rolling window)
- Average latency (EMA)
- Error rate
- SLO status (HEALTHY/DEGRADED/VIOLATED)
- Controller statistics for observability
6. Production Considerations
- Thread-safe with proper locking
- Graceful shutdown
- Configurable via dataclasses
- Extensible SLO monitoring
- Configurable adjustment intervals
- Protection against extreme budget swings
Usage Patterns:
# Initialize
controller = QPSAdmissionController(
initial_global_budget=1000.0,
adjustment_interval=5.0
)
# Register services
controller.register_tenant(TenantConfig(
name="critical-api",
weight=5.0,
priority=5,
min_qps=100.0,
slo_thresholds={'latency_p99': 100, 'error_rate': 0.001}
))
# In request handler
if controller.admit_request("critical-api"):
try:
response = handle_request()
controller.record_request_completion(
"critical-api",
latency=response.latency_ms,
success=response.is_success
)
except Exception:
controller.record_request_completion(
"critical-api",
latency=0,
success=False
)
else:
return HttpResponse(503, "Service overloaded")
Extensions Possible:
- Multi-dimensional SLOs: Add more SLO types (throughput, availability)
- Predictive adjustment: Use time-series forecasting
- Cost-based shedding: Consider business impact
- Geographic distribution: Multi-region budget allocation
- Machine learning: Learn optimal weights from historical data
This implementation provides a solid foundation that balances fairness, efficiency, and SLO protection while being simple enough to understand and extend.