Observability & SRE
Structured logging, metrics, tracing, health checks, and SLO-friendly instrumentation.
How to Check Uptime with a Synthetic HTTP Mock in Python
Run a mock HTTP server locally and probe it with urllib to measure synthetic uptime and response times, perfect for testing monitoring logic without external dependencies.
import http.server
import threading
import time
import urllib.request
class MockHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/health":
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
…
How to Create a Mock OpenTelemetry Trace in Python
Create a mock OpenTelemetry trace in memory to test span creation, attributes, and parent-child relationships without exporting to a backend.
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
def create_mock_trace():
tracer_provider = TracerProvider()
span_exporter =…
How to Create a TCP DNS Mock Server in Python
This code creates a mock TCP DNS server that listens on a specified port, accepts probe connections, and returns a fixed DNS response header to simulate a live DNS service for testing and observability.
import socket
import threading
def handle_client(client_socket, address):
print(f"[+] Connection from {address}")
try:
while True:
data = client_socket.recv(1024)
if not data:
break
print(f"[*] Received {len(data)} bytes (TCP DNS probe)")
…
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 Implement an Error Budget Policy in Python
This code implements a mock error budget policy that decides whether to freeze deployments based on a simulated error rate and monthly freeze limits.
from datetime import datetime, timedelta
class ErrorBudgetPolicy:
FREEZE_WINDOW_HOURS = 24
MAX_FREEZES_PER_MONTH = 3
def __init__(self, budget_percentage=99.9):
self.budget_percentage = budget_percentage
self.freeze_count = 0
self.last_freeze_start = None
self.freeze_enabl…
Summary Quantile Mock Sketch in Python
Build a memory-efficient sketch that stores sorted bins of data points to answer approximate quantile queries like median without keeping all values in memory.
import random
import statistics
from collections import Counter
class SummaryQuantileSketch:
"""
A simple sketch that stores a fixed-size summary of data (min, max, deciles)
using sorted bins, then answers approximate quantile queries.
"""
def __init__(self, bins=10):
self.bins = bins
…
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.