Reference library

Reliability & rate limiting

Retries, exponential backoff, circuit breakers, token buckets, and idempotent handlers.

7 matches
Reliability & rate limiting medium

Circuit breaker failure threshold count in Python

Track consecutive or time-windowed failures with a deque to open a circuit breaker and auto-recover to half-open after a cooldown.

circuit-breaker resilience deque
Python
from collections import deque
from time import time, sleep


class CircuitBreaker:
    def __init__(self, failure_threshold: int = 5, recovery_time: float = 10.0):
        self.failure_threshold = failure_threshold
        self.recovery_time = recovery_time
        self.failures: deque[float] = deque()
        self.st…
16 0 Open
Reliability & rate limiting medium

How to Implement Hedged Requests in Python

This code demonstrates a hedged request pattern using threading, which sends duplicate calls and returns the first result that arrives within a timeout.

hedged-requests threading timeout
Python
import time
from unittest.mock import Mock

def hedged_request(call, timeout=0.05):
    """Execute two duplicate calls, return first result within timeout."""
    result_container = {}

    def run_and_store():
        result_container['result'] = call()
        result_container['done'] = True

    # Simulate slow cal…
16 0 Open
Reliability & rate limiting medium

How to Implement a Sliding Window Log Rate Limiter in Python

Implements a sliding window log rate limiter in Python using a deque of timestamps to enforce a maximum request count within a rolling time window.

rate-limiting sliding-window deque
Python
from collections import deque
from datetime import datetime, timedelta
from time import sleep


class SlidingWindowLog:
    def __init__(self, window_seconds: int, max_requests: int):
        self.window_seconds = window_seconds
        self.max_requests = max_requests
        self.timestamps = deque()

    def allow_…
15 0 Open
Reliability & rate limiting medium

How to Implement a Token Bucket Rate Limiter per Client IP in Python

Implements a simple sliding-window rate limiter using a dictionary of timestamp lists per client IP to limit requests per window.

rate-limiting sliding-window ip
Python
from time import time
from collections import defaultdict

class RateLimiter:
    def __init__(self, max_requests: int, window_seconds: int):
        self.max_requests = max_requests
        self.window_seconds = window_seconds
        self.clients = defaultdict(list)

    def allow(self, ip: str) -> bool:
        now…
13 0 Open
Reliability & rate limiting medium

How to Mock a Circuit Breaker Reset Timeout in Python

This code implements a simple circuit breaker with a reset timeout test, simulating a flaky service to show half-open state transitions.

circuit-breaker reliability mock-testing
Python
import time
import random


class CircuitBreaker:
    def __init__(self, failure_threshold=3, reset_timeout=5):
        self.failure_threshold = failure_threshold
        self.reset_timeout = reset_timeout
        self.failure_count = 0
        self.last_failure_time = None
        self.state = "CLOSED"  # CLOSED (nor…
15 0 Open
Reliability & rate limiting medium

How to implement a rate-limited shared counter in Python

Implements a thread-safe global counter that allows a maximum number of increments per second using a lock and time-based refill.

rate-limiting threading global-counter
Python
import threading
import time
import random

counter = 0
lock = threading.Lock()
MAX_CALLS_PER_SECOND = 3
last_refill = time.time()

def rate_limited_increment():
    global counter, last_refill
    with lock:
        now = time.time()
        if now - last_refill >= 1.0:
            last_refill = now
            count…
12 0 Open
Reliability & rate limiting medium

How to implement rate limiting per API key in Python

A simple sliding-window rate limiter that tracks request timestamps per API key and rejects requests exceeding the configured limit.

rate-limiting api time-window
Python
import time

API_RATE_LIMITS = {"api_key_1": 5, "api_key_2": 3}  # max requests per window
WINDOW_SECONDS = 10

class RateLimiter:
    def __init__(self, limits, window):
        self.limits = limits
        self.window = window
        self.requests = {key: [] for key in limits}

    def allow(self, api_key):
       …
13 0 Open

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.