Reliability & rate limiting
Retries, exponential backoff, circuit breakers, token buckets, and idempotent handlers.
Chaos Inject Random Failures in Python
Simulate random failures in a Python function to test error handling and resilience, using random thresholds and controllable success rates.
import random
def unreliable_function(success_rate: float = 0.7) -> str:
"""Simulate a function that sometimes fails."""
if random.random() > success_rate:
raise ConnectionError("Simulated network failure")
return "Operation completed successfully"
if __name__ == "__main__":
random.seed(42)…
How to Inject Random Latency for Chaos Testing in Python
Mock unreliable services by wrapping functions with a decorator that adds random network-like delays before execution.
import random
import time
from functools import wraps
def inject_latency(func):
@wraps(func)
def wrapper(*args, **kwargs):
latency = random.uniform(0.1, 0.5)
print(f"Injecting {latency:.3f}s latency...")
time.sleep(latency)
return func(*args, **kwargs)
return wrapper
@inje…
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.
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):
…
How to Mock a Timeout per HTTP Request in Python
Simulate a per-request HTTP timeout using unittest.mock to test timeout handling without network access.
import time
from unittest.mock import Mock, patch
# Simulate an HTTP client that might time out
def fetch_data(url, timeout=5):
time.sleep(0.5) # Simulate network delay
return f"Response from {url}"
# Mock to test timeout behavior without real network
def test_timeout():
mock_response = Mock(side_effect…
Browse by section
Each section groups closely related Python snippets.
Reliability & rate limiting — Python code examples
What you will find here
This page collects reliability & rate limiting snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.