Reference library

Reliability & rate limiting

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

31 matches
Reliability & rate limiting easy

Build a Rate Limiter Decorator in Python

This code defines a reusable rate limiter decorator that caps function calls within a sliding time window using a deque and monotonic time.

rate-limiting decorator time
Python
import time
from collections import deque


def rate_limiter(max_calls: int, period: float):
    calls = deque()

    def decorator(func):
        def wrapper(*args, **kwargs):
            now = time.monotonic()
            while calls and now - calls[0] >= period:
                calls.popleft()
            if len(ca…
13 0 Open
Reliability & rate limiting easy

Build a queue-based admission control system in Python

Implement a simple bounded-queue admission controller that accepts or rejects incoming requests based on current queue capacity.

admission-control queue rate-limiting
Python
from collections import deque
import time


class AdmissionControl:
    """Simple admission control using a bounded queue.

    Requests arrive at the queue; they are admitted in FIFO order.
    If the queue is full, the incoming request is rejected.
    """

    def __init__(self, capacity: int):
        self.capacit…
16 0 Open
Reliability & rate limiting easy

Chaos Inject Random Failures in Python

Simulate random failures in a Python function to test error handling and resilience, using random thresholds and controllable success rates.

chaos-engineering random resilience
Python
import random


def unreliable_function(success_rate: float = 0.7) -> str:
    """Simulate a function that sometimes fails."""
    if random.random() > success_rate:
        raise ConnectionError("Simulated network failure")
    return "Operation completed successfully"


if __name__ == "__main__":
    random.seed(42)…
15 0 Open
Reliability & rate limiting easy

Exactly Once Processing Dedupe Mock in Python

Implements a streaming deduplicator using a set and queue to guarantee each item is processed exactly once while preserving insertion order.

deduplication exactly-once streaming
Python
from collections import deque

class DedupeStream:
    def __init__(self):
        self.seen = set()
        self.queue = deque()

    def add(self, item):
        if item not in self.seen:
            self.seen.add(item)
            self.queue.append(item)
            print(f"Processed: {item} (exactly once)")
      …
15 0 Open
Reliability & rate limiting easy

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.

rate-limiting fixed-window time
Python
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 >=…
13 0 Open
Reliability & rate limiting easy

Health Check Mark Unhealthy Stop Traffic Mock in Python

Simulates a health check with a 20% failure rate and automatically stops traffic when the service is unhealthy.

health-check reliability traffic-management
Python
import time
import random

class HealthCheck:
    def __init__(self):
        self.is_healthy = True
        self.stop_traffic = False

    def check_health(self):
        # Simulate health check with random failure rate (20% chance unhealthy)
        self.is_healthy = random.random() > 0.2
        return self.is_heal…
12 0 Open
Reliability & rate limiting easy

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.

rate-limiting token-bucket retry
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 …
15 0 Open
Reliability & rate limiting easy

How to Build a Rate Limiter in Python

Implements a simple sliding-window rate limiter that caps the number of calls per period, used to throttle processing of a data list.

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.timestamps = []

    def allow(self):
        now = time.time()
        self.timestamps = [t for t in self.timestamps if now - t < self.period]
        if len(self.tim…
12 0 Open
Reliability & rate limiting easy

How to Deduplicate Messages in Python by ID

This code consumes a mock inbox of JSON messages and deduplicates them by message ID, keeping either the first or last occurrence.

deduplication inbox json
Python
import json
from collections import OrderedDict

mock_inbox = [
    {"id": 1, "message": "hello", "timestamp": "2024-01-01T10:00:00Z"},
    {"id": 2, "message": "world", "timestamp": "2024-01-01T10:01:00Z"},
    {"id": 1, "message": "hello", "timestamp": "2024-01-01T10:00:00Z"},
    {"id": 3, "message": "test", "times…
14 0 Open
Reliability & rate limiting easy

How to Implement Message Visibility Timeout Renewal in Python

Simulate queue message visibility control with timeout renewal using a simple Python class that tracks received time and visibility state.

visibility-timeout queue sqs
Python
import time
import uuid

class Message:
    def __init__(self, body, visibility_timeout=30):
        self.body = body
        self.visibility_timeout = visibility_timeout
        self.receipt_handle = str(uuid.uuid4())
        self.received_at = time.time()
        self.deleted = False

    def is_visible(self):
     …
13 0 Open
Reliability & rate limiting easy

How to Implement a Dead Letter Queue Replay in Python

A mock Dead Letter Queue that stores failed messages with retry attempts and replays them with a simple retry counter.

dead-letter-queue queue retry
Python
import json
from collections import deque

class DeadLetterQueue:
    def __init__(self):
        self.messages = deque()
    
    def add_message(self, message_id, payload, attempts=3):
        """Add a message to the DLQ with retry metadata."""
        self.messages.append({
            "id": message_id,
           …
13 0 Open
Reliability & rate limiting easy

How to Implement a Rate Limiter in Python

A beginner-friendly Python class that tracks call timestamps with a deque to allow or block calls based on a max rate per time period.

rate-limit deque time
Python
import time
from collections import deque


class RateLimiter:
    """Simple rate limiter for beginners."""

    def __init__(self, max_calls: int, period_seconds: float):
        self.max_calls = max_calls
        self.period = period_seconds
        self.calls = deque()

    def allow(self) -> bool:
        """Retur…
16 0 Open
Reliability & rate limiting easy

How to Implement a Sliding Window Counter in Python

This code implements an approximate sliding window counter using a deque of time-based buckets to track event counts within a recent time window.

sliding-window rate-limiting deque
Python
from collections import deque
from time import time


class SlidingWindowCounter:
    def __init__(self, window_size, bucket_size=1):
        self.window_size = window_size
        self.bucket_size = bucket_size
        self.buckets = deque()

    def _evict_expired(self, now):
        while self.buckets and self.buck…
13 0 Open
Reliability & rate limiting easy

How to Implement a Temporary Block in Python

Build a reusable PenaltyBox class that temporarily blocks access after a failure and reports remaining lockout time.

rate-limiting penalty-box lockout
Python
class PenaltyBox:
    def __init__(self, block_seconds: int = 30):
        self.block_seconds = block_seconds
        self._blocked_until = 0.0
        self._attempts = 0

    def try_access(self, current_time: float) -> bool:
        if self._blocked_until and current_time < self._blocked_until:
            return Fa…
14 0 Open
Reliability & rate limiting easy

How to Inject Random Latency for Chaos Testing in Python

Mock unreliable services by wrapping functions with a decorator that adds random network-like delays before execution.

chaos-engineering decorators latency
Python
import random
import time
from functools import wraps

def inject_latency(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        latency = random.uniform(0.1, 0.5)
        print(f"Injecting {latency:.3f}s latency...")
        time.sleep(latency)
        return func(*args, **kwargs)
    return wrapper

@inje…
12 0 Open
Reliability & rate limiting easy

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.

quota rate-limiting class
Python
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…
16 0 Open
Reliability & rate limiting easy

How to Mock Fault Injection Percentage in Python

Simulate a service with a 30% failure rate using random.random to test error handling and retries.

fault-injection random testing
Python
import random

class Service:
    def call(self):
        if random.random() < 0.3:  # 30% failure rate
            raise ConnectionError("Simulated network fault")
        return "ok"

def main():
    svc = Service()
    random.seed(42)  # deterministic for demonstration
    results = []
    for _ in range(10):
     …
13 0 Open
Reliability & rate limiting easy

How to Mock a Slow Startup Probe in Python

Simulate slow service initialization with a configurable mock delay to test readiness probes.

startup probe mock reliability
Python
import time
from dataclasses import dataclass, field


@dataclass
class StartupProbe:
    name: str
    min_wait_sec: float = 0.5
    max_wait_sec: float = 2.0
    _ready: bool = field(default=False, init=False, repr=False)

    def initialize(self) -> None:
        """Simulate slow startup with a fixed mock delay."""…
12 0 Open
Reliability & rate limiting easy

How to Mock a Timeout per HTTP Request in Python

Simulate a per-request HTTP timeout using unittest.mock to test timeout handling without network access.

mocking timeout testing
Python
import time
from unittest.mock import Mock, patch

# Simulate an HTTP client that might time out
def fetch_data(url, timeout=5):
    time.sleep(0.5)  # Simulate network delay
    return f"Response from {url}"

# Mock to test timeout behavior without real network
def test_timeout():
    mock_response = Mock(side_effect…
12 0 Open
Reliability & rate limiting easy

How to Mock a Try Confirm Cancel Pattern in Python

Define a simple class with confirm and cancel methods, execute a try confirm with error handling, and print the final state.

try-except mock class
Python
class TCC:
    def __init__(self):
        self.confirmed = False
        self.cancelled = False

    def confirm(self):
        self.confirmed = True
        return "confirmed"

    def cancel(self):
        self.cancelled = True
        return "cancelled"

    def try_confirm(self):
        try:
            result =…
12 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)
          …
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…
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…
14 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 -…
16 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.