Reference library

Reliability & rate limiting

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

37 matches
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.…
13 0 Open
Reliability & rate limiting easy

How to Retry on Specific Exception Tuples in Python

A decorator-based retry pattern that retries a function only when it raises exceptions specified in a tuple, with configurable retries and delay.

retry decorator exceptions
Python
import time
import random
from unittest.mock import patch


def retry_on_exceptions(retries=3, exceptions=(ValueError,), delay=0.1):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for attempt in range(retries):
                try:
                    return func(*args, **kwargs)
          …
15 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…
15 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"…
14 0 Open
Reliability & rate limiting easy

How to Stop Receiving Requests Until Ready in Python

A mock server that refuses requests until a readiness gate is passed, simulating fail-stop behavior for production reliability.

readiness fail-stop mock-server
Python
import random
import time


class MockServer:
    def __init__(self):
        self.ready = False
        self.requests_received = 0

    def readiness_check(self):
        """Simulates a readiness probe. Returns True only when ready."""
        if not self.ready:
            return False
        return True

    def r…
14 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 easy

How to implement an idempotency key store in Python

Build an in-memory idempotency key store with TTL that processes a request once and reuses the cached result for duplicate calls.

idempotency cache ttl
Python
import hashlib
import time
from typing import Dict, Optional


class IdempotencyStore:
    """Simple in-memory idempotency key store with mock processing."""

    def __init__(self, ttl_seconds: int = 3600) -> None:
        self.ttl = ttl_seconds
        self._store: Dict[str, tuple[str, float]] = {}

    def _is_expi…
15 0 Open
Reliability & rate limiting easy

How to implement rate limiting in Python

Build a simple sliding-window rate limiter in Python that enforces a max number of calls per time period and formats data with timestamps.

rate-limiting time sliding-window
Python
import time

class RateLimiter:
    def __init__(self, max_calls, period):
        self.max_calls = max_calls
        self.period = period
        self.calls = []
    
    def allow(self):
        now = time.time()
        # Remove calls older than the period window
        self.calls = [t for t in self.calls if now -…
17 0 Open
Reliability & rate limiting easy

How to implement rate limiting in Python

A beginner-friendly Python rate limiter that throttles API calls and retries parsing tasks with exponential backoff.

rate-limiting retry parsing
Python
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…
15 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
Reliability & rate limiting easy

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.

unittest mocking requests
Python
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:
…
15 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_…
14 0 Open
Reliability & rate limiting easy

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.

rate-limiting sliding-window dataclass
Python
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…
12 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.