How to Mock Database Query Duration in Python

Simulate realistic database query durations with random jitter for testing dashboards, alerts, and SLO calculations.

Easy Python 3.6+ Aug 9, 2026 Observability & SRE 14 views 0 copies

Python code

21 lines
Python 3.6+
import 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

stdout
{'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

  1. Use `time.perf_counter()` to measure real query timing and then apply jitter for mocked latency.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Observability & SRE

Related tutorials and quizzes for this topic.