Reliability & rate limiting
Retries, exponential backoff, circuit breakers, token buckets, and idempotent handlers.
Fixed Window Counter Rate Limiting in Python
A simple fixed window counter rate limiter that allows a maximum number of requests per 60-second window, with a mock time simulation.
from collections import deque
from time import time
class FixedWindowCounter:
def __init__(self, max_requests):
self.max_requests = max_requests
self.window_start = int(time())
self.window_count = 0
def allow_request(self):
current_time = int(time())
if current_time >=…
How to Build a Rate Limiter in Python
A beginner-friendly token bucket rate limiter with retry logic for handling API rate limits in Python.
import time
import random
class RateLimiter:
"""Simple token bucket rate limiter for beginners."""
def __init__(self, max_tokens=5, refill_rate=1.0):
self.max_tokens = max_tokens
self.tokens = max_tokens
self.refill_rate = refill_rate # tokens per second
self.last_refill …
How to Mock Daily and Monthly Quota Counters in Python
Track daily and monthly API call usage with automatic resets, quota checks, and limits using a Python class.
import random
from datetime import datetime, timedelta
class QuotaCounter:
def __init__(self, daily_limit=1000, monthly_limit=20000):
self.daily_limit = daily_limit
self.monthly_limit = monthly_limit
self.daily_usage = 0
self.monthly_usage = 0
self.current_day = datetime.n…
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…
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 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.