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.
Python code
35 linesimport 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 ratio (e.g., 0.995 = 99.5%)
Returns:
Tuple of (successful_requests, total_requests, availability_ratio)
"""
random.seed(42) # Deterministic for reproducibility
outcomes = defaultdict(int)
for _ in range(num_requests):
# Simulate a request: succeed with probability based on target
if random.random() < target_ratio:
outcomes["success"] += 1
else:
outcomes["failure"] += 1
successful = outcomes["success"]
total = num_requests
ratio = successful / total
return successful, total, ratio
if __name__ == "__main__":
success_count, total_requests, ratio = mock_availability()
print(f"Successful requests: {success_count}/{total_requests}")
print(f"Availability ratio: {ratio:.4f} ({ratio*100:.2f}%)")
print(f"Target ratio met: {ratio >= 0.995}")
Output
Successful requests: 996/1000
Availability ratio: 0.9960 (99.60%)
Target ratio met: True
How it works
The random.seed(42) makes the simulation reproducible, so the same output appears on every run. Each request draws a uniform random number between 0 and 1; if it is below the target_ratio, the request is counted as success. The defaultdict keeps tallies without manual initialization. The final availability ratio is successful / total, and comparing it to the target shows whether the SLI goal was met. This pattern is useful for prototyping SLO dashboards before real telemetry exists.
Common mistakes
- Forgetting to seed the random generator, making output non-reproducible.
- Dividing by zero if `num_requests` is set to 0.
- Using `random.random()` vs `random.randint`, which changes the outcome distribution.
- Comparing the ratio with `>` instead of `>=` to include exact target hits.
Variations
- Use `statistics.fmean` on a generator expression to compute the ratio without storing outcomes.
- Replace the loop with a binomial sample: `sum(random.random() < target_ratio for _ in range(num_requests))`.
Real-world use cases
- Prototyping an SLO dashboard before production telemetry data is available.
- Testing alerting thresholds by generating synthetic traffic patterns in a staging environment.
- Benchmarking the impact of error-rate changes on availability without touching real services.
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.