Health Check Mark Unhealthy Stop Traffic Mock in Python

Simulates a health check with a 20% failure rate and automatically stops traffic when the service is unhealthy.

Easy Python 3.9+ Aug 9, 2026 Reliability & rate limiting 13 views 0 copies

Python code

32 lines
Python 3.9+
import time
import random

class HealthCheck:
    def __init__(self):
        self.is_healthy = True
        self.stop_traffic = False

    def check_health(self):
        # Simulate health check with random failure rate (20% chance unhealthy)
        self.is_healthy = random.random() > 0.2
        return self.is_healthy

    def manage_traffic(self):
        if not self.is_healthy:
            self.stop_traffic = True
            print("HEALTH CHECK FAILED - STOPPING TRAFFIC")
        else:
            self.stop_traffic = False
            print("Health check passed - traffic flowing normally")

    def run(self, checks=5):
        for i in range(1, checks + 1):
            print(f"\nCheck #{i}:")
            self.check_health()
            self.manage_traffic()
            time.sleep(0.5)

if __name__ == "__main__":
    random.seed(42)  # Deterministic output for testing
    health_monitor = HealthCheck()
    health_monitor.run(checks=3)

Output

stdout
Check #1:
Health check passed - traffic flowing normally

Check #2:
HEALTH CHECK FAILED - STOPPING TRAFFIC

Check #3:
Health check passed - traffic flowing normally

How it works

This mock replicates a service health monitoring pattern where traffic is automatically cut off when a health check fails. The class tracks health status and a separate traffic flag, updating both during each check cycle. random.seed(42) ensures deterministic output, making it easy to verify behavior in tests. The simple state machine mirrors production patterns where load balancers route around unhealthy instances.

Common mistakes

  • Forgetting to reset stop_traffic to False when health recovers
  • Not seeding random for reproducible test output
  • Checking health but not actually acting on the stop_traffic flag

Variations

  1. Use `unittest.mock` to patch the check method and force failures
  2. Add a max consecutive failures threshold before stopping traffic

Real-world use cases

  • Testing load balancer behavior before deployment to production environments.
  • Simulating service degradation in integration tests to verify circuit breaker logic.
  • Validating that traffic cut-off logic works correctly during chaos engineering drills.

Sponsored

Run this sample

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

Open editor

More from Reliability & rate limiting

Related tutorials and quizzes for this topic.