Token Bucket Rate Limiter
Implement a token bucket that refills at a steady rate and allows short bursts, a standard algorithm for shaping request traffic.
Code
import time
from dataclasses import dataclass, field
@dataclass
class TokenBucket:
capacity: float
refill_rate: float
tokens: float = field(init=False)
updated_at: float = field(init=False)
def __post_init__(self) -> None:
self.tokens = self.capacity
self.updated_at = time.monotonic()
def allow(self, cost: float = 1.0) -> bool:
now = time.monotonic()
elapsed = now - self.updated_at
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
self.updated_at = now
if self.tokens >= cost:
self.tokens -= cost
return True
return FalseInside the snippet
The working surface is the class class and the functions __post_init__ and allow — everything else is wiring.
Using it
Signature: def allow(self, cost: float = 1.0) -> bool
allow is what another module would consume; nothing else here is load-bearing for callers.
Key statements
def __post_init__(self) -> None:
self.tokens = self.capacity
self.updated_at = time.monotonic()
def allow(self, cost: float = 1.0) -> bool:
now = time.monotonic()
elapsed = now - self.updated_at
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
self.updated_at = now
if self.tokens >= cost:
self.tokens -= cost
return True
return False
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.LLM Token & Cost EstimatorEstimate BPE-approximate LLM token counts across English, CJK text, and source code and compare request and batch costs across pricing tiers.
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `__post_init__`, `allow` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.