Mock Health Endpoint Liveness Check in Python

Simulate a liveness endpoint that reports service health with a configurable failure rate and uptime.

Easy Python 3.9+ Aug 9, 2026 Observability & SRE 16 views 0 copies

Python code

19 lines
Python 3.9+
import 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

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

  1. Use `datetime.now(timezone.utc).isoformat()` for a timezone-aware timestamp.
  2. 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

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.