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.
Python code
32 linesimport 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
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
- Use `unittest.mock` to patch the check method and force failures
- 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
More from Reliability & rate limiting
- At Least Once with Idempotent Consumer in Python medium
- Build a Rate Limiter Decorator in Python easy
- Build a queue-based admission control system in Python easy
- Chaos Inject Random Failures in Python easy
- Circuit breaker failure threshold count in Python medium
- Exactly Once Processing Dedupe Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.