Reliability & rate limiting
Retries, exponential backoff, circuit breakers, token buckets, and idempotent handlers.
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…
How to mock a fallback return value in Python
Test a function that returns a default value on failure by mocking requests.get and its side effects.
from unittest.mock import Mock, patch
import requests
def fetch_data(url, default=None):
try:
response = requests.get(url)
response.raise_for_status()
return response.json()
except (requests.RequestException, ValueError):
return default
with patch("requests.get") as mock_get:
…
How to retry idempotent operations with a mock in Python
Wrap a flaky idempotent operation in a retry loop with exponential backoff, and use unittest.mock to deterministically test the str's behavior.
import random
import time
from unittest.mock import Mock
def idempotent_operation(value):
"""Simulate an idempotent operation that sometimes fails."""
if random.random() < 0.6: # 60% failure rate
raise ConnectionError("Temporary failure")
return value * 2
def retry_with_backoff(operation, max_…
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.