Observability & SRE
Structured logging, metrics, tracing, health checks, and SLO-friendly instrumentation.
How to Build a Burn Rate Alert with Multiple Time Windows in Python
Track token consumption and trigger alerts when the burn rate exceeds a threshold across multiple time windows using deque and time-based sliding windows.
import time
from collections import deque
class BurnRateAlert:
def __init__(self, windows_seconds=(60, 300, 900), threshold_rate=0.8):
self.windows = {w: deque() for w in windows_seconds}
self.threshold_rate = threshold_rate
self.previous_tokens = None
def record_sample(self, current_…
How to Compute SRE Metrics Like Error Rate and Availability in Python
Tracks log events in a sliding time window and calculates error rate per second and availability percentage using an easy-to-follow class.
from collections import deque
from datetime import datetime, timedelta
from typing import Dict, Deque
class LogMetrics:
"""Simple observability helper to track log events and calculate SRE metrics."""
def __init__(self, window_seconds: int = 60):
self.window_seconds = window_seconds
self.eve…
How to Group Alerts by Time Window in Python
Group alert occurrences that fall within a sliding time window per alert key, reducing noise and summarizing bursts into single events.
from collections import defaultdict
from datetime import datetime, timedelta
def group_alerts(alerts, window_minutes=10):
"""Group alerts that occur within the same time window."""
alerts_by_key = defaultdict(list)
for alert in alerts:
key = alert["key"]
timestamp = alert["timestamp"]…
How to mock SLI availability success ratio in Python
Simulate request outcomes with deterministic randomness and compute the SLI availability success ratio to check if a target is met.
import random
from collections import defaultdict
def mock_availability(num_requests=1000, target_ratio=0.995):
"""
Simulate request outcomes and compute the SLI availability success ratio.
Args:
num_requests: Total number of requests to simulate
target_ratio: Target availability rati…
Browse by section
Each section groups closely related Python snippets.
Observability & SRE — Python code examples
What you will find here
This page collects observability & sre snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.