How to Calculate SLO Error Budget in Python
Simulate an SLO error budget by computing allowed downtime from a target availability percentage and mocking monthly incidents.
Python code
25 lines```python
import random
def calculate_error_budget(total_seconds: int, target_availability: float) -> float:
return (1.0 - target_availability) * total_seconds
def simulate_monthly_availability(seconds_in_month: int, budget_seconds: float) -> float:
# Mock: randomly consume a fraction of the error budget in real incidents
random.seed(42)
consumed = budget_seconds * random.uniform(0.3, 0.9)
available_seconds = seconds_in_month - consumed
return available_seconds / seconds_in_month * 100
if __name__ == "__main__":
month_seconds = 30 * 24 * 60 * 60 # 30-day month
target = 0.995 # 99.5% availability
budget = calculate_error_budget(month_seconds, target)
actual = simulate_monthly_availability(month_seconds, budget)
print(f"Error budget (seconds): {budget:.0f}")
print(f"Actual availability: {actual:.3f}%")
print(f"Budget consumed: {(1 - actual/100) / (1 - target) * 100:.1f}%")
Output
Error budget (seconds): 12960
Actual availability: 99.699%
Budget consumed: 60.2%
How it works
The calculate_error_budget function uses the standard formula (1 - target_availability) * total_seconds to convert an availability target into the maximum allowed downtime. simulate_monthly_availability then mocks real incidents by randomly consuming 30–90% of the budget with a fixed seed for reproducibility. The consumed seconds are subtracted from the month's total to compute actual availability as a percentage. The final print reports the budget, observed availability, and what fraction of the budget was used, which is how teams track SLO health.
Common mistakes
- Using minutes or hours instead of seconds for the budget calculation
- Forgetting to seed random for reproducible mocks
- Mixing percentage values (0.995 vs 99.5) in the formula
Variations
- Use a rolling 28-day window instead of a fixed month for a more realistic SLO period
- Build a simulation that models multiple independent incident types with different burn rates
Real-world use cases
- Automating SLO dashboards that alert when error budget consumption crosses a threshold.
- Running Monte Carlo simulations to forecast budget burn and prevent missed targets.
- Validating new release impact by comparing error budget consumption before and after deploys.
Sponsored
More from Observability & SRE
- Adding a Correlation ID to Log Context in Python medium
- Calculate Error Rate from Log Stream in Python easy
- Check if a Timestamp Falls in a Daily Maintenance Window in Python easy
- Export Metrics with OTLP Mock in Python medium
- Generate Mock CPU and Memory Metrics in Python easy
- Generate Prometheus Text Exposition Format in Python easy
Keep learning
Related tutorials and quizzes for this topic.