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.
Python code
37 linesimport 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
{'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
- Use a real HTTP request like `requests.get(endpoint, timeout=5)` instead of random values.
- 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
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
Keep learning
Related tutorials and quizzes for this topic.