How to Mock Database Query Duration in Python
Simulate realistic database query durations with random jitter for testing dashboards, alerts, and SLO calculations.
Python code
21 linesimport random
import time
def mock_query_duration(db_name, avg_ms, jitter_ms=5, runs=3):
"""Simulate database query durations with realistic variation."""
durations = []
for _ in range(runs):
# Base duration plus random jitter (can be negative)
duration = avg_ms + random.uniform(-jitter_ms, jitter_ms)
duration = max(0.1, duration) # Never below 0.1 ms
durations.append(round(duration, 2))
time.sleep(0.05) # Small delay between mock queries
return {"database": db_name, "query_ms": durations, "avg_ms": round(sum(durations) / runs, 2)}
if __name__ == "__main__":
random.seed(42)
result = mock_query_duration("users_db", avg_ms=15, jitter_ms=4, runs=5)
print(result)
Output
{'database': 'users_db', 'query_ms': [17.27, 14.12, 15.9, 12.63, 14.06], 'avg_ms': 14.8}
How it works
The function takes an average query time and adds random jitter to mimic real-world variation. random.uniform produces a float between -jitter and +jitter, which is added to the base. max(0.1, duration) prevents negative or zero values. Rounding to two decimals keeps output clean. The return dictionary includes individual durations and the computed average for easy metrics tracking.
Common mistakes
- Forgetting to seed the random generator, causing non-reproducible results.
- Using `random.randint` instead of `uniform` to get integer-only jitter, losing precision.
- Not handling the case where jitter exceeds avg_ms, creating negative durations.
Variations
- Use `time.perf_counter()` to measure real query timing and then apply jitter for mocked latency.
- Return a generator that yields one duration at a time for streaming observability data.
Real-world use cases
- Load testing dashboards by feeding simulated query latencies into a metrics collection pipeline.
- Validating alert thresholds and SLO burn rate calculations with consistent historical variability.
- Developing and debugging tracing or monitoring tools without needing access to a live database.
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.