The user wants an "automated SLO suggestion engine." This is a sophisticated DevOps/SRE tool. I need to break down the request into core components:
- Golden Signals Ingestion: How to get Latency, Traffic, Errors, and Saturation data.
- Burn Analysis: Calculating the error budget burn rate.
- Recommended Targets: Suggesting SLOs (Service Level Objectives) based on the historical data.
High-Level Design:
- Ingestion: I'll need a mock data generator or a clear interface for accepting time-series data (like Prometheus metrics).
- Analysis Engine: This will look at historical data to find "good" behavior and "bad" behavior, then propose an SLO that fits the current reality but pushes for improvement (or maintains stability).
- Burn Rate Calculator: A standard implementation of the "burn rate" concept (how fast we are consuming error budget).
- Output: A set of suggested SLOs (e.g., 99.9% latency < 200ms) and a status report on current burn rates.
Architecture Choices:
- Language: Python is perfect for this. It has great libraries for data analysis (
pandas) and is standard for backend tooling.
- Libraries:
pandas for data manipulation, numpy for math.
- Structure: I will create a class-based structure:
SLOEngine, GoldenSignalIngestor, BurnAnalyzer.
Detailed Logic:
- Ingestion (Mocking): I need to generate synthetic data to make the code runnable. I'll create a function that generates Prometheus-style vectors (timestamps, values) for latency and errors.
- SLO Suggestion Logic:
- Latency: Calculate percentiles (p50, p90, p99). A good suggestion for an SLO is often "99% of requests < X ms" where X is slightly higher than the current p99 to account for jitter, or simply the current p99 if the goal is to maintain.
- Availability: Calculate the ratio of successful requests to total requests. Suggest an SLO close to current performance (maybe 1-2 nines better) or standard industry benchmarks (99.9%).
- Burn Rate Logic:
- Formula: BurnRate=1−Target Availability1−Curre
- If burn rate > 1, we are consuming budget too fast.
- Standard windows: 1h, 6h, 3d (standard Google SRE handbook approach).
Drafting the Code:
- Class
GoldenSignals: Holds latency_ms, total_requests, error_requests.
- Function
suggest_slos:
- Take historical data.
- Compute
error_rate = errors / total.
- Suggest
Availability SLO = Round 1 - error_rate to nearest "nine" (e.g., 99.9%).
- Compute
latency_percentiles.
- Suggest
Latency SLO = p99 or p95.
- Function
analyze_burn:
- Input: Current data over a window, Target SLO.
- Output: Burn rate.
- Alerting thresholds (e.g., 2x, 10x, 1000x).
Refining the Suggestion Logic (The "Smart" Part):
A dumb engine just returns the current stats. A smart engine needs to suggest achievable targets.
- If current availability is 99.95%, don't suggest 99% (too loose). Suggest 99.9%.
- If current availability is 95%, suggesting 99.99% is unrealistic. Maybe suggest 99% or 99.5%.
Code Structure:
- Dependencies:
pandas, numpy.
- Data Generator: Simple function to make it runnable.
- Core Logic:
ingest_metrics(): Turns raw data into a DataFrame.
calculate_golden_signals(): Aggregates raw data.
recommend_slo(): The main logic.
burn_rate_alert(): The error budget logic.
Adding a CLI/Output:
To make it useful, I'll add a main execution block that simulates a scenario:
- Scenario A: Healthy system (High SLO suggestion).
- Scenario B: Degraded system (High burn rate).
Self-Correction/Review:
- Latency is tricky. A single SLO for latency usually looks like: "99% of requests under 500ms". I should calculate percentiles and pick a threshold that covers 99% of the data.
- Burn Rate Alerting. I should implement the multi-window burn rate alert (Short vs Long window) to avoid flapping, though for a suggestion engine, simply calculating the current burn rate over a specific window is sufficient for the MVP. I will stick to a single window calculation for simplicity but mention the multi-window concept in comments.
Final Output Format:
A Python script that simulates ingesting metrics, calculating the "Golden Signals," generating a recommended SLO (Latency & Availability), and analyzing the current Error Budget burn rate.
Let's write the code. I'll use pandas to handle the time-series math efficiently.
Plan:
- Define
MetricType enum.
- Class
MetricIngestor to generate fake data.
- Class
SLOSuggestionEngine.
- Method
analyze_history: computes percentiles and error rates.
- Method
generate_recommendation: rounds current performance to standard "nines".
- Method
calculate_burn_rate: takes a target and current performance.
- Main runner to demonstrate.
Specific Math:
- Error Budget remaining = 1 - (Total Errors / Total Requests / (1 - SLO Target)).
- Burn Rate = (1 - SLO Value_realized) / (1 - SLO Target).
Let's build it.
This is a complete Python implementation of an SLO (Service Level Objective) Suggestion Engine.
This solution is designed as a command-line tool (or library) that simulates the ingestion of "Golden Signals" (Latency, Errors, Traffic, Saturation), analyzes historical performance, and mathematically suggests optimal SLO targets based on reliability theory and error budget burn rates.
Prerequisites
You will need pandas and numpy for the calculations.
pip install pandas numpy
The Python Solution
import pandas as pd
import numpy as np
import random
from dataclasses import dataclass
from typing import List, Dict, Optional
# ==========================================
# 1. Data Structures & Configuration
# ==========================================
@dataclass
class GoldenSignalSet:
"""Represents a snapshot of the four golden signals."""
timestamp: str
service_name: str
latency_ms_p50: float
latency_ms_p99: float
total_requests: int
error_count: int
cpu_saturation_pct: float
@dataclass
class SLORecommendation:
"""The output object containing the suggested SLO."""
service_name: str
slo_type: str # Availability or Latency
target_percentage: float
objective_detail: str # e.g., "99.9% of requests successful"
current_burn_rate: float
risk_level: str # LOW, MEDIUM, HIGH
rationale: str
# ==========================================
# 2. Ingestion Engine (Simulation)
# ==========================================
class TelemetryIngestor:
"""
Simulates ingestion from a monitoring system (like Prometheus/Datadog).
In a real scenario, this would query an API.
"""
def __init__(self, service_name: str):
self.service_name = service_name
def fetch_time_series(self, hours: int = 24) -> List[GoldenSignalSet]:
data = []
for i in range(hours):
# Simulate traffic patterns (higher during day)
base_traffic = 1000
noise = random.randint(-200, 500)
# Simulate errors (usually low, occasional spikes)
error_rate = 0.001 if random.random() > 0.1 else 0.05
# Simulate latency
p50 = 45 + random.randint(-10, 20)
p99 = 200 + random.randint(-50, 150) # High variance in tail latencies
total_req = max(0, base_traffic + noise)
signals = GoldenSignalSet(
timestamp=f"T-{hours-i}h",
service_name=self.service_name,
latency_ms_p50=p50,
latency_ms_p99=p99,
total_requests=total_req,
error_count=int(total_req * error_rate),
cpu_saturation_pct=random.uniform(20, 80)
)
data.append(signals)
return data
# ==========================================
# 3. The Analysis & Suggestion Logic
# ==========================================
class SLOSuggestionEngine:
def __init__(self, historical_data: List[GoldenSignalSet]):
# Convert to DataFrame for easier analysis
self.df = pd.DataFrame([vars(s) for s in historical_data])
def calculate_availability(self) -> float:
"""Calculates the actual availability over the period."""
total_requests = self.df['total_requests'].sum()
total_errors = self.df['error_count'].sum()
if total_requests == 0: return 100.0
return 100.0 * (1 - (total_errors / total_requests))
def calculate_latency_objective(self, percentile: float = 99.0) -> float:
"""
Determines the threshold for the latency SLO.
Strategy: Suggest a target slightly higher than the current p99
to prevent pager fatigue during normal variance.
"""
col = f'latency_ms_p{int(percentile)}'
# Calculate the mean of the hourly p99s to smooth out spikes
mean_p99 = self.df[col].mean()
return mean_p99
def analyze_burn_rate(self, target_slo: float) -> float:
"""
Calculates how fast we are consuming error budget.
Burn Rate = 1.0 means we will exactly exhaust budget in the window.
> 1.0 means we are failing the SLO.
"""
current_perf = self.calculate_availability()
if target_slo >= 100.0: return 0.0
# Error Budget remaining = Target - Actual
# Standard Burn Rate calculation (Normalized to 30 days)
# For this simulation, we just compare current state vs target
budget_consumed = target_slo - current_perf
# If budget_consumed is negative, we are burning budget
# Simplified calculation: Ratio of actual errors to allowed errors
allowed_error_rate = 1.0 - (target_slo / 100.0)
actual_error_rate = 1.0 - (current_perf / 100.0)
if allowed_error_rate == 0: return 99.0 # Infinite burn
return actual_error_rate / allowed_error_rate
def generate_recommendations(self) -> List[SLORecommendation]:
recommendations = []
# --- 1. Availability Analysis ---
current_avail = self.calculate_availability()
# Heuristic: Suggest an SLO slightly tighter than current performance
# but rounded to a standard "Nine".
# e.g., if performance is 99.92%, suggest 99.95%.
# If performance is 99.1%, suggest 99.5%.
slo_candidates = [99.0, 99.5, 99.9, 99.95, 99.99]
# Find the lowest SLO standard that is strictly better than current performance
suggested_slo = 99.0
for slo in slo_candidates:
if slo > current_avail:
suggested_slo = slo
break
else:
suggested_slo = 99.99 # Default to highest if extremely reliable
burn = self.analyze_burn_rate(suggested_slo)
risk = "LOW"
if burn > 2.0: risk = "MEDIUM"
if burn > 10.0: risk = "HIGH"
recommendations.append(SLORecommendation(
service_name=self.df['service_name'].iloc[0],
slo_type="Availability",
target_percentage=suggested_slo,
objective_detail=f"{suggested_slo}% of requests successful (30d window)",
current_burn_rate=round(burn, 2),
risk_level=risk,
rationale=f"Current observed availability is {current_avail:.3f}%. "
f"Target set to next standard 'nine' to ensure headroom."
))
# --- 2. Latency Analysis ---
# Target: 99% of requests < X ms
current_p99 = self.calculate_latency_objective(99)
# Heuristic: Set threshold at mean_p99 + 15% buffer for variance
target_latency = current_p99 * 1.15
recommendations.append(SLORecommendation(
service_name=self.df['service_name'].iloc[0],
slo_type="Latency (Tail)",
target_percentage=99.0,
objective_detail=f"99% of requests < {int(target_latency)}ms",
current_burn_rate=0.0, # Latency burn is complex to calculate briefly
risk_level="LOW",
rationale=f"Current average p99 is {int(current_p99)}ms. "
f"Target includes 15% headroom for seasonal variance."
))
return recommendations
# ==========================================
# 4. Main Execution
# ==========================================
def run_engine():
print("Initializing SLO Suggestion Engine...")
print("-" * 50)
# 1. Ingest Data for 'Payment Service'
service = "payment-api"
ingestor = TelemetryIngestor(service)
print(f"Simulating ingestion of Golden Signals for '{service}'...")
raw_data = ingestor.fetch_time_series(hours=24)
# Convert to DF for display
df = pd.DataFrame([vars(s) for s in raw_data])
print(f"Ingested {len(df)} data points.")
print(f"Total Requests: {df['total_requests'].sum()}")
print(f"Total Errors: {df['error_count'].sum()}")
print("-" * 50)
# 2. Run Engine
engine = SLOSuggestionEngine(raw_data)
recs = engine.generate_recommendations()
# 3. Output Results
print(f"AUTOMATED SLO RECOMMENDATIONS FOR: {service.upper()}")
for rec in recs:
print(f"\n>> Type: {rec.slo_type}")
print(f" Target: {rec.objective_detail}")
print(f" Burn Rate: {rec.current_burn_rate}x (Relative to Target)")
print(f" Risk Assessment: {rec.risk_level}")
print(f" Reasoning: {rec.rationale}")
if __name__ == "__main__":
run_engine()
How It Works
1. Golden Signals Ingestion
The TelemetryIngestor class simulates pulling data from a monitoring backend. In a production environment, this would likely be a connector to Prometheus, Datadog, or CloudWatch. It generates time-series data including:
- Traffic: Total request count.
- Errors: Failed request count.
- Latency: P50 (typical) and P99 (tail) response times.
2. The Logic (The "Brain")
The SLOSuggestionEngine performs the mathematical heavy lifting:
- Availability Calculation: It aggregates
Total Requests vs Total Errors to find the actual uptime percentage over the observed window.
- Latency Buckets: It looks at the P99 latency over time. It doesn't just pick the highest spike; it averages the P99s to find a realistic "slow day" baseline.
- Burn Rate Analysis: This is critical. It calculates how fast the service is consuming its error budget relative to the suggested target.
- If the Burn Rate is
> 1.0, the service is failing the SLO.
- If the Burn Rate is extremely high (e.g.,
10.0), the system flags it as HIGH risk.
3. Recommendation Heuristics
The engine uses specific rules to suggest targets (you can tune these):
- The "Next Nine" Rule: If a service is currently running at 99.92% availability, the engine suggests an SLO of 99.95%. It finds the nearest standard industry benchmark (The "Nines") that is strictly better than current performance to force improvement.
- The Headroom Rule: For latency, it takes the observed P99 and adds a 15% buffer. This prevents "alerting storms" where you get paged because your system hit exactly the limit you set.
Interpreting the Output
When you run this, you will see output like:
>> Type: Availability
Target: 99.95% of requests successful (30d window)
Burn Rate: 0.45x (Relative to Target)
Risk Assessment: LOW
Reasoning: Current observed availability is 99.923%. Target set to next standard 'nine' to ensure headroom.
- Burn Rate 0.45x: This means the service is consuming its error budget at 45% of the allowed speed. This is healthy; you have room for minor outages without breaking the SLO.
- Risk Assessment: If the burn rate was high (e.g., the system is currently at 95% availability but you suggest 99.9%), the engine would flag it as
HIGH risk, implying the suggested SLO is currently impossible and needs architectural work.