Reliability & rate limiting
Retries, exponential backoff, circuit breakers, token buckets, and idempotent handlers.
Build a Rate Limiter Decorator in Python
This code defines a reusable rate limiter decorator that caps function calls within a sliding time window using a deque and monotonic time.
import time
from collections import deque
def rate_limiter(max_calls: int, period: float):
calls = deque()
def decorator(func):
def wrapper(*args, **kwargs):
now = time.monotonic()
while calls and now - calls[0] >= period:
calls.popleft()
if len(ca…
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.
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_heal…
How to Implement a Temporary Block in Python
Build a reusable PenaltyBox class that temporarily blocks access after a failure and reports remaining lockout time.
class PenaltyBox:
def __init__(self, block_seconds: int = 30):
self.block_seconds = block_seconds
self._blocked_until = 0.0
self._attempts = 0
def try_access(self, current_time: float) -> bool:
if self._blocked_until and current_time < self._blocked_until:
return Fa…
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 Slow Startup Probe in Python
Simulate slow service initialization with a configurable mock delay to test readiness probes.
import time
from dataclasses import dataclass, field
@dataclass
class StartupProbe:
name: str
min_wait_sec: float = 0.5
max_wait_sec: float = 2.0
_ready: bool = field(default=False, init=False, repr=False)
def initialize(self) -> None:
"""Simulate slow startup with a fixed mock delay."""…
How to Stop Receiving Requests Until Ready in Python
A mock server that refuses requests until a readiness gate is passed, simulating fail-stop behavior for production reliability.
import random
import time
class MockServer:
def __init__(self):
self.ready = False
self.requests_received = 0
def readiness_check(self):
"""Simulates a readiness probe. Returns True only when ready."""
if not self.ready:
return False
return True
def r…
Implementing Fallback with Cached Stale Data in Python
This code demonstrates a resilient data-fetching pattern that caches successful responses, falls back to cached data when the external API fails, and returns stale data as a last-resort fallback.
import random
import time
# Simulated cache dictionary: key -> (value, timestamp)
_cache = {}
_CACHE_TTL = 3 # seconds
# Mock data source (simulates an unreliable external API)
def fetch_mock_data(key):
failure = random.random() < 0.4 # 40% chance of failure
if failure:
raise ConnectionError("Mock …
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.