Reliability & rate limiting
Retries, exponential backoff, circuit breakers, token buckets, and idempotent handlers.
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.
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 ==…
How to Mock a Slow Startup Probe in Python
Simulate slow service initialization with a configurable mock delay to test readiness probes.
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."""…
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.
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…
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.