Mock Health Endpoint Liveness Check in Python
Simulate a liveness endpoint that reports service health with a configurable failure rate and uptime.
Python code
19 linesimport time
import random
def liveness_check(service_name: str, failure_rate: float = 0.1) -> dict:
"""Mock health check that returns liveness status with a configurable failure rate."""
healthy = random.random() > failure_rate
response = {
"service": service_name,
"status": "alive" if healthy else "dead",
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"uptime_seconds": random.randint(100, 10000),
}
return response
if __name__ == "__main__":
print(liveness_check("api-gateway", failure_rate=0.0))
print(liveness_check("auth-service", failure_rate=0.5))
Output
{'service': 'api-gateway', 'status': 'alive', 'timestamp': '2024-05-12T10:30:45Z', 'uptime_seconds': 4321}
{'service': 'auth-service', 'status': 'alive' or 'dead', 'timestamp': '2024-05-12T10:30:45Z', 'uptime_seconds': 6789}
How it works
This code uses the random module to decide service health based on a failure rate. The function returns a dictionary with service name, status, timestamp, and uptime. The time module generates a UTC timestamp in ISO format. By setting failure_rate to 0 in the first call, the service is always alive; 0.5 makes it equally likely to be alive or dead.
Common mistakes
- Forgetting to set the failure rate to 0 to force a healthy response
- Assuming the timestamp is local time instead of UTC
- Not including a unique service name in the response
Variations
- Use `datetime.now(timezone.utc).isoformat()` for a timezone-aware timestamp.
- Add a `latency_ms` field to simulate response time for load testing.
Real-world use cases
- Testing client-side retry logic against a mock liveness endpoint during development.
- Simulating flaky services in integration tests to verify circuit breaker behavior.
- Generating synthetic metrics for dashboards when real services are offline.
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.