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.

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

Python code

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

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

  1. Use `random.random() < failure_rate` with failure_rate passed as a function argument for configurable fault injection
  2. 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

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.