import asyncio
import time
import heapq
import collections
from enum import Enum
from typing import Dict, List, Optional, Callable, Any
from dataclasses import dataclass
import logging
logger = logging.getLogger(__name__)
class Priority(Enum):
HIGH = 3
MEDIUM = 2
LOW = 1
@dataclass
class Request:
id: str
priority: Priority
budget_key: str # e.g., downstream service name
latency_target_p99: float = 100.0 # ms, for hedging decision
callback: Callable[[Any], None]
start_time: Optional[float] = None
hedge_count: int = 0
max_hedges: int = 2 # Cap on hedges per request
class Budget:
"""Per-priority budget with soft/hard caps."""
def __init__(self, soft_concurrent: int, hard_concurrent: int, weight: float):
self.soft_concurrent = soft_concurrent
self.hard_concurrent = hard_concurrent
self.weight = weight # For proportional allocation
self.current: int = 0
self.peak_latency: float = 0.0 # Track for guard decisions
class ServiceBudgetGuard:
"""
Service Budget Guard for tail latency mitigation.
- Priorities: High/Med/Low with weighted budgets.
- Caps: Soft (throttle) / Hard (reject).
- Hedging: Duplicate requests for slow ones (tail latency hedge).
Usage:
guard = ServiceBudgetGuard(budgets={"serviceA": {...}})
await guard.execute_request(req)
"""
def __init__(self, budgets: Dict[str, Dict[Priority, Budget]]):
self.budgets = budgets # {service: {prio: Budget}}
self.active_requests: Dict[str, List[Request]] = collections.defaultdict(list)
self.request_heap: List[Request] = [] # Min-heap by (start_time, priority) for eviction
self.lock = asyncio.Lock()
self.stats: Dict[str, Dict[str, int]] = collections.defaultdict(lambda: collections.Counter())
async def acquire_budget(self, req: Request) -> bool:
"""Acquire budget slot for req.budget_key and req.priority. Returns True if acquired."""
async with self.lock:
service = req.budget_key
if service not in self.budgets:
return False
prio_budget = self.budgets[service][req.priority]
# Hard cap check (reject)
if prio_budget.current >= prio_budget.hard_concurrent:
self.stats[service]['hard_reject'] += 1
return False
# Soft cap: If over soft, probabilistically throttle based on weight
if prio_budget.current >= prio_budget.soft_concurrent:
# Proportional probability: lower prio more likely to throttle
prob = prio_budget.weight / sum(b.weight for b in self.budgets[service].values())
if not (asyncio.get_event_loop().time() % 1 < prob):
self.stats[service]['soft_throttle'] += 1
return False
prio_budget.current += 1
heapq.heappush(self.request_heap, (req.start_time or 0, -req.priority.value, req)) # Min-heap by time, max-prio
self.active_requests[service].append(req)
return True
async def release_budget(self, req: Request, success: bool = True):
"""Release budget slot."""
async with self.lock:
service = req.budget_key
if service in self.budgets and req.priority in self.budgets[service]:
self.budgets[service][req.priority].current -= 1
if service in self.active_requests:
self.active_requests[service] = [r for r in self.active_requests[service] if r.id != req.id]
# Evict old low-prio requests if over budget (preemption-like)
self._evict_low_priority(service)
def _evict_low_priority(self, service: str):
"""Evict oldest low-priority requests if total over aggregate cap."""
total_cap = sum(b.hard_concurrent for b in self.budgets[service].values())
active_count = sum(b.current for b in self.budgets[service].values())
while active_count > total_cap and self.request_heap:
_, neg_prio, oldest_req = heapq.heappop(self.request_heap)
if oldest_req.budget_key == service and oldest_req.priority == Priority.LOW:
# Cancel/timeout the request (in real impl, send cancel signal)
logger.warning(f"Evicted low-prio request {oldest_req.id}")
self.stats[service]['evicted'] += 1
active_count -= 1
async def should_hedge(self, req: Request) -> bool:
"""Decide to hedge based on elapsed time vs p99 target and hedge cap."""
if req.hedge_count >= req.max_hedges:
return False
elapsed = (asyncio.get_event_loop().time() - (req.start_time or 0)) * 1000 # ms
return elapsed > req.latency_target_p99
async def execute_request(self, req: Request, executor: Callable[[Request], Any]):
"""
Execute request with budget guard, hedging, and priorities.
- Tries to acquire budget.
- Executes via provided executor (e.g., HTTP client).
- Hedges if slow.
- Releases on completion.
"""
loop = asyncio.get_event_loop()
req.start_time = loop.time()
# Acquire budget
if not await self.acquire_budget(req):
req.callback({"error": "Budget exceeded"})
return
try:
# Initial execution
result = await asyncio.wait_for(
self._execute_with_hedge(req, executor),
timeout=req.latency_target_p99 * 3 / 1000 # Overall timeout
)
req.callback(result)
self.stats[req.budget_key]['success'] += 1
except asyncio.TimeoutError:
req.callback({"error": "Timeout"})
self.stats[req.budget_key]['timeout'] += 1
finally:
await self.release_budget(req)
async def _execute_with_hedge(self, req: Request, executor: Callable[[Request], Any]):
"""Execute with hedging: send duplicates if slow."""
futures = [executor(req)] # Initial request
while await self.should_hedge(req):
req.hedge_count += 1
hedge_future = executor(req) # Send hedge (duplicate)
futures.append(hedge_future)
logger.info(f"Hedged request {req.id} (hedge #{req.hedge_count})")
# Wait for first done
done, _ = await asyncio.wait(futures, return_when=asyncio.FIRST_COMPLETED)
result = await done.pop()
# Cancel remaining
for f in futures:
if not f.done():
f.cancel()
return result
# Example usage and budgets config
async def example_http_executor(req: Request) -> Dict[str, Any]:
"""Mock executor: Simulate variable latency based on priority/service."""
await asyncio.sleep(0.05 + 0.1 * (4 - req.priority.value) + 0.2 * (req.hedge_count > 0)) # Simulate tail
return {"data": f"Response for {req.id}", "from_hedge": req.hedge_count > 0}
async def demo():
budgets = {
"slowService": {
Priority.HIGH: Budget(soft_concurrent=5, hard_concurrent=10, weight=0.6),
Priority.MEDIUM: Budget(soft_concurrent=3, hard_concurrent=5, weight=0.3),
Priority.LOW: Budget(soft_concurrent=1, hard_concurrent=2, weight=0.1),
}
}
guard = ServiceBudgetGuard(budgets)
tasks = []
for i in range(20):
prio = Priority.HIGH if i % 3 == 0 else Priority.MEDIUM if i % 3 == 1 else Priority.LOW
req = Request(
id=f"req-{i}",
priority=prio,
budget_key="slowService",
latency_target_p99=50.0, # Tight p99
callback=lambda r, i=i: print(f"Req {i} ({prio.name}): {r}"),
)
tasks.append(guard.execute_request(req, example_http_executor))
await asyncio.gather(*tasks, return_exceptions=True)
print("Stats:", dict(guard.stats))
# Run demo: python this_file.py
if __name__ == "__main__":
asyncio.run(demo())
Explanation (Sherlock's Deduction)
My dear user, you've tasked me with mitigating tail latency in a service mesh—a classic villain in distributed systems, where 1% slow requests ruin the 99th percentile for all.
Key Features Implemented:
Priorities: HIGH/MED/MEDIUM/LOW with weighted budgets. High-prio gets more slots (e.g., 60% weight).
Caps:
Soft cap: Probabilistic throttle (prio-weighted) when exceeded.
Hard cap: Reject outright.
Eviction: Preempt oldest LOW-prio requests if aggregate over cap (heap-based).
Hedging: After latency_target_p99 (e.g., 50ms), send duplicate requests (capped at max_hedges=2). First response wins; cancel others.
Tune budgets for your services. E.g., for a slow DB:
python
"dbService": {
Priority.HIGH: Budget(10, 20, 0.7), # More room for crit
# ...
}
Production Notes:
Real Executor: Swap example_http_executor with aiohttp/grpc.aio.
Cancellation: Use asyncio.Task.cancel() for RPCs with cancel support.
Metrics: Extend stats to Prometheus.
Monitoring: Track peak_latency for adaptive latency_target_p99.
Scalability: Use Redis for distributed locking if multi-instance.
This guards your service budget like a hawk—tail latency be damned. Test the demo; observe hedging/throttling in action. Questions? The game's afoot! 🕵️