import time
import threading
import logging
import statistics
from collections import deque
from dataclasses import dataclass
from typing import Optional, Dict, List, Callable, Any
from datetime import datetime, timedelta
from enum import Enum
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class AlertSeverity(Enum):
INFO = "INFO"
WARNING = "WARNING"
CRITICAL = "CRITICAL"
@dataclass
class Alert:
timestamp: datetime
severity: AlertSeverity
message: str
metric: str
current_value: float
threshold: float
context: Dict[str, Any]
class QueueTimeBudget:
"""Manages queue time budgets with multiple percentiles and time windows"""
def __init__(
self,
target_p50_ms: float = 100,
target_p95_ms: float = 500,
target_p99_ms: float = 1000,
violation_window_seconds: int = 60,
consecutive_violations_threshold: int = 3
):
self.targets = {
'p50': target_p50_ms,
'p95': target_p95_ms,
'p99': target_p99_ms
}
self.violation_window = violation_window_seconds
self.consecutive_threshold = consecutive_violations_threshold
self._violation_history = {k: deque(maxlen=consecutive_violations_threshold)
for k in self.targets.keys()}
def check_budget_violation(self, queue_times_ms: List[float]) -> Dict[str, bool]:
"""Check if queue times violate budgets across percentiles"""
if not queue_times_ms:
return {k: False for k in self.targets.keys()}
violations = {}
for percentile, target in self.targets.items():
if percentile == 'p50':
value = statistics.median(queue_times_ms)
elif percentile == 'p95':
sorted_times = sorted(queue_times_ms)
idx = int(len(sorted_times) * 0.95)
value = sorted_times[min(idx, len(sorted_times) - 1)]
elif percentile == 'p99':
sorted_times = sorted(queue_times_ms)
idx = int(len(sorted_times) * 0.99)
value = sorted_times[min(idx, len(sorted_times) - 1)]
violated = value > target
violations[percentile] = violated
# Track consecutive violations
if violated:
self._violation_history[percentile].append(True)
else:
self._violation_history[percentile].append(False)
return violations
def is_sustained_violation(self, percentile: str) -> bool:
"""Check if we have consecutive violations for a percentile"""
history = self._violation_history[percentile]
return len(history) == self.consecutive_threshold and all(history)
def get_violation_metrics(self) -> Dict[str, float]:
"""Get violation rate for each percentile"""
metrics = {}
for percentile, history in self._violation_history.items():
if history:
violation_rate = sum(history) / len(history)
metrics[f"{percentile}_violation_rate"] = violation_rate
return metrics
class AdaptivePoolLimits:
"""Dynamically adjusts pool limits based on performance metrics"""
def __init__(
self,
min_connections: int,
max_connections: int,
initial_connections: int,
scale_up_threshold: float = 0.8, # 80% utilization triggers scale up
scale_down_threshold: float = 0.3, # 30% utilization triggers scale down
scale_up_factor: float = 1.2, # Increase by 20%
scale_down_factor: float = 0.9, # Decrease by 10%
adjustment_cooldown_seconds: int = 300, # 5 minutes between adjustments
min_adjustment_amount: int = 1
):
self.min = min_connections
self.max = max_connections
self.current = initial_connections
self.scale_up_threshold = scale_up_threshold
self.scale_down_threshold = scale_down_threshold
self.scale_up_factor = scale_up_factor
self.scale_down_factor = scale_down_factor
self.adjustment_cooldown = adjustment_cooldown_seconds
self.min_adjustment = min_adjustment_amount
self._last_adjustment = 0
self._adjustment_history: List[Dict] = []
def calculate_adjustment(
self,
active_connections: int,
waiting_requests: int,
queue_time_avg: float
) -> Optional[int]:
"""Calculate if and how much to adjust pool size"""
now = time.time()
# Check cooldown
if now - self._last_adjustment < self.adjustment_cooldown:
return None
# Calculate utilization
utilization = active_connections / self.current if self.current > 0 else 0
# Determine adjustment direction
adjustment = None
# Scale up conditions
if (utilization >= self.scale_up_threshold or
(waiting_requests > 0 and queue_time_avg > 100)): # 100ms queue time
target = int(self.current * self.scale_up_factor)
adjustment = min(target, self.max) - self.current
# Scale down conditions (only if no pending requests)
elif (utilization <= self.scale_down_threshold and
waiting_requests == 0 and
self.current > self.min):
target = int(self.current * self.scale_down_factor)
adjustment = max(target, self.min) - self.current
# Apply minimum adjustment threshold
if adjustment and abs(adjustment) < self.min_adjustment:
adjustment = self.min_adjustment if adjustment > 0 else -self.min_adjustment
return adjustment
def apply_adjustment(self, adjustment: int) -> int:
"""Apply adjustment and update current value"""
new_value = max(self.min, min(self.max, self.current + adjustment))
actual_adjustment = new_value - self.current
if actual_adjustment != 0:
self._adjustment_history.append({
'timestamp': datetime.utcnow(),
'old_value': self.current,
'new_value': new_value,
'adjustment': actual_adjustment
})
self.current = new_value
self._last_adjustment = time.time()
return actual_adjustment
def get_metrics(self) -> Dict[str, Any]:
"""Get current metrics for monitoring"""
return {
'current_size': self.current,
'min_size': self.min,
'max_size': self.max,
'last_adjustment': self._last_adjustment,
'adjustment_count': len(self._adjustment_history),
'recent_adjustments': self._adjustment_history[-5:] # Last 5 adjustments
}
class StarvationDetector:
"""Main starvation detection and management system"""
def __init__(
self,
# Pool configuration
min_connections: int = 5,
max_connections: int = 100,
initial_connections: int = 10,
# Queue time budgets
queue_time_budget_p50_ms: float = 100,
queue_time_budget_p95_ms: float = 500,
queue_time_budget_p99_ms: float = 1000,
# Monitoring configuration
metrics_window_size: int = 1000, # Keep last 1000 measurements
check_interval_seconds: float = 1.0,
# Adaptive limits configuration
adaptive_config: Optional[Dict] = None,
# Alerting configuration
alert_callbacks: Optional[List[Callable[[Alert], None]]] = None,
alert_cooldown_seconds: int = 300, # 5 minutes between same alerts
):
# Initialize components
self.queue_budget = QueueTimeBudget(
target_p50_ms=queue_time_budget_p50_ms,
target_p95_ms=queue_time_budget_p95_ms,
target_p99_ms=queue_time_budget_p99_ms
)
adaptive_config = adaptive_config or {}
self.adaptive_limits = AdaptivePoolLimits(
min_connections=min_connections,
max_connections=max_connections,
initial_connections=initial_connections,
**adaptive_config
)
# Metrics storage
self.metrics_window = deque(maxlen=metrics_window_size)
self._check_interval = check_interval_seconds
# Alerting
self.alert_callbacks = alert_callbacks or []
self.alert_cooldown = alert_cooldown_seconds
self._last_alert_times: Dict[str, datetime] = {}
# Threading
self._running = False
self._monitor_thread: Optional[threading.Thread] = None
self._lock = threading.RLock()
# Pool interface (to be implemented by user)
self.pool_interface = None
logger.info(
f"StarvationDetector initialized: "
f"min={min_connections}, max={max_connections}, initial={initial_connections}, "
f"budgets=p50<{queue_time_budget_p50_ms}ms, "
f"p95<{queue_time_budget_p95_ms}ms, p99<{queue_time_budget_p99_ms}ms"
)
def set_pool_interface(self, pool_interface: Any):
"""Set the connection pool interface to monitor and control"""
self.pool_interface = pool_interface
def record_queue_time(self, queue_time_ms: float):
"""Record a queue time measurement (call from pool when connection is acquired)"""
with self._lock:
timestamp = time.time()
self.metrics_window.append({
'timestamp': timestamp,
'queue_time_ms': queue_time_ms,
'datetime': datetime.utcnow()
})
def get_pool_metrics(self) -> Dict[str, Any]:
"""Get current pool metrics from the pool interface"""
if not self.pool_interface:
return {}
try:
return {
'active_connections': self.pool_interface.get_active_connections(),
'idle_connections': self.pool_interface.get_idle_connections(),
'waiting_requests': self.pool_interface.get_waiting_requests(),
'total_connections': self.pool_interface.get_total_connections(),
'max_configured': self.pool_interface.get_max_connections()
}
except Exception as e:
logger.error(f"Error getting pool metrics: {e}")
return {}
def _calculate_metrics(self, window_seconds: int = 60) -> Dict[str, float]:
"""Calculate metrics over a time window"""
now = time.time()
window_start = now - window_seconds
# Filter metrics within window
recent = [m for m in self.metrics_window
if m['timestamp'] >= window_start]
if not recent:
return {}
queue_times = [m['queue_time_ms'] for m in recent]
# Calculate percentiles
sorted_times = sorted(queue_times)
n = len(sorted_times)
def get_percentile(p: float) -> float:
if n == 0:
return 0
idx = int(n * p)
return sorted_times[min(idx, n - 1)]
metrics = {
'queue_time_avg': statistics.mean(queue_times) if queue_times else 0,
'queue_time_p50': get_percentile(0.5),
'queue_time_p95': get_percentile(0.95),
'queue_time_p99': get_percentile(0.99),
'queue_time_max': max(queue_times) if queue_times else 0,
'queue_time_min': min(queue_times) if queue_times else 0,
'request_count': n,
' starvation_probability': sum(1 for t in queue_times if t > 1000) / n if n > 0 else 0
}
return metrics
def _check_and_alert(self, metrics: Dict[str, float], violations: Dict[str, bool]):
"""Check for alert conditions and trigger alerts"""
now = datetime.utcnow()
for percentile, violated in violations.items():
if not violated:
continue
budget_key = f"queue_time_budget_{percentile}"
current_key = f"queue_time_{percentile}"
current_value = metrics.get(current_key, 0)
threshold = getattr(self.queue_budget.targets, percentile)
# Check cooldown for this specific alert
alert_id = f"{percentile}_budget_exceeded"
last_alert = self._last_alert_times.get(alert_id)
should_alert = (
not last_alert or
(now - last_alert).total_seconds() > self.alert_cooldown or
self.queue_budget.is_sustained_violation(percentile)
)
if should_alert:
severity = AlertSeverity.WARNING
if percentile == 'p99' or self.queue_budget.is_sustained_violation(percentile):
severity = AlertSeverity.CRITICAL
alert = Alert(
timestamp=now,
severity=severity,
message=f"{percentile} queue time ({current_value:.1f}ms) exceeds budget ({threshold}ms)",
metric=current_key,
current_value=current_value,
threshold=threshold,
context={
'violation_rate': self.queue_budget.get_violation_metrics().get(f"{percentile}_violation_rate", 0),
'consecutive_violations': sum(self.queue_budget._violation_history[percentile]),
'pool_size': self.adaptive_limits.current
}
)
self._trigger_alert(alert)
self._last_alert_times[alert_id] = now
def _trigger_alert(self, alert: Alert):
"""Trigger alert via callbacks"""
logger.log(
logging.CRITICAL if alert.severity == AlertSeverity.CRITICAL else logging.WARNING,
f"[{alert.severity.value}] {alert.message} | Context: {alert.context}"
)
for callback in self.alert_callbacks:
try:
callback(alert)
except Exception as e:
logger.error(f"Alert callback failed: {e}")
def _monitor_loop(self):
"""Main monitoring loop"""
logger.info("Starvation detection monitor started")
while self._running:
try:
# Get current metrics
metrics = self._calculate_metrics()
pool_metrics = self.get_pool_metrics()
# Check budget violations
if metrics:
violations = self.queue_budget.check_budget_violation(
[m['queue_time_ms'] for m in self.metrics_window
if m['timestamp'] >= time.time() - 60] # Last 60 seconds
)
# Check and alert
self._check_and_alert(metrics, violations)
# Calculate and apply adaptive adjustment
if self.pool_interface and pool_metrics:
adjustment = self.adaptive_limits.calculate_adjustment(
active_connections=pool_metrics.get('active_connections', 0),
waiting_requests=pool_metrics.get('waiting_requests', 0),
queue_time_avg=metrics.get('queue_time_avg', 0)
)
if adjustment:
actual = self.adaptive_limits.apply_adjustment(adjustment)
if actual != 0:
try:
self.pool_interface.set_max_connections(
self.adaptive_limits.current
)
logger.info(
f"Adjusted pool size: {self.adaptive_limits.current} "
f"(change: {actual:+d})"
)
except Exception as e:
logger.error(f"Failed to set pool size: {e}")
# Log periodic status (every 5 minutes)
if int(time.time()) % 300 == 0:
self._log_status(metrics, pool_metrics)
except Exception as e:
logger.error(f"Monitor loop error: {e}")
time.sleep(self._check_interval)
def _log_status(self, metrics: Dict, pool_metrics: Dict):
"""Log current status"""
logger.info(
f"Status: Pool={self.adaptive_limits.current}/{self.adaptive_limits.max}, "
f"QueueP50={metrics.get('queue_time_p50', 0):.1f}ms, "
f"P95={metrics.get('queue_time_p95', 0):.1f}ms, "
f"Active={pool_metrics.get('active_connections', 0)}, "
f"Waiting={pool_metrics.get('waiting_requests', 0)}"
)
def start(self):
"""Start the monitoring thread"""
if self._running:
return
self._running = True
self._monitor_thread = threading.Thread(
target=self._monitor_loop,
daemon=True,
name="StarvationDetector"
)
self._monitor_thread.start()
logger.info("Starvation detector started")
def stop(self):
"""Stop the monitoring thread"""
self._running = False
if self._monitor_thread and self._monitor_thread.is_alive():
self._monitor_thread.join(timeout=5)
logger.info("Starvation detector stopped")
def get_status(self) -> Dict[str, Any]:
"""Get complete detector status"""
metrics = self._calculate_metrics()
pool_metrics = self.get_pool_metrics()
return {
'detector': {
'running': self._running,
'queue_budget': self.queue_budget.targets,
'adaptive_limits': self.adaptive_limits.get_metrics(),
'violation_rates': self.queue_budget.get_violation_metrics()
},
'current_metrics': metrics,
'pool_metrics': pool_metrics,
'alert_cooldowns': {k: v.isoformat()
for k, v in self._last_alert_times.items()}
}
def force_adjustment(self, direction: str = "up"):
"""Manually trigger pool adjustment"""
current = self.adaptive_limits.current
if direction == "up" and current < self.adaptive_limits.max:
adjustment = min(
self.adaptive_limits.max - current,
max(1, int(current * 0.1))
)
elif direction == "down" and current > self.adaptive_limits.min:
adjustment = -min(
current - self.adaptive_limits.min,
max(1, int(current * 0.1))
)
else:
return 0
actual = self.adaptive_limits.apply_adjustment(adjustment)
if actual != 0 and self.pool_interface:
self.pool_interface.set_max_connections(self.adaptive_limits.current)
return actual
# Example Pool Interface Implementation
class ExampleConnectionPool:
"""Example connection pool that works with StarvationDetector"""
def __init__(self, initial_max: int = 10):
self._max_connections = initial_max
self._active_connections = 0
self._idle_connections = 0
self._waiting_requests = 0
self._lock = threading.RLock()
def get_connection(self, timeout: float = 30.0) -> Any:
"""Get connection with timing (simulated)"""
start_time = time.time()
with self._lock:
self._waiting_requests += 1
try:
# Simulate waiting for connection
while self._active_connections >= self._max_connections:
time.sleep(0.01) # Simulate wait
if time.time() - start_time > timeout:
raise TimeoutError("Timeout waiting for connection")
with self._lock:
self._waiting_requests -= 1
self._active_connections += 1
if self._idle_connections > 0:
self._idle_connections -= 1
# Simulate connection acquisition time
time.sleep(0.001)
# Calculate queue time and record
queue_time = (time.time() - start_time) * 1000 # Convert to ms
return {"id": id(self), "queue_time": queue_time}
finally:
pass
def release_connection(self, conn: Any):
"""Release connection back to pool"""
with self._lock:
self._active_connections -= 1
self._idle_connections += 1
# Pool interface methods required by StarvationDetector
def get_active_connections(self) -> int:
with self._lock:
return self._active_connections
def get_idle_connections(self) -> int:
with self._lock:
return self._idle_connections
def get_waiting_requests(self) -> int:
with self._lock:
return self._waiting_requests
def get_total_connections(self) -> int:
with self._lock:
return self._active_connections + self._idle_connections
def get_max_connections(self) -> int:
return self._max_connections
def set_max_connections(self, new_max: int):
with self._lock:
old_max = self._max_connections
self._max_connections = max(1, new_max)
logger.info(f"Pool max connections changed: {old_max} -> {self._max_connections}")
# Example usage
def example_alert_callback(alert: Alert):
"""Example alert callback - send to monitoring system"""
print(f"🚨 ALERT: {alert.severity.value} - {alert.message}")
print(f" Metric: {alert.metric}={alert.current_value:.1f} (threshold: {alert.threshold})")
print(f" Context: {alert.context}")
# Here you would send to: Prometheus, CloudWatch, PagerDuty, Slack, etc.
def main():
"""Example usage of the starvation detector"""
# Create pool and detector
pool = ExampleConnectionPool(initial_max=10)
detector = StarvationDetector(
min_connections=5,
max_connections=50,
initial_connections=10,
queue_time_budget_p50_ms=50,
queue_time_budget_p95_ms=200,
queue_time_budget_p99_ms=500,
adaptive_config={
'scale_up_threshold': 0.7,
'scale_down_threshold': 0.2,
'adjustment_cooldown_seconds': 60
},
alert_callbacks=[example_alert_callback]
)
# Connect detector to pool
detector.set_pool_interface(pool)
# Start monitoring
detector.start()
# Simulate workload
try:
for i in range(1000):
try:
conn = pool.get_connection(timeout=1.0)
# Simulate work
time.sleep(0.05)
pool.release_connection(conn)
# Record queue time from connection (in real pool, this would be automatic)
if hasattr(conn, 'queue_time'):
detector.record_queue_time(conn['queue_time'])
except TimeoutError:
logger.warning("Connection timeout - possible starvation")
# Vary load
if i % 100 == 0:
time.sleep(0.5) # Brief pause
time.sleep(0.01)
except KeyboardInterrupt:
print("\nShutting down...")
finally:
detector.stop()
# Print final status
status = detector.get_status()
print("\n=== Final Status ===")
print(f"Detector running: {status['detector']['running']}")
print(f"Final pool size: {status['detector']['adaptive_limits']['current_size']}")
print(f"Total adjustments: {status['detector']['adaptive_limits']['adjustment_count']}")
print(f"Recent metrics: P50={status['current_metrics'].get('queue_time_p50', 0):.1f}ms")
if __name__ == "__main__":
main()