The user wants a system that monitors and alerts on Service Level Objective (SLO) violations. This is a complex request involving metrics collection, calculation, and alerting logic.
1. Deconstruct the Request:
- Goal: Monitor and alert on SLO violations.
- Core Components:
- Service Level Indicators (SLIs): What are we measuring? (Latency, Availability, Error Rate).
- Service Level Objectives (SLOs): What are the targets? (e.g., 99.9% availability).
- Monitoring System: Collects data (SLIs) and compares against SLOs.
- Alerting System: Notifies humans when violations are imminent or occurring (Error Budget burn rate).
- Implementation: Needs to be concrete (code/architecture), not just theory.
2. Determine the Architecture/Approach:
- Since I cannot build a physical infrastructure or a SaaS product, I need to provide a software framework or a reference implementation.
- Language: Python is great for this. It's readable and has good libraries.
- Metrics Storage: Prometheus is the industry standard for this. I should assume the metrics exist in Prometheus or simulate them.
- Concept: The "Error Budget" concept is crucial. Alerting on "burn rate" is the modern best practice (Google's SRE book).
3. Step-by-Step Implementation Plan:
-
Step 1: Define the Data Model.
- We need classes for SLOs, SLIs, and Error Budgets.
- An
SLO needs a target (e.g., 99.9%) and a window (e.g., 30 days).
-
Step 2: The Metric Collector (Simulated).
- I need a way to get "Good events" vs "Bad events" or "Total latency" vs "Satisfied latency".
- I'll create a mock client that fetches data from a time-series database (TSDB).
-
Step 3: The SLO Calculator.
- Logic:
SLI = Good / Total.
- Logic:
Error Budget = 1 - SLO.
- Logic:
Remaining Budget.
-
Step 4: The Alerting Engine (Burn Rate).
- Simply checking
if SLI < SLO is too slow.
- We need to alert on Burn Rate.
- Burn Rate: How fast are we consuming the error budget?
- Thresholds: If we burn the budget in 2 days, alert immediately (High severity). If we burn it in 30 days, alert low severity.
-
Step 5: The Notification System.
- Abstraction for sending alerts (Email, PagerDuty, Slack).
-
Step 6: Putting it together (Main loop).
- A scheduler that runs these checks periodically.
4. Drafting the Code (Mental or scratchpad):
-
Python classes:
Service: name, slos.
SLO: name, target_percentage, window_days.
AlertManager: check_burn_rate.
-
Burn Rate Math:
- SLO Target: 99.9% (Error budget 0.1%).
- If current error rate is 1%, that's 10x the budget (Burn rate = 10).
- Time to exhaustion = (1 - CurrentSLI) / (Burn Rate logic... wait, let's refine).
- Standard approach: Calculate consumption over a short window (e.g., 1 hour) vs the full window (e.g., 30 days).
5. Refining the Solution for the User:
The user needs something actionable. A raw Python script is good, but a conceptual architecture + a concrete Python implementation is best.
- Architecture: Explain the flow (App -> Metrics -> Burn Rate Calculator -> Alerter).
- The "Burn Rate" Alerting Strategy: Explain why this is the chosen method (avoids alert fatigue, catches issues fast). I will use the "Multi-window Burn Rate" approach concept, but simplify it to a "Single Window" for code clarity unless I want to make it robust. Let's stick to a configurable Burn Rate threshold for simplicity in code.
6. Writing the Code (Iterative Refinement):
- Imports:
dataclasses, datetime, random (for simulation).
- Class
ServiceSLO: Stores target (e.g., 0.999).
- Function
calculate_sli: Simulates fetching metrics. Returns good_count, total_count.
- Function
calculate_burn_rate:
error_rate = (total - good) / total
max_error_rate = 1 - target
burn_rate = error_rate / max_error_rate (If > 1, we are failing the SLO).
- Alert Logic:
- If
burn_rate > threshold (e.g., 2x or 10x), trigger alert.
7. Adding a CLI/Dashboard Simulation:
- Create a loop that simulates traffic.
- Sometimes inject errors.
- Print the status to console.
8. Review against constraints:
- Does it monitor? Yes.
- Does it alert? Yes.
- Does it handle violations? Yes (via Burn Rate).
9. Polishing the Output:
- Add comments explaining the math.
- Use type hinting.
- Provide a
requirements.txt equivalent (standard library mostly).
- Explain how to extend this (Prometheus integration).
Self-Correction during drafting:
- Initial thought: Just compare current SLI to Target.
- Correction: That's useless. If the SLO is annual, you won't know you failed until the year is over. I must use Error Budgets and Burn Rates.
- Refinement on Burn Rate: Standard Google SRE approach uses multiple windows (short and long) to prevent flapping. I will implement a simplified version of this: Check the last hour vs the budget allowed for that hour.
10. Final Structure:
- Conceptual Overview: What are SLIs, SLOs, Error Budgets, and Burn Rates?
- Architecture Diagram (Text): How pieces fit together.
- Python Implementation: A complete, runnable simulation.
- Production Considerations: Prometheus, Grafana, Alertmanager.
Let's write the Python code.
MetricClient: Mock fetching data.
SLOMonitor: The core logic.
Alerter: Handles output.
- Main loop to simulate time passing.
(Self-Correction on Python Code): Ensure the math is correct.
If SLO is 99.9%:
Allowed error rate = 0.1% (0.001).
If actual error rate is 0.5% (0.005).
Burn Rate = 0.005 / 0.001 = 5.
We are burning budget 5x faster than allowed.
Time to exhaustion = (30 days * 1) / 5 = 6 days.
Okay, the logic holds up. Proceeding to generate response.
Designing an SLO (Service Level Objective) monitoring system requires moving beyond simple "is it up/down" checks to a system that understands Error Budgets and Burn Rates.
Here is a comprehensive guide and a complete Python implementation of an SLO Monitoring Engine that tracks metrics, calculates burn rates, and alerts when your error budget is draining too fast.
1. The Architecture
A robust SLO system relies on four pillars:
- SLI (Service Level Indicator): The raw metric (e.g., HTTP 200 vs 500 counts).
- SLO (Service Level Objective): The target (e.g., 99.9% availability).
- Error Budget: The inverse of the SLO. If your SLO is 99.9%, you have 0.1% "budget" to spend on errors.
- Burn Rate: How fast you are consuming that budget compared to the ideal pace.
2. The "Burn Rate" Alerting Strategy
We will implement the Burn Rate Method (popularized by Google). This allows you to alert based on how fast you are spending your error budget, ensuring you catch incidents quickly without being noisy.
- Ideal Burn Rate: 1.0 (You are consuming the budget exactly evenly over the time window).
- Alert Condition: If the burn rate is > 2.0 (or higher), trigger an alert.
3. Python Implementation
This system simulates a time-series database (like Prometheus) and an alerting evaluator. It requires no external libraries to run (standard library only).
System Components
MetricStore: Simulates fetching data (Good vs Bad events).
SLOConfig: Defines the targets.
SLOMonitor: Calculates the Burn Rate and determines if an alert should fire.
import time
import random
import math
from dataclasses import dataclass
from typing import List, Dict, Tuple
# ==========================================
# 1. Configuration & Data Structures
# ==========================================
@dataclass
class SLOConfig:
name: str
target_percentage: float # e.g., 99.9
window_days: int # The rolling window (e.g., 30 days)
@property
def target_fraction(self) -> float:
return self.target_percentage / 100.0
@dataclass
class AlertRule:
burn_rate_threshold: float # How fast we are burning budget
short_window_minutes: int # For immediate detection
long_window_minutes: int # For sustained detection
# ==========================================
# 2. Mock Metric Source (The "Probe")
# ==========================================
class MetricStore:
"""
Simulates a time-series database (like Prometheus).
In reality, this would query 'rate(http_requests_total[5m])'
"""
def __init__(self):
# history stores tuples of (timestamp, is_success)
self.history: List[Tuple[float, bool]] = []
def inject_traffic(self, success_rate: float):
"""Simulate incoming traffic."""
current_time = time.time()
# Simulate 100 requests per injection
for _ in range(100):
is_success = random.random() < success_rate
self.history.append((current_time, is_success))
# Clean up old data beyond 30 days to keep memory low
cutoff = current_time - (30 * 24 * 3600)
self.history = [h for h in self.history if h[0] > cutoff]
def get_sli_counts(self, window_seconds: float) -> Tuple[int, int]:
"""
Returns (good_events, total_events) within the specified window.
"""
now = time.time()
cutoff = now - window_seconds
relevant = [h for h in self.history if h[0] > cutoff]
total = len(relevant)
good = sum(1 for r in relevant if r[1])
return good, total
# ==========================================
# 3. The Monitoring Engine
# ==========================================
class SLOMonitor:
def __init__(self, config: SLOConfig, metrics: MetricStore):
self.config = config
self.metrics = metrics
self.alert_state = {} # Tracks active alerts to prevent flapping
def calculate_burn_rate(self, window_seconds: float) -> float:
"""
Core logic:
Burn Rate = (Actual Error Rate) / (Allowed Error Rate)
"""
good, total = self.metrics.get_sli_counts(window_seconds)
if total == 0:
return 0.0
# 1. Calculate Actual Error Rate
actual_error_rate = (total - good) / total
# 2. Calculate Allowed Error Rate (based on SLO target)
# If SLO is 99.9%, allowed error is 0.1% (0.001)
allowed_error_rate = 1.0 - self.config.target_fraction
if allowed_error_rate == 0:
return float('inf')
# 3. Calculate Burn Rate
# A rate of 1.0 means we are using budget exactly as planned.
# A rate of 2.0 means we are using budget 2x faster than allowed.
burn_rate = actual_error_rate / allowed_error_rate
return burn_rate
def check_violations(self) -> Dict[str, str]:
"""
Checks alerting conditions based on Burn Rate.
We use a simplified Multi-Window Burn Rate check:
We check if the Burn Rate is high over a LONG period (sustained issue).
"""
alerts_fired = {}
# Define a rule: Alert if burning > 2x speed over the last hour
# In production, you usually check multiple windows (e.g., 1h and 5m)
# to ensure it's both a significant and immediate issue.
long_window_sec = 3600 # 1 hour
burn_rate = self.calculate_burn_rate(long_window_sec)
# Threshold: If we are burning budget 2x faster than allowed
THRESHOLD = 2.0
if burn_rate > THRESHOLD:
status = "CRITICAL"
msg = (f"SLO Violation: '{self.config.name}' "
f"Burn Rate is {burn_rate:.2f} (Threshold {THRESHOLD}). "
f"You are consuming error budget 2x faster than allowed.")
alerts_fired[status] = msg
else:
status = "OK"
msg = f"SLO Healthy. Burn Rate: {burn_rate:.2f}"
return {"status": status, "message": msg, "burn_rate": burn_rate}
# ==========================================
# 4. Execution / Simulation
# ==========================================
def main():
# 1. Setup SLO: 99.9% Availability over 30 days
slo_config = SLOConfig(name="API Availability", target_percentage=99.9, window_days=30)
metrics = MetricStore()
monitor = SLOMonitor(slo_config, metrics)
print(f"--- Starting Monitor for: {slo_config.name} ---")
print(f"Target: {slo_config.target_percentage}%")
# Simulation Loop
for minute in range(1, 10):
print(f"\n--- Minute {minute} ---")
# Scenario: Simulate traffic
# For the first 3 minutes, everything is fine
# At minute 4, we introduce a failure (98% success rate)
if minute == 4:
print("!!! SIMULATING INCIDENT: Success rate dropped to 98% !!!")
success_rate = 0.98
elif minute > 4 and minute < 8:
# Sustained failure
success_rate = 0.98
else:
# Recovery or Healthy
success_rate = 1.0
if minute >= 8:
print("!!! INCIDENT RESOLVED !!!")
# Inject Metrics
metrics.inject_traffic(success_rate)
# Check Status
result = monitor.check_violations()
print(f"Status: {result['status']}")
print(f"Info: {result['message']}")
if result['status'] == 'CRITICAL':
print(f"⚠️ ACTION REQUIRED: Page the on-call engineer!")
time.sleep(1) # Pause for dramatic effect
if __name__ == "__main__":
main()
4. How to Interpret the Output
When you run this code:
- Minutes 1-3 (Healthy): The Burn Rate will be
0.00. The system reports OK.
- Minute 4 (Incident Start): Success rate drops to 98%.
- Even though 98% sounds high, for an SLO of 99.9%, this is a massive failure.
- Math: Actual Error is 2%. Allowed Error is 0.1%.
- Burn Rate = 0.02 / 0.001 = 20.0.
- Alert Triggered: The system sees Burn Rate (20.0) > Threshold (2.0). It fires a CRITICAL alert.
- Minutes 8+ (Recovery): Traffic returns to 100%. The Burn Rate calculation drops back to 0. The alert resolves.
5. Production Considerations
If you were to build this for a real company (Scale), you should make the following architectural changes:
- Storage: Do not store metrics in a Python list. Use Prometheus, Thanos, or Cortex. They handle the
rate() calculations natively.
- Alerting Logic:
- The code above calculates the burn rate over a single window (1 hour).
- Best Practice: Use Multiple Windows (e.g., "Burn rate is high over 1 hour" AND "Burn rate is high over 5 minutes"). This prevents false positives from momentary blips and false negatives from slow burns.
- Notification: Integrate with PagerDuty or Opsgenie for the "Critical" alerts, and Slack for the "Warning" alerts.
- Metric Instrumentation: Use OpenTelemetry to generate the "Good" (HTTP 200) and "Bad" (HTTP 500) counts from your application automatically.
6. The "Burn Rate" Formula Recap
If you want to implement this in Grafana/PromQL directly, the query looks like this:
(
sum(rate(http_requests_total{code=~"5.."}[1h]))
/
sum(rate(http_requests_total[1h]))
)
/
(1 - 0.999)
> 2
- Top part: Actual Error Rate (calculated over 1 hour).
- Bottom part: Target Error Rate (1 - 99.9%).
- Result: If the ratio is greater than 2, fire the alert.