Reference library

Reliability & rate limiting

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

26 matches
Reliability & rate limiting medium

At Least Once with Idempotent Consumer in Python

Implements a thread-safe idempotent consumer that processes each unique message exactly once, even when a producer sends duplicates under an at-least-once delivery model.

idempotency at-least-once threading
Python
import threading
import time
import uuid
from collections import Counter


class IdempotentConsumer:
    def __init__(self):
        self.processed = set()
        self._lock = threading.Lock()

    def consume(self, message_id, payload):
        with self._lock:
            if message_id in self.processed:
          …
15 0 Open
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

GCRA generic cell rate algorithm in Python

Mock implementation of the Generic Cell Rate Algorithm (GCRA) for traffic shaping and rate limiting.

gcra rate-limiting traffic-shaping
Python
from collections import deque
import time

class GCRA:
    def __init__(self, rate, burst):
        self.tau = burst
        self.T = rate
        self.t = 0
        self.LCT = 0

    def add_cell(self, arrival_time):
        if arrival_time <= self.t:
            return False
        arrived_early = (arrival_time - s…
14 0 Open
Reliability & rate limiting medium

How to Cap Retry Attempts in Python with a Decorator

Build a reusable retry decorator that caps attempts, adds delays, and lets flaky services fail fast instead of hanging.

retry decorator resilience
Python
import random
from functools import wraps
from time import sleep


def retry(max_attempts, delay=0.1):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            attempts = 0
            while attempts < max_attempts:
                try:
                    return func(*args, **kw…
13 0 Open
Reliability & rate limiting medium

How to Implement Graceful Degradation with Feature Disabling in Python

A pattern that disables enhanced features and falls back to basic functionality when a dependency fails, with mock-based testing.

graceful-degradation feature-flags resilience
Python
import random
from unittest.mock import patch


class EnhancedFeature:
    """A feature that can gracefully degrade when a dependency is unavailable."""

    def __init__(self):
        self.feature_enabled = True

    def get_enhanced_data(self):
        """Simulate an enhanced feature that depends on external data."…
12 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 Bulkhead Pattern with Threading in Python

Implement a bulkhead pattern in Python that isolates concurrent tasks with a bounded semaphore, limiting active workers to prevent resource exhaustion.

bulkhead threading semaphore
Python
import threading
import time
import random


class Bulkhead:
    def __init__(self, workers: int):
        self._semaphore = threading.BoundedSemaphore(workers)
        self._lock = threading.Lock()
        self._active = 0

    def run(self, task):
        with self._semaphore:
            with self._lock:
          …
13 0 Open
Reliability & rate limiting medium

How to Implement a Circuit Breaker in Python

A Python dataclass that provides circuit breaker logic with closed, open, and half-open states to fail fast on repeated errors.

circuit-breaker resilience fault-tolerance
Python
from dataclasses import dataclass
from datetime import datetime, timedelta
import time


@dataclass
class CircuitBreaker:
    failure_threshold: int = 3
    timeout_seconds: float = 5.0
    failures: int = 0
    state: str = "closed"
    last_failure: datetime = None

    def call(self, func):
        if self.state ==…
14 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_…
14 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 Implement an Adaptive Rate Limiter in Python

Build an adaptive rate limiter that adjusts request intervals dynamically based on recent error rates, slowing down when failures spike.

rate-limiting backoff adaptive
Python
import time
import random

class AdaptiveRateLimiter:
    """Simple adaptive rate limiter that reduces requests when error rate is high."""
    
    def __init__(self, min_interval=0.1, max_interval=2.0, error_threshold=0.3):
        self.min_interval = min_interval
        self.max_interval = max_interval
        sel…
11 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…
14 0 Open
Reliability & rate limiting medium

How to Mock a Liveness Check and Restart a Process in Python

Simulate a failing process and restart it after a liveness check fails, using a mock class and a liveness loop.

liveness restart mock
Python
import subprocess
import sys
import time
import os

class ProcessMock:
    def __init__(self, name, fail_after_seconds=3):
        self.name = name
        self.fail_after = fail_after_seconds
        self.start_time = None
        self.is_running = False

    def start(self):
        self.start_time = time.time()
   …
13 0 Open
Reliability & rate limiting medium

How to Propagate Context Variables with asyncio in Python

Use Python's ContextVar with asyncio to carry deadline information across concurrent tasks and propagate context automatically.

contextvars asyncio concurrency
Python
import asyncio
from contextvars import ContextVar
from datetime import datetime

deadline = ContextVar("deadline", default=None)

async def worker(name):
    current = deadline.get()
    if current:
        print(f"{name} sees deadline: {current}")
    else:
        print(f"{name} sees no deadline")
    await asyncio.…
12 0 Open
Reliability & rate limiting medium

How to Send Messages to a Dead Letter Queue in Python

Simulates a poison message queue that retries failed messages up to a limit before moving them to a dead letter queue.

dlq message queue retries
Python
import json

class PoisonMessageQueue:
    def __init__(self, max_retries=3):
        self.dlq = []
        self.max_retries = max_retries
        self.processed_count = 0
        self.failed_count = 0

    def process_message(self, message_body):
        if "poison" in message_body:
            self.failed_count += 1…
14 0 Open
Reliability & rate limiting medium

How to Simulate an Outbox Pattern with Reliable Retry in Python

This code implements a mock outbox pattern with records, delivery attempts, and retries to simulate reliable message publishing.

outbox retry messaging
Python
import time
import itertools

class Outbox:
    def __init__(self):
        self._records = []
        self._seq = itertools.count(1)

    def publish(self, topic, payload):
        record = {
            "id": next(self._seq),
            "topic": topic,
            "payload": payload,
            "status": "pending"…
13 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…
11 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):
       …
12 0 Open
Reliability & rate limiting medium

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.

retry backoff mock
Python
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_…
13 0 Open
Reliability & rate limiting medium

Implement a Circuit Breaker Pattern in Python

This code implements a simple circuit breaker that opens after a threshold of consecutive failures, causing subsequent calls to fail fast without invoking the underlying function.

circuit-breaker reliability resilience
Python
class CircuitBreaker:
    def __init__(self, failure_threshold=3):
        self.failure_threshold = failure_threshold
        self.failure_count = 0
        self.open = False

    def call(self, func, *args, **kwargs):
        if self.open:
            raise RuntimeError("Circuit is open - failing fast")
        try:
…
14 0 Open
Reliability & rate limiting medium

Leaky Bucket Rate Limiter in Python: Smooth Burst Traffic

Implements a token-bucket-style leaky bucket rate limiter that smooths bursty traffic by draining at a fixed rate and dropping excess packets.

rate-limiting traffic-shaping simulation
Python
import time
import random


class LeakyBucket:
    def __init__(self, capacity, drain_rate):
        self.capacity = capacity
        self.drain_rate = drain_rate
        self.water = 0.0
        self.last_time = time.time()

    def allow(self, packet_size=1.0):
        now = time.time()
        elapsed = now - self.…
13 0 Open
Reliability & rate limiting medium

Mock Distributed Rate Limiter with Dict in Python

Simulates a distributed token-bucket rate limiter with a thread-safe dict, useful for testing before moving to Redis.

rate-limiting token-bucket threading
Python
import time
import threading
from collections import defaultdict


class DistributedRateLimiter:
    """
    A mock distributed rate limiter using a dict with thread-safe access.
    Implements a token bucket algorithm per user.
    """

    def __init__(self, rate_per_second=5, burst_capacity=10):
        self.rate_p…
12 0 Open
Reliability & rate limiting medium

Mock a Two-Phase Commit Coordinator in Python

Simulates a two-phase commit protocol where a coordinator asks participants to prepare, then commits or aborts based on unanimous readiness.

two-phase commit distributed systems transactions
Python
import random
import time
from typing import Dict, List


class TwoPhaseCommitCoordinator:
    def __init__(self, participants: List[str]):
        self.participants = participants
        self.participant_state: Dict[str, bool] = {}

    def prepare(self) -> bool:
        print("[Coordinator] Phase 1: Prepare")
     …
11 0 Open
Reliability & rate limiting medium

Retry with Exponential Backoff and Jitter in Python

A decorator-style retry wrapper that retries a flaky function with exponential backoff plus random jitter, then raises after the last attempt fails.

retry backoff jitter
Python
import random
import time

def retry_with_backoff(func, max_retries=3, base_delay=0.5, max_jitter=0.1):
    for attempt in range(max_retries + 1):
        try:
            return func()
        except Exception as e:
            if attempt == max_retries:
                raise
            delay = base_delay * (2 ** at…
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.