The user wants an "error budget policy simulator." This is a concept from Site Reliability Engineering (SRE).
An error budget represents the allowable amount of downtime or errors within a given period (usually a month) based on a Service Level Objective (SLO).
The simulator needs to handle:
- Scenarios: Simulating different rates of errors or outages over time.
- Burn Forecasts: Calculating how fast the error budget is being consumed and predicting when it will run out.
- Decision Support: Recommending actions based on the burn rate (e.g., "Slow down releases," "Page on-call," "Freeze feature development").
Key Concepts/Components:
- SLO (Service Level Objective): Target reliability (e.g., 99.9%).
- SLI (Service Level Indicator): Actual measurement (e.g., successful requests / total requests).
- Error Budget: 1 - SLO.
- Time Window: The period over which the budget is calculated (e.g., 30 days).
- Burn Rate: How fast we are consuming the budget relative to the ideal rate.
- Alerting Windows: Fast burn (minutes), moderate burn (hours), slow burn (days).
Architecture of the Simulator:
- Configuration: Define SLOs, Time Windows, and Alerting Thresholds (Standard SRE practices, e.g., Google's SRE workbook).
- Simulation Engine:
- Takes a stream of events or a synthetic scenario (e.g., "10% error rate for 5 minutes").
- Updates the state (Remaining Budget).
- Calculates current Burn Rate.
- Reporting/Output:
- Status (Safe, Warning, Critical).
- Forecast (Days remaining).
- Decision/Recommendation (Action to take).
Implementation Plan (Python Class Structure):
ErrorBudgetSimulator class:
__init__: Set SLO, total_requests, window_size.
consume_errors: Method to log errors and valid events.
calculate_metrics: Update SLI, consumed budget, burn rate.
check_policy: Compare burn rates against thresholds (2%, 5%, 10% of budget consumed in specific windows).
run_scenario: Helper to play out a timeline of events.
Refining the "Decision Support" aspect:
I shouldn't just print numbers. I should map specific burn rates to concrete policy actions.
- Fast Burn: Immediate page, halt deployments.
- Medium Burn: Ticket created, investigate non-critical.
- Slow Burn: Just monitoring, reliability debt accumulation.
Drafting the Code (Mental or Scratchpad):
- Inputs: Target SLO (e.g., 99.9%), Window (e.g., 30 days).
- Budget Calculation: Total requests in window * (1 - SLO).
- Burn Rate: (Errors observed / Budget allowed) normalized to time. Actually, simpler is:
(Current Error Rate) / (Max Allowed Error Rate).
- Max Allowed Error Rate = (1 - SLO).
- Current Error Rate = Errors / Total Requests.
- Burn Rate = Current Error Rate / Max Allowed Error Rate.
- Ideal Burn Rate = 1.0 (meaning we finish the budget exactly at the end of the month).
- Burn Rate > 1 means we run out early.
Scenario Examples:
- The "Happy Path": Low error rate.
- The "Outage": High error rate for a short time.
- The "Death Spiral": Consistent medium-high error rate draining budget slowly but surely.
Python Implementation Details:
- I'll use
pandas if complex data manipulation is needed, but standard Python libraries are probably sufficient and easier to run as a standalone script for the user. Let's stick to standard libraries + maybe math to keep it dependency-light.
- I will simulate a time window (e.g., a month) stepping through hours or minutes.
Step-by-Step Logic for the Simulator:
- Define constants (SLO = 99.9%).
- Define Alerting Policy thresholds (based on standard SRE guides):
- Fast Burn: consuming 2% of budget in 1 hour.
- Slow Burn: consuming 5% of budget in 6 hours.
- (Simplified for the simulator).
- Create a function to inject traffic (requests) and errors.
- Track state:
total_requests
total_errors
remaining_budget
- Evaluate decision logic at each step.
Adding a "Forecast":
- If current burn rate is maintained, when does budget hit 0?
Time_Remaining = (Remaining_Budget) / (Burn_Rate * Budget_Per_Unit_Time)? No, simpler:
Budget_Remaining (in errors) / Current_Error_Rate (errors per time unit).
Let's write the code structure.
I'll create a Python script that acts as a CLI tool or a library.
I will include a main execution block that runs 3 distinct scenarios.
Scenario 1: Small Spike.
Scenario 2: Chronic background noise.
Scenario 3: Catastrophic failure.
Refining the Output:
The output needs to be readable. A table or clear text summary per time step.
Decision support needs to be text: "Recommendation: Freeze feature releases. Focus on tech debt."
Self-Correction during thought process:
Calculating exact burn rates over rolling windows is complex math. To keep this robust but understandable, I will simulate a simplified "Burn Rate" based on the current ratio of actual errors vs allowed errors, or simulate rolling windows if I keep the state in a list/deque.
Decision: Let's use a deque to simulate a rolling time window for accurate "Fast Burn" vs "Slow Burn" detection. This makes it more realistic.
The Policy Logic (The "Brain"):
- If (Budget Remaining < 10%) -> ACTION: RELIABILITY FREEZE.
- If (Burn Rate > 10x) -> ACTION: PAGE NOW (Fast Burn).
- If (Burn Rate > 2x) -> ACTION: TICKET (Slow Burn).
- If (Burn Rate <= 1) -> ACTION: PROCEED (Safe).
Let's put it together.
- Class
ErrorBudgetSimulator:
config: SLO, Window (seconds).
state: List of events (timestamp, is_error).
report(t): Aggregates events, computes metrics, returns decision.
Let's write the Python code. I will focus on clean, commented code and a "Scenario Runner" to demonstrate the decision support.
Final Polish of the Request:
The user asked for "Scenarios, burn forecasts, and decision support."
I will ensure the output explicitly labels these three sections.
- Scenarios: Defined in the code as specific traffic patterns.
- Burn Forecasts: Calculated as "Days/Hours until exhaustion".
- Decision Support: Explicit text actions printed to the console.
Let's generate the solution.
This solution implements a comprehensive Error Budget Policy Simulator in Python.
It models an SRE scenario where a service has a specific reliability target (SLO). It tracks the "budget" remaining, simulates different failure scenarios (spikes vs. slow burns), calculates burn rate forecasts, and outputs decision support recommendations (e.g., "Declare Incident" or "Freeze Releases").
Core Concepts Used
- SLO (Service Level Objective): The target reliability (e.g., 99.9%).
- Error Budget: The allowed amount of downtime/failure within a window.
- Burn Rate: How fast you are consuming your budget relative to the passage of time.
- Alerting Windows: We use standard SRE multi-window burn rate alerts (e.g., checking burn over the last 1 hour vs the last 5 minutes).
Python Implementation
import datetime
import random
import math
class ErrorBudgetPolicySimulator:
def __init__(self, slo_target: float, window_days: int = 30):
"""
Initialize the simulator.
:param slo_target: The SLO target (e.g., 0.999 for 99.9%)
:param window_days: The rolling window for the error budget (e.g., 30 days)
"""
self.slo_target = slo_target
self.error_budget_target = 1.0 - slo_target
# Total expected requests in the window (normalized to 1.0 for the simulator)
# We simulate based on budget units.
# 1.0 Budget = 100% of the allowed error budget for the month.
self.max_budget = 1.0
self.remaining_budget = 1.0
# Time tracking
self.window_days = window_days
self.current_step = 0 # Represents minutes passed
# History for forecasting and burn rate calculation
# Stores tuples of (timestamp_step, budget_consumed_in_step)
self.event_history = []
def get_allowed_budget_per_minute(self):
""" How much budget are we allowed to burn per minute if we want to exactly hit 0 at the end? """
total_minutes = self.window_days * 24 * 60
return self.max_budget / total_minutes
def simulate_traffic(self, burn_rate_factor: float = 1.0):
"""
Simulate one minute of traffic.
:param burn_rate_factor:
1.0 = Normal traffic (exactly on SLO limit).
0.0 = Perfect reliability (no budget used).
2.0 = Burning budget twice as fast as allowed.
50.0 = Major outage.
"""
allowed_burn = self.get_allowed_budget_per_minute()
actual_burn = allowed_burn * burn_rate_factor
self.remaining_budget -= actual_burn
self.current_step += 1
self.event_history.append((self.current_step, actual_burn))
# Clip budget (can't have negative reliability in this simple model)
if self.remaining_budget < -0.1: self.remaining_budget = -0.1
def get_current_burn_rate(self, window_minutes: int = 60):
"""
Calculate the current burn rate over the last X minutes.
Returns: A factor (e.g., 2.0 means burning 2x faster than allowed)
"""
if len(self.event_history) < 2: return 0
# Slice history to the window
start_step = max(0, self.current_step - window_minutes)
relevant_events = [burn for step, burn in self.event_history if step >= start_step]
total_burned = sum(relevant_events)
# How much *should* we have burned in that window?
expected_burn = self.get_allowed_budget_per_minute() * len(relevant_events)
if expected_burn == 0: return 0
return total_burned / expected_burn
def forecast_exhaustion(self):
"""
Predicts when the budget will hit 0 if current trends continue.
"""
current_burn = self.get_current_burn_rate(60) # Look at last hour trend
if current_burn <= 0:
return "Never (System Healthy)"
remaining = self.remaining_budget
allowed_per_min = self.get_allowed_budget_per_minute()
# Time remaining = Remaining Budget / (Allowed Burn Rate * Current Burn Factor)
# = Remaining / (Current Actual Burn Rate)
current_actual_burn_per_min = allowed_per_min * current_burn
if current_actual_burn_per_min <= 0:
return "Never (System Healthy)"
minutes_left = remaining / current_actual_burn_per_min
if minutes_left < 0: return "Exhausted"
if minutes_left > 60 * 24 * 30: return "> 30 Days"
hours = int(minutes_left / 60)
mins = int(minutes_left % 60)
return f"{hours}h {mins}m"
def get_policy_decision(self):
"""
Decision Support Logic based on Burn Rates and Remaining Budget.
This mimics a standard SRE error budget policy.
"""
remaining_pct = self.remaining_budget * 100
# Calculate Burn Rates for different windows (Fast vs Slow alerts)
burn_5m = self.get_current_burn_rate(5)
burn_1h = self.get_current_burn_rate(60)
burn_24h = self.get_current_burn_rate(1440)
decision = {
"status": "NORMAL",
"action": "No action required.",
"burn_rate_5m": burn_5m,
"burn_rate_1h": burn_1h,
"remaining_budget_pct": remaining_pct
}
# 1. Critical: Budget Exhausted
if remaining_pct <= 0:
decision["status"] = "CRITICAL"
decision["action"] = "🛑 BUDGET EXHAUSTED. Freeze all non-emergency changes. Reliability sprint required."
return decision
# 2. High Burn (Short Window) -> Outage Detection
# If burning > 10x speed in 5 mins, it's a major outage.
if burn_5m > 10 and burn_1h > 5:
decision["status"] = "ALERT"
decision["action"] = "🔥 HIGH BURN (>10x). Trigger Incident Response. Page on-call."
return decision
# 3. Medium Burn (Long Window) -> Creeping Failure
# If burning > 2x speed for an hour.
if burn_1h > 2:
decision["status"] = "WARNING"
decision["action"] = "⚠️ ELEVATED BURN (2x). Investigate immediately. Check recent deploys."
return decision
# 4. Budget Thresholds (Policy Enforcement)
if remaining_pct < 10:
decision["status"] = "DANGER"
decision["action"] = "🚨 BUDGET LOW (<10%). Halt feature development. Focus solely on reliability."
elif remaining_pct < 25:
decision["status"] = "CAUTION"
decision["action"] = "⚡ BUDGET TIGHT (<25%). Prioritize bug fixes over features."
return decision
def run_scenario(self, name, steps, burn_generator):
print(f"\n--- 🔬 SCENARIO: {name} ---")
print(f"{'Time (m)':<10} | {'Budget Left':<15} | {'Burn (5m)':<10} | {'Forecast':<15} | {'Decision'}")
print("-" * 85)
for _ in range(steps):
# Get burn factor from the generator function
factor = burn_generator()
self.simulate_traffic(factor)
# Log every 10 minutes to keep output clean
if self.current_step % 10 == 0 or self.current_step == 1:
d = self.get_policy_decision()
forecast = self.forecast_exhaustion()
print(f"{self.current_step:<10} | {d['remaining_budget_pct']:<15.2f} | {d['burn_rate_5m']:<10.2f} | {forecast:<15} | {d['status']}")
if d['status'] == "ALERT":
print(f" >>> ACTION: {d['action']}")
# --- Scenario Generators ---
def gen_healthy():
"""Simulates traffic well within SLO (0.5x burn rate)."""
return random.uniform(0, 0.8)
def gen_slow_leak():
"""Simulates a slow, hard-to-detect leak (1.5x burn rate)."""
return 1.5
def gen_catastrophic_outage():
"""Simulates a sudden massive spike."""
# We introduce a spike at minute 30
if 30 <= ErrorBudgetPolicySimulator.current_step <= 40: # Accessing static context isn't ideal but works for simple script
return 50.0 # 50x burn rate
return 0.5
# --- Execution ---
if __name__ == "__main__":
# Setup a 99.9% SLO over a 30 day rolling window
simulator = ErrorBudgetPolicySimulator(slo_target=0.999, window_days=30)
# Scenario 1: The "Happy Path"
simulator.run_scenario("Normal Traffic (Below SLO)", steps=60, burn_generator=gen_healthy)
# Reset for next scenario
simulator = ErrorBudgetPolicySimulator(slo_target=0.999, window_days=30)
# Scenario 2: The "Slow Burn" (Stealthy issue)
# Notice how the forecast drops rapidly
simulator.run_scenario("Slow Configuration Leak (1.5x Burn)", steps=120, burn_generator=gen_slow_leak)
# Reset for next scenario
simulator = ErrorBudgetPolicySimulator(slo_target=0.999, window_days=30)
# Scenario 3: The "Outage" (Sudden Spike)
# Note: Because the generator logic depends on step count, we wrap it to use the instance step
def gen_outage_wrapper():
if 30 <= simulator.current_step <= 40:
return 50.0
return 0.5
simulator.run_scenario("Major Outage (50x Burn)", steps=60, burn_generator=gen_outage_wrapper)
How to Interpret the Output
- Budget Left: This is the percentage of your "allowed errors" remaining. If this hits 0, you have violated the SLO for the month.
- Burn (5m): This is the Burn Rate.
- 1.0 means you are consuming budget exactly at the rate time passes (perfect pacing).
- > 1.0 means you are consuming budget faster than time (you will run out before the month ends).
- < 1.0 means you are building a surplus.
- Decision Logic:
- Alert: Triggered only when the Burn Rate spikes significantly (e.g., >10x) over a short window. This mimics a "Page."
- Warning: Triggered when the Burn Rate is consistently elevated (e.g., >2x) but not catastrophic.
- Danger: Triggered when the absolute Budget remaining is low, regardless of current burn rate.
Example Output Explanation
- Scenario 1: You will see the budget increase (surplus) because the burn rate is < 1.0. Forecast says "> 30 days".
- Scenario 2: The burn rate hovers around 1.5. The forecast will start ticking down (e.g., "15d 2h"), indicating that if this leak continues, the SLO will be missed in 15 days.
- Scenario 3: At minute 30, the Burn Rate spikes to 50.00. The system immediately flags an ALERT status, recommending a page, even if the overall budget is still 99% full. This demonstrates using burn rate alerts to catch issues before they consume the whole budget.