Reliability & rate limiting
Retries, exponential backoff, circuit breakers, token buckets, and idempotent handlers.
How to implement rate limiting in Python
A beginner-friendly Python rate limiter that throttles API calls and retries parsing tasks with exponential backoff.
import time
import random
class RateLimiter:
def __init__(self, max_calls, per_seconds):
self.max_calls = max_calls
self.per_seconds = per_seconds
self.timestamps = []
def allow(self):
now = time.time()
self.timestamps = [t for t in self.timestamps if now - t < sel…
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:
…
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 …
Rate Limit per User ID in Python with a Dict Mock
Implements a simple sliding window rate limiter using a defaultdict of timestamps per user ID, blocking requests that exceed a max count within a time window.
import time
from collections import defaultdict
class RateLimiter:
def __init__(self, max_requests, window_seconds):
self.max_requests = max_requests
self.window_seconds = window_seconds
self.user_timestamps = defaultdict(list)
def allow_request(self, user_id):
now = time.tim…
Rate Limiting in Python with a Sliding Window
A beginner-friendly dataclass-based sliding window rate limiter that controls how many calls are allowed per time window.
import time
from dataclasses import dataclass
@dataclass
class RateLimiter:
max_calls: int
window_seconds: float = 1.0
def __post_init__(self):
self.calls = []
self._start = time.monotonic()
def _update(self, now):
self.calls = [t for t in self.calls if now - t < self.window…
Rate Limiting with Queue Rejection in Python
Simulates a load shed pattern that rejects tasks when a queue fills up.
from collections import deque
import time
class RateLimiter:
def __init__(self, max_queue_size=3):
self.queue = deque()
self.max_queue_size = max_queue_size
self.rejected_count = 0
def submit(self, task_name):
if len(self.queue) >= self.max_queue_size:
self.reject…
Rate Limiting with a Simple Python RateLimiter Class
A beginner-friendly Python rate limiter that tracks call timestamps and enforces a maximum number of calls within a rolling time window, with a helper to validate positive integers.
import time
class RateLimiter:
def __init__(self, max_calls, period_seconds):
self.max_calls = max_calls
self.period_seconds = period_seconds
self.calls = []
def is_allowed(self):
now = time.time()
while self.calls and now - self.calls[0] >= self.period_seconds:
…
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.