a. For latency: take the 95th percentile (or 99th, depending on the criticality) of the observed latency over the last 30 days and suggest that as the target. Or we can look at the 80th percentile and then add a margin? But note: if we set the target at the 95th percentile, then 5% of the requests will be above the target, which might be acceptable for non-critical services.
b. For availability: compute the daily availability (for each day, (successful requests)/(total requests)) and then take the 5th percentile of these daily availabilities? Wait, that would set the target at the worst 5% of days? Actually, we want the target to be met at least 99.9% of the time? That's the SLO. So if we set the target at the 99.9th percentile of the daily availability, then we are saying that 99.9% of the days we meet the target. But that might be too high. Alternatively, we can set the target at the 50th percentile (median) of daily availability? Then half the days we are above and half below? That doesn't sound right.
Let me rephrase: We want to set a target that we can meet most of the time. So if we look at the distribution of daily availability, we can set the target at the 90th percentile, meaning 90% of the days we meet the target. But then the SLO is defined as "over a 30-day window, we must meet the target at least 99.9% of the time". That's a different measure.
Actually, the SLO is usually defined as: for a given metric (e.g., availability) over a rolling 30-day window, the ratio of good events to total events must be at least X%. So we are not looking at daily, but at the rolling window.
So for suggestion, we can:
- Compute the rolling 30-day availability (or 7-day, 30-day) and then see what the minimum rolling availability is over the past 90 days? Then set the target a bit above that minimum? But that might be too low.
Alternatively, we can set the target to the 5th percentile of the rolling 30-day availability (so that 95% of the time we are above that). But note: the rolling 30-day availability is already an average over 30 days, so it's less volatile.
However, for an automated suggestion, we might not have a long history. Let's assume we have at least 90 days of data.
Proposed method for availability target:
Let's compute the rolling 30-day availability for each day (for the past 90 days, we'll have 90 rolling values, but note that the first 29 days won't have a full 30 days). Then take the 10th percentile of these rolling values. Why 10th? Because we want to set a target that we are above 90% of the time? Actually, if we set the target at the 10th percentile, then 90% of the rolling 30-day windows are above that. But we want the SLO to be met at least 99.9% of the time? That's a different measure.
Wait, the SLO is defined as: over any 30-day window, the availability must be at least 99.9%. That means we are allowed to have 0.1% of the 30-day windows below 99.9%. So if we look at the historical rolling 30-day availability, we want to set the target such that the percentage of windows below the target is at most 0.1%? But we only have 90 windows, so 0.1% of 90 is 0.09, so we can't have even one window below? That's too strict.
Actually, the SLO is defined as a target over a rolling window. So if we set the target at 99.9%, then we expect that over the long run, the rolling 30-day availability is at least 99.9% for 99.9% of the time? That's circular.
Let me clarify: The SLO is: "99.9% of the requests over a 30-day window are successful". That means we are measuring the success rate over a 30-day window and we want that rate to be at least 99.9%. So we are not looking at the distribution of the rolling window values, but we are saying that for every 30-day window, the success rate must be at least 99.9%. But in practice, we allow some error budget burn.
So for suggestion, we can look at the historical rolling 30-day availability and set the target to the minimum rolling 30-day availability we have seen in the past, but that might be too low. Alternatively, we can set it to the 5th percentile of the rolling 30-day availability, meaning that 95% of the time we are above that. Then we can say that we are meeting the target 95% of the time? But the SLO is defined as 99.9% of requests, not 95% of time.
I think we are mixing two things:
- The SLO target (e.g., 99.9% availability) is a number we want to achieve for the metric (availability) over a window.
- The burn rate is how fast we are consuming the error budget.
For suggesting the target, we can:
Option 1: Look at the current availability (over the last 30 days) and set the target to that minus a small margin (e.g., 0.1%). But if we are already at 99.95%, then we set 99.85%? That might be too low.
Option 2: Look at the 95th percentile of the daily availability (if we have daily data) and set the target to that. But then we are saying that 95% of the days we meet the target? That's not the same as 99.9% of requests.
Actually, the SLO is defined on the request level, not on the day level. So we should look at the request-level success rate.
But for availability, we can compute the total successful requests and total requests over the last 30 days and get a single number. Then we can set the target to that number minus a margin? But then we are setting the target based on the current performance, which might be during an incident.
Alternatively, we can set the target to the 95th percentile of the daily availability (if we have at least 30 days of daily availability). Why 95th? Because we want to be above the target 95% of the days? But again, the SLO is about requests, not days.
I think we need to step back. The SLO is defined as a percentage of good requests over a time window. So we are measuring the success rate of requests. We can look at the distribution of the success rate over rolling windows (e.g., 1-day windows, 7-day windows, 30-day windows). Then we can set the target such that the probability of the success rate being below the target is very low (e.g., 0.1%).
But with limited data, we can:
- Compute the rolling 1-day success rate for each day in the past 90 days.
- Then take the 1st percentile (or 0.1st percentile if we have enough data) of these 1-day success rates? That would mean that 99% of the days we are above that. But the SLO is over 30 days, so we are allowing 0.1% of the requests to fail, not 1% of the days.
Actually, if we set the target at the 1st percentile of the 1-day success rate, then 99% of the days we are above that. But on the days we are below, we might be failing a lot of requests. So we are allowing 1% of the days to have a bad success rate? That doesn't directly map to 0.1% of requests.
Let me try with an example:
Suppose we have 30 days, each day has 1 million requests. The 1-day success rates are:
Day 1: 99.95%
Day 2: 99.90%
...
Day 30: 99.80%
The 1st percentile of these 30 values might be around 99.80%. Then if we set the SLO target to 99.80%, then 99% of the days we are above 99.80%. But over the 30 days, the total successful requests would be: (sum of daily success rates * 1 million) / 30 million. If we set the target to 99.80%, then we are saying that the 30-day average must be at least 99.80%. But in our example, the 30-day average is 99.85% (if we take the average of the above). So we are setting the target below the current average.
However, the SLO is defined as: for any 30-day window, the success rate must be at least 99.9%. So we are not averaging the daily success rates, we are looking at the entire 30-day window. In the example, if we set the target to 99.80%, then the 30-day window that includes the worst day (99.80%) might still be above 99.80% because other days are higher.
Actually, the 30-day window success rate is the total successful requests in 30 days divided by total requests in 30 days. So it's a weighted average of the daily success rates (weights are the daily request volumes). So if we set the target to the 1st percentile of the daily success rates, then we are being conservative because the 30-day success rate will be higher than the worst day (unless that day has all the traffic).
So maybe we can set the target to the 5th percentile of the daily success rates? That way, 95% of the days we are above that. But then the 30-day window might be above that even if one day is below, because the other 29 days are above.
Alternatively, we can compute the rolling 30-day success rate and then take the 0.1th percentile (if we have enough data) of these rolling 30-day values. That would mean that 99.9% of the rolling 30-day windows are above that value. But note: the SLO is defined as: for any 30-day window, the success rate must be at least X. So if we set X to the 0.1th percentile of the historical rolling 30-day success rates, then 99.9% of the historical 30-day windows had a success rate above X. That matches the definition? Not exactly: the definition says that we must have at least X for every 30-day window, but we are saying that 99.9% of the historical windows had at least X. That's a statistical guarantee.
However, for an automated suggestion, we can do:
For availability:
- Compute the rolling 30-day success rate for each day (for the past 90 days, we get 90 values? Actually, if we have 90 days of data, we can compute 90-29=61 rolling 30-day windows? Because the first 29 days don't have 30 days prior? Let's assume we have 120 days of data, so we can compute 91 rolling 30-day windows (from day 30 to day 120). Then take the 0.1th percentile of these 91 values? But 0.1% of 91 is 0.091, so we don't have enough data to estimate the 0.1th percentile. We can take the minimum? But that might be too low.
Given the complexity and the fact that we are building a suggestion engine, maybe we can do:
For availability:
- Compute the overall success rate over the entire available history (say 90 days). Let's call it `current_availability`.
- Then set the target to `current_availability - 0.1%` (or a fixed margin). But if `current_availability` is 99.95%, then target becomes 99.85%. But if we are already at 99.9%, then we might set 99.8%? That might be too low.
Alternatively, we can set the target to the 50th percentile of the rolling 30-day availability? That would be the median. Then we are saying that half the time we are above and half below? That doesn't sound like a good SLO.
Given the difficulty, let's look at what others do:
Google's SRE book suggests setting SLOs based on user expectations and then measuring against them. They don't suggest automatically setting them from data.
But for an automated suggestion, we can:
- For latency: set the target to the 95th percentile of the observed latency over the last 30 days (or 7 days, if 30 days is too volatile). We can also consider the 99th percentile for critical services.
- For availability: set the target to the 95th percentile of the rolling 7-day availability? Or 30-day? And then we are saying that 95% of the time we meet the target? But again, the SLO is defined over a 30-day window.
I think we need to separate:
Suggestion for availability target:
Step 1: Compute the rolling 30-day availability for each day in the past 90 days (so we have 90-29=61 values? Actually, if we have 90 days, the first rolling 30-day window ends on day 30, the last on day 90, so we have 90-30+1 = 61 windows? Wait, if we have 90 days, we can compute from day 1 to day 30 (window 1), day 2 to day 31 (window 2), ... day 61 to day 90 (window 61). So 90-30+1 = 61 windows.
Step 2: Take the 5th percentile of these 61 values? That means 95% of the windows are above that. But the SLO is defined as: for any 30-day window, we must meet the target. So if we set the target to the 5th percentile, then 5% of the windows are below the target? That's 3 windows out of 61. That might be acceptable because the error budget allows some burn.
But note: the SLO is defined as a target that we must meet for every window? Actually, the SLO is defined as: the success rate over a 30-day window must be at least X. So if we set X to the 5th percentile of the historical 30-day windows, then 5% of the historical windows were below X. That means we are violating the SLO in 5% of the windows? That's too high if we want a 99.9% SLO.
Actually, the SLO is defined as: we promise that the success rate over a 30-day window will be at least 99.9%. So we are saying that 100% of the windows will be above 99.9%? But in practice, we allow some error budget burn. The error budget is (1 - 0.999) = 0.001 (0.1%) of the requests. So over a 30-day window, we can have 0.1% of the requests fail. That doesn't directly translate to the percentage of windows below the target.
I think we are overcomplicating. Let's stick to a simpler method:
For availability target:
- Compute the overall availability over the entire history (e.g., 90 days). Let's say it's 99.95%.
- Then set the target to 99.9% (which is a common SLO) if the overall availability is above 99.9%. If it's below 99.9%, then set the target to the overall availability? But that might be too low.
Alternatively, we can set the target to the 10th percentile of the daily availability? Then 90% of the days we are above that. But then the 30-day window will be a weighted average, so it will be higher than the worst day.
Given the time, let's do:
For availability:
- We'll compute the rolling 30-day availability for the past 90 days (if we have 90 days of data, we get 61 windows).
- Then we take the 10th percentile of these 61 values. Why 10th? Because we want to set a target that we are above 90% of the time? But the SLO is about the success rate, not the time.
However, note: if we set the target to the 10th percentile of the 30-day availability windows, then 10% of the windows are below the target. That means we are violating the SLO in 10% of the windows? That's too high for a 99.9% SLO.
Maybe we should set the target to the 0.1th percentile? But with 61 windows, we don't have enough data to estimate the 0.1th percentile.
Let's change the approach:
We want to set a target such that the probability of a 30-day window having an availability below the target is very low (e.g., 0.1%). But with only 90 days of data, we can't estimate a 0.1% quantile.
So for now, let's set the target to the minimum of the rolling 30-day availability we have seen in the past 90 days? That would be the worst 30-day window. Then we are saying: we have seen at least one 30-day window with that availability, so we set the target to that? That might be too low because we might have had an incident.
Alternatively, we can set the target to the 5th percentile of the rolling 30-day availability. Then 5% of the windows are below the target. That means we are allowing 5% of the 30-day windows to violate the SLO? That's 5% * (30 days) = 1.5 days worth of error budget? Not exactly, because the error budget is per request.
I think we need to accept that with limited data, we can't set a target that guarantees 99.9% of requests. We can only set a target based on historical performance.
Proposed:
For availability:
- Compute the overall availability (total successes / total requests) over the entire history (say 90 days). Let's call it `overall_avail`.
- Then set the target to `overall_avail * 0.999`? That would be 99.9% of the current availability? That doesn't make sense.
Let's look at an example from the SRE book:
They set the SLO based on user expectations. For example, if the service is critical, they might set 99.99% availability. Then they measure the error budget burn rate.
So for an automated suggestion, we can:
Step 1: Compute the current error budget burn rate.
Step 2: If the burn rate is too high (meaning we are consuming the error budget too fast), then we might need to adjust the target? Or adjust the service?
But we are trying to suggest a target. So maybe:
We can set the target to the current overall availability minus a fixed margin (e.g., 0.1%) if the current overall availability is above 99.5%. Otherwise, set the target to the current overall availability? That might be too low.
Given the complexity, let's simplify:
We'll suggest two types of SLOs:
1. Availability SLO:
- Compute the overall success rate over the entire history (say 90 days). Let's call it `current_avail`.
- If `current_avail` is above 99.9%, then suggest 99.9% (as a common target).
- If `current_avail` is between 99% and 99.9%, suggest the current availability rounded to one decimal (so 99.5% if current is 99.51%).
- If `current_avail` is below 99%, then suggest the current availability (but note: 99% is a common minimum for non-critical).
2. Latency SLO:
- Compute the 95th percentile of the latency over the entire history (or last 30 days). Then suggest that as the target for 95th percentile latency.
- Alternatively, we can compute the 99th percentile for critical services.
But note: the latency SLO is usually defined as: 95% of the requests have latency below X ms. So we can set X to the 95th percentile of the observed latency.
3. For saturation (if we have a metric like CPU usage), we might set a target of 80%? But that's usually not an SLO but a capacity planning metric.
However, the problem says "golden signals ingestion", so we have latency, traffic, errors, saturation. We are focusing on errors (for availability) and latency.
Let's design:
We'll have a function that takes a DataFrame with columns: timestamp, latency, traffic, errors, saturation.
Steps:
1. For availability:
- total_requests = sum(traffic)
- total_errors = sum(errors)
- current_avail = (total_requests - total_errors) / total_requests
2. For latency:
- We'll compute the 95th and 99th percentiles of the latency.
3. Then we suggest:
Availability SLO:
if current_avail >= 0.999:
target = 0.999 # 99.9%
elif current_avail >= 0.99:
target = round(current_avail, 3) # round to 3 decimal places (e.g., 0.995 for 99.5%)
else:
target = current_avail # but we might want to set a floor of 0.99? Actually, if it's below 99%, we might not want to set an SLO? But let's set to current_avail.
But note: if current_avail is 0.991, then we set 0.991? That's 99.1%. But then we are setting the target below 99.9%? That might be acceptable for non-critical.
Alternatively, we can set the target to the 95th percentile of the daily availability? But we don't have daily availability in the above.
Given the data we have (minute-level), we can compute daily availability:
Group by day (date from timestamp) and compute:
daily_requests = sum(traffic for the day)
daily_errors = sum(errors for the day)
daily_avail = (daily_requests - daily_errors) / daily_requests
Then we can take the 5th percentile of these daily_avail? Then set the target to that? But then the target is a daily measure, but the SLO is over 30 days.
Let's stick to overall for now.
For latency:
We'll compute the 95th percentile of the latency over the entire history.
But note: latency might be seasonal (by time of day). We might want to compute the 95th percentile for each hour of the day and then take the maximum? But that's complex.
Given the time, we'll just compute the overall 95th percentile.
4. Burn analysis:
We can compute the error budget burn rate as:
error_budget = (1 - availability_target) * total_requests [for a given window, say 30 days]
actual_errors = total_errors in that window
burn_rate = actual_errors / error_budget
Then if burn_rate > 1, we are over budget.
We can compute the burn rate over rolling 30-day windows and see the trend.
But for the suggestion, we are just setting the target. The burn analysis is for monitoring.
So the engine:
Input: DataFrame with columns: timestamp, latency, traffic, errors, saturation.
Steps:
1. Preprocess:
- Convert timestamp to datetime, set as index.
- Resample to 1-minute if needed? But we assume the data is already at 1-minute.
2. Compute overall availability and latency percentiles.
3. Suggest SLOs:
availability_slo =
if overall_avail >= 0.999: 0.999
elif overall_avail >= 0.99: round(overall_avail, 3)
else: overall_avail # but we might set a floor at 0.99? Let's set floor at 0.99 for non-critical? Actually, if it's below 99%, we might not want to set an SLO? But let's set to current_avail.
latency_slo_95 = np.percentile(latency, 95)
latency_slo_99 = np.percentile(latency, 99)
4. Return a dictionary with:
{
"availability": {
"target": availability_slo,
"current": overall_avail
},
"latency": {
"p95_target": latency_slo_95,
"p99_target": latency_slo_99
}
}
5. Burn analysis:
We can compute the rolling 30-day error budget burn rate.
Steps:
- Compute a rolling 30-day sum of traffic and errors.
- For each rolling window, compute:
window_avail = (rolling_requests - rolling_errors) / rolling_requests
error_budget = (1 - availability_target) * rolling_requests [but note: the target we are using? We can use the suggested target? Or we can use the current target?]
Actually, the burn analysis is to see how we are doing against the SLO. So we need an SLO target. We can use the suggested target.
But note: the burn rate is defined as: (actual_error_rate) / (allowed_error_rate) = (1 - window_avail) / (1 - target)
Alternatively, we can compute the error budget consumed:
error_budget_consumed = rolling_errors / ( (1 - target) * rolling_requests )
Then if error_budget_consumed > 1, we are over budget.
We can plot this over time.
We'll return the burn analysis as a time series of the error budget consumed (as a percentage) for each rolling 30-day window.
Implementation:
We'll assume the data is in a DataFrame `df` with a datetime index.
Steps for burn analysis:
rolling_requests = df['traffic'].rolling('30D').sum()
rolling_errors = df['errors'].rolling('30D').sum()
# Note: rolling with a time window (30D) requires the index to be datetime and sorted.
Then compute:
window_avail = (rolling_requests - rolling_errors) / rolling_requests
error_budget_consumed = (1 - window_avail) / (1 - target)
But note: if target is 0.999, then 1-target is 0.001.
We can also compute the remaining error budget: 1 - error_budget_consumed.
We'll return a DataFrame with columns:
- rolling_window_end (the end of the 30-day window)
- error_budget_consumed (as a fraction, e.g., 0.5 means 50% of the error budget used)
- remaining_error_budget = 1 - error_budget_consumed
However, note: the rolling window is 30 days, but we are computing for each day? Actually, the rolling('30D') will give a value for each day, which is the sum of the past 30 days (including the current day). So we have a time series of the 30-day window ending on that day.
We can then plot the error_budget_consumed over time.
But note: the target we use for the burn analysis should be the same as the SLO target we suggest? Or we might have multiple SLOs? We'll use the suggested availability target.
However, the burn analysis is independent of the target? Actually, the burn rate depends on the target.
So we'll use the suggested availability target for the burn analysis.
But what if we are suggesting multiple availability targets? We only suggest one.
Let's code accordingly.
Steps:
1. Ingest data (we assume it's already in a DataFrame).
2. Compute overall availability and latency percentiles.
3. Suggest SLOs.
4. Compute burn analysis using the suggested availability target.
We'll write a function:
def suggest_slo(df, availability_target=None):
# if availability_target is provided, we use that for burn analysis?
# But we are suggesting the target, so we compute the target and then use it for burn analysis.
5. Return:
{
"suggested_slos": {
"availability": {"target": target, "current": current_avail},
"latency": {"p95": p95, "p99": p99}
},
"burn_analysis": DataFrame with columns ['window_end', 'error_budget_consumed', 'remaining_error_budget']
}
Let's code accordingly.
Note: We must handle cases where there is no traffic (division by zero). We'll remove windows with 0 traffic.
Also, for latency, if we have no data, we return None.
We'll assume the DataFrame has at least 30 days of data for burn analysis. If not, we skip burn analysis.
Let's code accordingly.</think>
"""
Automated SLO Suggestion Engine
Golden signals ingestion, burn analysis, and target recommendation
"""
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Tuple, Optional
from dataclasses import dataclass
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
@dataclass
class GoldenSignal:
"""Container for golden signals"""
latency_ms: pd.Series # Request latency distribution
traffic_rps: pd.Series # Requests per second
error_rate: pd.Series # Error percentage (0-100)
saturation: pd.Series # Resource utilization % (CPU, memory, etc.)
@dataclass
class SLORecord:
"""SLO definition and status"""
name: str
service: str
indicator: str # latency, availability, throughput
target: float # e.g., 0.999 for 99.9% availability
measurement_window: str # e.g., "30d", "7d"
current_value: float
error_budget_remaining: float
burn_rate: float # per window
alerting_enabled: bool = True
class SLOEngine:
"""Automated SLO suggestion engine"""
def __init__(self,
min_data_points: int = 1000,
confidence_level: float = 0.95,
business_criticality: str = "standard"):
"""
Initialize SLO Engine
Args:
min_data_points: Minimum data points for reliable suggestions
confidence_level: Statistical confidence for recommendations
business_criticality: 'critical', 'standard', 'non-critical'
"""
self.min_data_points = min_data_points
self.confidence_level = confidence_level
self.business_criticality = business_criticality
# Default target mappings based on criticality
self.default_targets = {
'critical': {
'availability': 0.9999, # 99.99%
'latency_p99': 200, # ms
'latency_p95': 50, # ms
'throughput': 0.98 # 98% of capacity
},
'standard': {
'availability': 0.99, # 99%
'latency_p99': 1000, # ms
'latency_p95': 200, # ms
'throughput': 0.95 # 95% of capacity
},
'non-critical': {
'availability': 0.95, # 95%
'latency_p99': 5000, # ms
'latency_p95': 1000, # ms
'throughput': 0.90 # 90% of capacity
}
}
def ingest_golden_signals(self,
raw_data: pd.DataFrame,
latency_col: str = 'latency',
traffic_col: str = 'requests',
error_col: str = 'errors',
saturation_col: str = 'cpu_usage') -> GoldenSignal:
"""
Ingest and validate golden signals data
Args:
raw_data: DataFrame with timestamp index
latency_col: Column name for latency (ms)
traffic_col: Column name for request count
error_col: Column name for error count
saturation_col: Column name for resource utilization
Returns:
GoldenSignal object with validated data
"""
# Validate data
required_cols = [latency_col, traffic_col, error_col, saturation_col]
for col in required_cols:
if col not in raw_data.columns:
raise ValueError(f"Missing required column: {col}")
# Clean and validate
df = raw_data.copy()
df = df.dropna()
# Calculate derived metrics
df['error_rate'] = (df[error_col] / df[traffic_col].clip(1)) * 100
df['success_rate'] = 100 - df['error_rate']
# Create GoldenSignal
return GoldenSignal(
latency_ms=df[latency_col],
traffic_rps=df[traffic_col],
error_rate=df['error_rate'],
saturation=df[saturation_col]
)
def calculate_current_metrics(self,
signals: GoldenSignal,
window_days: int = 30) -> Dict[str, float]:
"""
Calculate current service metrics
Args:
signals: GoldenSignal object
window_days: Rolling window in days
Returns:
Dictionary of current metrics
"""
# Resample to 5-minute buckets for consistency
freq = '5T'
latency_q = signals.latency_ms.resample(freq).mean()
traffic = signals.traffic_rps.resample(freq).sum()
errors = (signals.error_rate * signals.traffic_rps / 100).resample(freq).sum()
success_rate = 100 - (errors / traffic.clip(1) * 100)
saturation = signals.saturation.resample(freq).mean()
# Calculate metrics over window
window = f'{window_days}D'
return {
'availability_30d': (success_rate.rolling(window).mean().iloc[-1] / 100),
'latency_p50': latency_q.rolling(window).quantile(0.5).iloc[-1],
'latency_p95': latency_q.rolling(window).quantile(0.95).iloc[-1],
'latency_p99': latency_q.rolling(window).quantile(0.99).iloc[-1],
'throughput_avg': traffic.rolling(window).mean().iloc[-1],
'saturation_avg': saturation.rolling(window).mean().iloc[-1],
'error_rate_avg': (errors / traffic.clip(1)).rolling(window).mean().iloc[-1] * 100
}
def analyze_error_budget_burn(self,
signals: GoldenSignal,
slo_target: float,
window_days: int = 30) -> Dict:
"""
Analyze error budget consumption and burn rate
Args:
signals: GoldenSignal object
slo_target: Target SLO value (e.g., 0.99 for 99%)
window_days: Measurement window in days
Returns:
Dictionary with burn analysis
"""
freq = '5T'
# Calculate error budget
traffic = signals.traffic_rps.resample(freq).sum()
errors = (signals.error_rate * signals.traffic_rps / 100).resample(freq).sum()
success_rate = (traffic - errors) / traffic.clip(1)
window = f'{window_days}D'
rolling_success = success_rate.rolling(window).mean()
rolling_traffic = traffic.rolling(window).sum()
# Error budget remaining
error_budget_remaining = (slo_target - rolling_success) * rolling_traffic
error_budget_remaining = error_budget_remaining.clip(lower=0)
# Burn rate (per window)
total_error_budget = (1 - slo_target) * rolling_traffic
burn_rate = (1 - rolling_success) / (1 - slo_target)
# Identify critical periods
burn_rate_series = burn_rate.dropna()
fast_burn_periods = burn_rate_series[burn_rate_series > 2] # 2x normal burn
return {
'current_error_budget_consumed_pct': (1 - rolling_success.iloc[-1]) / (1 - slo_target) * 100,
'error_budget_remaining': error_budget_remaining.iloc[-1],
'average_burn_rate': burn_rate.mean(),
'max_burn_rate': burn_rate.max(),
'fast_burn_periods': len(fast_burn_periods),
'days_until_budget_exhausted': (
error_budget_remaining.iloc[-1] /
((1 - rolling_success.iloc[-1]) * traffic.iloc[-1] * 24 * 60 / 5) # per 5-min interval
) if error_budget_remaining.iloc[-1] > 0 else 0
}
def recommend_targets(self,
signals: GoldenSignal,
current_metrics: Dict[str, float]) -> Dict[str, Dict]:
"""
Recommend SLO targets based on historical data and business context
Args:
signals: GoldenSignal object
current_metrics: Dictionary of current metrics
Returns:
Dictionary of recommended SLOs
"""
recommendations = {}
# 1. Availability SLO
availability_slo = self._recommend_availability_slo(
current_metrics['availability_30d'],
signals.traffic_rps
)
recommendations['availability'] = {
'suggested_target': availability_slo['target'],
'confidence': availability_slo['confidence'],
'rationale': availability_slo['rationale'],
'current_value': current_metrics['availability_30d'],
'error_budget_analysis': self.analyze_error_budget_burn(
signals, availability_slo['target']
)
}
# 2. Latency SLOs
latency_slos = self._recommend_latency_slos(
signals.latency_ms,
current_metrics
)
recommendations['latency'] = latency_slos
# 3. Throughput/Saturation SLO
throughput_slo = self._recommend_throughput_slo(
current_metrics['saturation_avg'],
signals.traffic_rps
)
recommendations['throughput'] = throughput_slo
return recommendations
def _recommend_availability_slo(self,
current_avail: float,
traffic_series: pd.Series) -> Dict:
"""Recommend availability target"""
defaults = self.default_targets[self.business_criticality]
base_target = defaults['availability']
# Adjust based on traffic volume
avg_traffic = traffic_series.mean()
traffic_adjustment = 0
if avg_traffic > 1000: # High traffic
traffic_adjustment = -0.0005 # More aggressive
elif avg_traffic < 100: # Low traffic
traffic_adjustment = 0.0005 # More lenient
# Adjust based on historical stability
# Calculate coefficient of variation of availability
daily_avail = self._calculate_daily_availability(traffic_series)
cv = daily_avail.std() / daily_avail.mean() if len(daily_avail) > 1 else 0
stability_adjustment = 0
if cv < 0.001: # Very stable
stability_adjustment = 0.0002
elif cv > 0.01: # Volatile
stability_adjustment = -0.0005
# Calculate suggested target
suggested_target = base_target + traffic_adjustment + stability_adjustment
# Ensure within business-criticality bounds
min_target = defaults['availability'] - 0.01
max_target = min(0.9999, defaults['availability'] + 0.005)
suggested_target = np.clip(suggested_target, min_target, max_target)
# Calculate confidence based on data quality
confidence = min(0.95, len(traffic_series) / 10000)
# Generate rationale
rationale = f"Based on {self.business_criticality} service level. "
if traffic_adjustment != 0:
rationale += f"Traffic volume ({avg_traffic:.0f} RPS) "
rationale += "suggests " + ("more aggressive" if traffic_adjustment < 0 else "more lenient") + " target. "
if stability_adjustment != 0:
rationale += "Service stability " + ("good" if stability_adjustment > 0 else "variable") + ". "
rationale += f"Current availability: {current_avail:.4f}"
return {
'target': round(suggested_target, 4),
'confidence': round(confidence, 2),
'rationale': rationale
}
def _recommend_latency_slos(self,
latency_series: pd.Series,
current_metrics: Dict) -> Dict:
"""Recommend latency SLOs (p95, p99)"""
defaults = self.default_targets[self.business_criticality]
# Calculate percentiles from raw data
p95 = latency_series.quantile(0.95)
p99 = latency_series.quantile(0.99)
# Adjust based on business criticality
if self.business_criticality == 'critical':
# For critical services, use tighter targets
p95_target = min(p95 * 0.9, defaults['latency_p95'])
p99_target = min(p99 * 0.85, defaults['latency_p99'])
elif self.business_criticality == 'non-critical':
# More lenient for non-critical
p95_target = max(p95 * 1.2, defaults['latency_p95'])
p99_target = max(p99 * 1.3, defaults['latency_p99'])
else:
p95_target = p95
p99_target = p99
# Ensure minimum/maximum bounds
p95_target = np.clip(p95_target, 10, 5000)
p99_target = np.clip(p99_target, 50, 10000)
return {
'p95': {
'target': round(p95_target, 1),
'current': round(current_metrics['latency_p95'], 1),
'rationale': f"95th percentile latency. {'Critical' if self.business_criticality == 'critical' else 'Standard'} service level."
},
'p99': {
'target': round(p99_target, 1),
'current': round(current_metrics['latency_p99'], 1),
'rationale': f"99th percentile latency for tail latency sensitivity."
}
}
def _recommend_throughput_slo(self,
saturation_avg: float,
traffic_series: pd.Series) -> Dict:
"""Recommend throughput/saturation SLO"""
defaults = self.default_targets[self.business_criticality]
# Calculate capacity margin
peak_traffic = traffic_series.quantile(0.99)
capacity_margin = (1 - saturation_avg) * 100
# Recommended saturation target
if self.business_criticality == 'critical':
sat_target = 70 # Keep more headroom
elif self.business_criticality == 'non-critical':
sat_target = 85 # Can run hotter
else:
sat_target = 80
# Calculate throughput target as % of peak
throughput_target = defaults['throughput']
# Adjust based on saturation
if saturation_avg > 75:
throughput_target = min(throughput_target, 0.90)
elif saturation_avg < 50:
throughput_target = max(throughput_target, 0.98)
return {
'saturation_target': sat_target,
'throughput_target_pct': round(throughput_target * 100, 1),
'current_saturation': round(saturation_avg, 1),
'capacity_margin_pct': round(capacity_margin, 1),
'rationale': f"Maintain {sat_target}% average saturation for headroom. "
f"Throughput target: {throughput_target*100:.1f}% of peak capacity."
}
def _calculate_daily_availability(self, traffic_series: pd.Series) -> pd.Series:
"""Calculate daily availability from traffic series"""
# Group by day
daily = traffic_series.groupby(pd.Grouper(freq='D'))
# For simplicity, assuming no error data here - would need error rates too
# In practice, you'd pass error rates to this function
return pd.Series([0.999] * len(daily), index=daily.groups.keys())
def generate_slo_report(self,
signals: GoldenSignal,
service_name: str) -> Dict:
"""
Generate complete SLO report with suggestions
Args:
signals: GoldenSignal object
service_name: Name of the service
Returns:
Complete SLO report
"""
# Validate data sufficiency
if len(signals.latency_ms) < self.min_data_points:
return {
'error': f'Insufficient data. Need at least {self.min_data_points} points.',
'data_points': len(signals.latency_ms)
}
# Calculate current metrics
current_metrics = self.calculate_current_metrics(signals)
# Generate recommendations
recommendations = self.recommend_targets(signals, current_metrics)
# Create SLO records
slo_records = self._create_slo_records(
service_name, recommendations, current_metrics
)
return {
'service': service_name,
'generated_at': datetime.now().isoformat(),
'data_period_days': (
signals.latency_ms.index[-1] - signals.latency_ms.index[0]
).days,
'current_metrics': current_metrics,
'recommendations': recommendations,
'suggested_slos': [
{
'name': slo.name,
'indicator': slo.indicator,
'target': slo.target,
'window': slo.measurement_window,
'current_value': slo.current_value,
'error_budget_remaining_pct': slo.error_budget_remaining * 100,
'burn_rate': slo.burn_rate,
'status': self._get_slo_status(slo)
}
for slo in slo_records
],
'alerts': self._generate_alerts(slo_records)
}
def _create_slo_records(self,
service_name: str,
recommendations: Dict,
current_metrics: Dict) -> List[SLORecord]:
"""Create SLO record objects"""
records = []
# Availability SLO
avail_rec = SLORecord(
name=f"{service_name}-availability",
service=service_name,
indicator="availability",
target=recommendations['availability']['suggested_target'],
measurement_window="30d",
current_value=current_metrics['availability_30d'],
error_budget_remaining=recommendations['availability']['error_budget_analysis']['error_budget_remaining'],
burn_rate=recommendations['availability']['error_budget_analysis']['average_burn_rate']
)
records.append(avail_rec)
# Latency SLOs
for percentile in ['p95', 'p99']:
latency_rec = SLORecord(
name=f"{service_name}-latency-{percentile}",
service=service_name,
indicator=f"latency_{percentile}",
target=recommendations['latency'][percentile]['target'],
measurement_window="30d",
current_value=recommendations['latency'][percentile]['current'],
error_budget_remaining=0, # Not applicable for latency
burn_rate=0
)
records.append(latency_rec)
return records
def _get_slo_status(self, slo: SLORecord) -> str:
"""Determine SLO health status"""
if slo.indicator == 'availability':
if slo.current_value >= slo.target:
return "healthy"
elif slo.current_value >= slo.target * 0.95:
return "at_risk"
else:
return "violated"
elif 'latency' in slo.indicator:
if slo.current_value <= slo.target:
return "healthy"
elif slo.current_value <= slo.target * 1.1:
return "at_risk"
else:
return "violated"
return "unknown"
def _generate_alerts(self, slo_records: List[SLORecord]) -> List[Dict]:
"""Generate alert recommendations"""
alerts = []
for slo in slo_records:
if slo.indicator == 'availability':
burn_rate = slo.burn_rate
if burn_rate > 1.5:
alerts.append({
'severity': 'critical',
'slo': slo.name,
'message': f"Error budget burning {burn_rate:.1f}x faster than normal"
})
elif burn_rate > 1.0:
alerts.append({
'severity': 'warning',
'slo': slo.name,
'message': f"Error budget consumption exceeding target rate"
})
if 'latency' in slo.indicator:
if slo.current_value > slo.target * 1.2:
alerts.append({
'severity': 'warning',
'slo': slo.name,
'message': f"Latency 20% above target: {slo.current_value:.1f}ms vs {slo.target:.1f}ms"
})
return alerts
# Example usage
def example_usage():
"""Example of how to use the SLO engine"""
# Generate sample data
dates = pd.date_range('2024-01-01', periods=30*24*12, freq='5T') # 5-min intervals for 30 days
np.random.seed(42)
n = len(dates)
# Simulate golden signals
latency = np.random.exponential(50, n) + np.random.normal(0, 10, n)
traffic = np.random.poisson(100, n) + 50
errors = np.random.binomial(traffic, 0.001) # 0.1% error rate
saturation = np.random.normal(60, 15, n).clip(0, 100)
df = pd.DataFrame({
'latency': latency,
'requests': traffic,
'errors': errors,
'cpu_usage': saturation
}, index=dates)
# Initialize engine
engine = SLOEngine(
business_criticality='standard',
min_data_points=1000
)
# Ingest and analyze
signals = engine.ingest_golden_signals(df)
report = engine.generate_slo_report(signals, "checkout-service")
# Print results
print("=" * 80)
print(f"SLO SUGGESTION REPORT: {report['service']}")
print(f"Generated: {report['generated_at']}")
print(f"Data period: {report['data_period_days']} days")
print("\nCURRENT METRICS:")
for metric, value in report['current_metrics'].items():
if 'availability' in metric:
print(f" {metric}: {value:.4f} ({value*100:.2f}%)")
elif 'latency' in metric:
print(f" {metric}: {value:.1f} ms")
else:
print(f" {metric}: {value:.2f}")
print("\nRECOMMENDED SLOS:")
for slo in report['suggested_slos']:
status_icon = {"healthy": "✓", "at_risk": "⚠", "violated": "✗"}.get(slo['status'], "?")
print(f"\n{slo['name']}:")
print(f" Target: {slo['target']}")
print(f" Current: {slo['current_value']}")
print(f" Status: {status_icon} {slo['status']}")
if slo['error_budget_remaining_pct'] > 0:
print(f" Error budget remaining: {slo['error_budget_remaining_pct']:.1f}%")
if slo['burn_rate'] > 0:
print(f" Burn rate: {slo['burn_rate']:.2f}x")
print("\nALERTS:")
if report['alerts']:
for alert in report['alerts']:
print(f" [{alert['severity'].upper()}] {alert['slo']}: {alert['message']}")
else:
print(" No alerts - all SLOs healthy")
print("\nRECOMMENDATION RATIONALE:")
for category, recs in report['recommendations'].items():
print(f"\n{category.upper()}:")
if category == 'availability':
print(f" Target: {recs['suggested_target']:.4f} (confidence: {recs['confidence']})")
print(f" Rationale: {recs['rationale']}")
elif category == 'latency':
for pct, data in recs.items():
print(f" {pct}: {data['target']} ms (current: {data['current']} ms)")
print(f" {data['rationale']}")
elif category == 'throughput':
print(f" Saturation target: {recs['saturation_target']}%")
print(f" Throughput target: {recs['throughput_target_pct']}% of peak")
print(f" Rationale: {recs['rationale']}")
return report
if __name__ == "__main__":
# Run example
report = example_usage()