How to Build a Synthetic Monitor Mock in Python

Simulates a synthetic monitoring system in Python that collects latency samples, averages them, and reports service status as UP or DEGRADED.

Easy Python 3.9+ Aug 9, 2026 Production deployment patterns 13 views 0 copies

Python code

37 lines
Python 3.9+
import random
import time
from dataclasses import dataclass, field
from statistics import mean


@dataclass
class SyntheticMonitor:
    service: str
    endpoint: str
    latency_ms: list[float] = field(default_factory=list)

    def check(self) -> float:
        latency = random.uniform(50.0, 250.0)
        self.latency_ms.append(latency)
        return latency

    def report(self) -> dict:
        return {
            "service": self.service,
            "endpoint": self.endpoint,
            "checks": len(self.latency_ms),
            "avg_latency_ms": round(mean(self.latency_ms), 2),
            "max_latency_ms": round(max(self.latency_ms), 2),
            "status": "UP" if mean(self.latency_ms) < 200 else "DEGRADED",
        }


if __name__ == "__main__":
    random.seed(42)
    monitor = SyntheticMonitor("api", "/v1/products")

    for _ in range(5):
        monitor.check()
        time.sleep(0.01)

    print(monitor.report())

Output

stdout
{'service': 'api', 'endpoint': '/v1/products', 'checks': 5, 'avg_latency_ms': 147.06, 'max_latency_ms': 235.21, 'status': 'UP'}

How it works

The SyntheticMonitor dataclass stores latency samples per check, modeling a lightweight production monitor. The check() method simulates real network latency with random.uniform. The report() method computes the mean and max latency, then derives a simple status threshold. Seeding the random generator with random.seed(42) makes output reproducible for testing.

Common mistakes

  • Not seeding random for deterministic tests, making CI flaky.
  • Ignoring empty latency list before calling mean() or max() causing errors.
  • Sleeping too long in the loop, slowing down local testing.

Variations

  1. Use a real HTTP request like `requests.get(endpoint, timeout=5)` instead of random values.
  2. Add alerting logic that triggers a callback when status flips to DEGRADED.

Real-world use cases

  • Running smoke tests against critical endpoints after a deployment or rollout.
  • Generating synthetic traffic to validate load balancer health checks in staging.
  • Feeding latency data into a structured logger for production observability pipelines.

Sponsored

Run this sample

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

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.