How to Mock Fault Injection Percentage in Python
Simulate a service with a 30% failure rate using random.random to test error handling and retries.
Python code
21 linesimport random
class Service:
def call(self):
if random.random() < 0.3: # 30% failure rate
raise ConnectionError("Simulated network fault")
return "ok"
def main():
svc = Service()
random.seed(42) # deterministic for demonstration
results = []
for _ in range(10):
try:
results.append(svc.call())
except ConnectionError:
results.append("error")
print(results)
if __name__ == "__main__":
main()
Output
['error', 'ok', 'ok', 'ok', 'ok', 'ok', 'error', 'ok', 'ok', 'ok']
How it works
The random.random() call returns a float between 0 and 1, and comparing it to 0.3 gives roughly a 30% chance of raising ConnectionError. Seeding with random.seed(42) makes the failure pattern reproducible for testing. Each iteration calls svc.call() inside a try/except to capture errors as strings, simulating how a caller would handle partial failures. This pattern is useful for testing retry logic and circuit breakers without real network dependencies.
Common mistakes
- Forgetting to seed random for reproducible tests, making failures nondeterministic
- Using `random.randint` instead of `random.random` for probability-based faults
- Not wrapping calls in try/except, causing the script to crash on the first simulated failure
- Hardcoding the percentage in multiple places instead of as a configurable parameter
Variations
- Use `random.random() < failure_rate` with failure_rate passed as a function argument for configurable fault injection
- Use a decorator or wrapper that injects faults based on a counter for a percentage of total calls
Real-world use cases
- Testing retry and backoff logic in a microservice client to ensure it recovers gracefully from transient network errors.
- Validating circuit breaker behavior by injecting faults at a controlled rate in a load test environment.
- Verifying monitoring and alerting systems trigger correctly when a service experiences a predefined failure percentage.
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.