Python Development Specialist
Generates production-ready, fully typed Python code with tests, docstrings, and usage examples to your spec.
Example run
Generated by Claude Opus 5.5 on November 25, 2026
Inputs used
- What to build
- A thread-safe, asyncio-compatible token-bucket rate limiter library for Python. It must support (1) a `@rate_limited` decorator that can wrap both sync and async functions, (2) a `RateLimiter` class usable as a context manager, and (3) per-key limiting so that, e.g., different user IDs each get their own independent bucket instead of sharing one global quota.
- Input parameters
- Constructor: `rate: float` (tokens refilled per second, e.g. 5.0), `capacity: int` (max tokens/burst size, e.g. 10), `max_keys: int = 10_000` (LRU cap on number of distinct per-key buckets kept in memory). Decorator: `key_func: Callable[..., str] | None = None` to derive the bucket key from call arguments (defaults to a single global key "__default__"), `blocking: bool = True` (wait for a slot vs raise immediately), `timeout: float | None = None` (max seconds to wait when blocking). Call-time inputs are the arguments of whatever function/coroutine is decorated, e.g. `fetch_user_profile(user_id: str) -> dict`.
- Expected output
- When a token is available, the wrapped function/coroutine executes normally and its return value is passed through unchanged. When no token is available: in blocking mode it awaits/sleeps until a token refills (or raises `RateLimitTimeout` if `timeout` elapses first); in non-blocking mode it immediately raises `RateLimitExceeded` with the retry-after seconds attached as an attribute. The `RateLimiter` also exposes `try_acquire(key: str = "__default__") -> bool` for manual checks and `tokens_available(key: str) -> float` for introspection.
- Special requirements
- - No external/third-party dependencies — standard library only (`time`, `asyncio`, `threading`, `collections`, `dataclasses`, `typing`). - Must be safe under concurrent access from multiple threads AND from multiple asyncio tasks in the same process; use a `threading.Lock` for the sync path and an `asyncio.Lock` per key for the async path (or a single lock strategy that is provably safe for both — document the choice). - Use `time.monotonic()` exclusively for interval math so wall-clock adjustments (NTP sync, DST) never corrupt refill calculations. - Token refill must be computed lazily (on each acquire attempt) using elapsed-time math, not a background thread/timer, to avoid idle CPU usage. - Per-key buckets must be stored in a bounded LRU structure (`collections.OrderedDict` or similar) capped at `max_keys`; evict the least-recently-used key's bucket when the cap is exceeded, and document that an evicted key's burst allowance resets. - Memory: O(active distinct keys) up to `max_keys`, each bucket O(1) state (last-refill timestamp + float token count) — no unbounded growth, no per-call allocation beyond a small tuple/dataclass. - The decorator must correctly detect whether the wrapped callable is a coroutine function (`inspect.iscoroutinefunction`) and dispatch to the sync or async acquisition path accordingly, preserving the original function's signature and `__name__`/`__doc__` via `functools.wraps`. - Must not swallow exceptions raised by the wrapped function — only the rate-limiting logic itself should raise `RateLimitExceeded`/`RateLimitTimeout`. - Tests must simulate the passage of time deterministically (e.g., monkeypatching `time.monotonic`) rather than relying on real `time.sleep` delays, so the suite runs in well under one second. - Provide a clear explanation of why no external rate-limiting library (e.g., `ratelimit`, `aiolimiter`) was used, given the "stdlib only" constraint.
- Python version
- 3.11
- Docstring style
Token-Bucket Rate Limiter (stdlib only, Python 3.11)
1. Restated task and assumptions
Task. Build a stdlib-only token-bucket rate limiter that:
- works from threads and from asyncio tasks in the same process;
- keeps a separate bucket for each key (for example, each user ID), stored in an LRU cache bounded by
max_keys; - provides
@rate_limitedfor both sync and async callables; - provides
RateLimiterusable withwithandasync with; - provides
try_acquire()andtokens_available()for manual checks.
Refill is computed lazily with time.monotonic() math. There is no background thread.
Assumptions (where the spec was open):
- Decorator takes a limiter.
@rate_limited(limiter, key_func=..., blocking=..., timeout=...). Rate and capacity belong to theRateLimiterconstructor, as the spec lists them.limiter.limit(...)is a shortcut for the same thing. - One call costs one token. Each call,
acquire, or context-manager entry uses exactly one token. - New and evicted keys start full. A key's bucket starts with
capacitytokens. An evicted key that comes back also starts full. tokens_available()is read-only. It does not create a bucket and does not change LRU order. For an unknown key it returnsfloat(capacity).timeoutonly applies when blocking. Passingblocking=Falsetogether with atimeoutis a configuration mistake, so it raisesValueError.timeout=0means "try once, then raiseRateLimitTimeout".- Timeouts fail fast. Tokens only arrive through refill at a known rate. If the next token cannot arrive before the deadline,
RateLimitTimeoutis raised right away instead of sleeping until the deadline first. - Clock and sleep can be injected (
clock,sleep,async_sleep) for deterministic tests. The default clock istime.monotonic, looked up when the limiter is constructed, so monkeypatchingtime.monotonicalso works (one test does exactly that). - Keys must be
str. Anything else raisesTypeError, as does akey_functhat returns a non-str. - No FIFO fairness. Blocking waiters retry after sleeping, so a newly arriving caller can take a token ahead of an existing waiter. This is documented, not hidden.
2. Edge cases and how they are handled
| Case | Handling |
|---|---|
rate ≤ 0, NaN, ∞, bool, or non-numeric |
ValueError / TypeError |
capacity / max_keys < 1, a bool, or not an int |
ValueError / TypeError |
timeout negative, NaN, or set with blocking=False |
ValueError |
| Floating-point drift, e.g. 0.9999999 tokens after an "exact" sleep | 1e-6 token tolerance, so the retry loop always terminates, even with a fake clock whose value no longer changes on tiny steps |
| Clock not advancing between calls (or a buggy injected clock going backwards) | Elapsed time is clamped at ≥ 0, so tokens never go negative |
| Wrapped function raises | The exception propagates unchanged. The token stays consumed, because the call was attempted |
Exception inside a with / async with block |
Propagates; __exit__ never suppresses |
Async generator function, or callable object with async __generator__ |
Rejected with TypeError. A sync wrapper would block the loop and would not limit iteration |
Callable object with async def __call__ |
Detected and routed to the async path |
| Key evicted while a waiter sleeps | The waiter retries and gets a fresh, full bucket (documented reset) |
| Task cancelled while waiting | No token is consumed, because tokens are only taken on a successful attempt |
| Threads and tasks competing at once | A single threading.Lock around non-suspending O(1) critical sections. Covered by tests |
3. Implementation: token_bucket.py
"""Thread-safe, asyncio-compatible token-bucket rate limiting (stdlib only).
Algorithm
---------
Each key owns a bucket holding up to ``capacity`` tokens that refills at
``rate`` tokens/second. Refill is computed lazily on every access from the
time elapsed since the last update (``time.monotonic()``), so idle limiters
cost zero CPU and there is no background thread or timer.
Locking strategy (why one ``threading.Lock`` is safe for threads *and* tasks)
---------------------------------------------------------------------------
All bucket state is guarded by a single :class:`threading.Lock`. Every
critical section:
* performs only O(1) arithmetic and ``OrderedDict`` operations, and
* never awaits, sleeps, or calls user code while holding the lock.
An asyncio task therefore can never be suspended while holding the lock. It
cannot deadlock against another task on the same event-loop thread, and a
thread contending for the lock waits only microseconds. Waiting for a refill
happens *outside* the lock, via ``time.sleep`` (sync path) or
``asyncio.sleep`` (async path), so the event loop is never blocked on a
refill.
A per-key ``asyncio.Lock`` was deliberately not used. ``asyncio.Lock`` is not
thread-safe, is bound to one event loop, and gives no protection against
concurrent threads, so a ``threading.Lock`` would be required anyway. One
lock for both paths is a single, auditable source of truth and costs no
extra memory per key.
Fairness
--------
Blocking waiters sleep until the next token is due and then retry. Waiters
are not served in FIFO order, so a newly arriving caller may win a token
before an existing waiter. The total throughput guarantee is unaffected.
Eviction
--------
Per-key buckets live in an LRU ``OrderedDict`` capped at ``max_keys``. When a
new key would exceed the cap, the least-recently-used bucket is dropped.
**An evicted key that reappears gets a fresh, full bucket: its burst allowance
resets.** Size ``max_keys`` comfortably above the number of keys active within
one refill window (``capacity / rate`` seconds) to prevent clients from
cycling keys to earn extra bursts.
"""
from __future__ import annotations
import asyncio
import functools
import inspect
import math
import threading
import time
from collections import OrderedDict
from collections.abc import Awaitable, Callable, Coroutine
from dataclasses import dataclass
from types import TracebackType
from typing import Any, Final, ParamSpec, Protocol, Self, TypeVar, cast, overload
__all__ = [
"DEFAULT_KEY",
"RateLimitError",
"RateLimitExceeded",
"RateLimitTimeout",
"RateLimiter",
"rate_limited",
]
DEFAULT_KEY: Final[str] = "__default__"
# Tolerance (in tokens) that absorbs floating-point drift, so that sleeping
# exactly ``retry_after`` seconds always yields a usable token.
_EPSILON: Final[float] = 1e-6
P = ParamSpec("P")
R = TypeVar("R")
Clock = Callable[[], float]
SleepFunc = Callable[[float], None]
AsyncSleepFunc = Callable[[float], Awaitable[None]]
# --------------------------------------------------------------------------- #
# Exceptions
# --------------------------------------------------------------------------- #
class RateLimitError(Exception):
"""Base class for all errors raised by the rate-limiting logic.
Attributes:
key: The bucket key that was rate limited.
retry_after: Seconds until the next token becomes available.
"""
def __init__(self, message: str, *, key: str, retry_after: float) -> None:
super().__init__(message)
self.key = key
self.retry_after = retry_after
class RateLimitExceeded(RateLimitError):
"""Raised in non-blocking mode when no token is immediately available."""
def __init__(self, key: str, retry_after: float) -> None:
super().__init__(
f"Rate limit exceeded for key {key!r}; retry after {retry_after:.3f}s",
key=key,
retry_after=retry_after,
)
class RateLimitTimeout(RateLimitError, TimeoutError):
"""Raised in blocking mode when no token can be obtained within ``timeout``.
Attributes:
timeout: The timeout (in seconds) that was exceeded.
"""
def __init__(self, key: str, timeout: float, retry_after: float) -> None:
super().__init__(
f"Timed out after {timeout:.3f}s waiting for a token for key {key!r}; "
f"next token in {retry_after:.3f}s",
key=key,
retry_after=retry_after,
)
self.timeout = timeout
# --------------------------------------------------------------------------- #
# Validation helpers
# --------------------------------------------------------------------------- #
def _validate_positive_int(name: str, value: int) -> int:
"""Validate that ``value`` is an int >= 1 (bools rejected).
Args:
name: Parameter name used in error messages.
value: Value to validate.
Returns:
The validated value.
Raises:
TypeError: If ``value`` is not an ``int`` (or is a ``bool``).
ValueError: If ``value`` < 1.
"""
if isinstance(value, bool) or not isinstance(value, int):
raise TypeError(f"{name} must be an int, got {type(value).__name__}")
if value < 1:
raise ValueError(f"{name} must be >= 1, got {value}")
return value
def _validate_rate(rate: float) -> float:
"""Validate the refill rate.
Args:
rate: Tokens refilled per second.
Returns:
The rate as a ``float``.
Raises:
TypeError: If ``rate`` is not a real number (or is a ``bool``).
ValueError: If ``rate`` is not finite or not strictly positive.
"""
if isinstance(rate, bool) or not isinstance(rate, (int, float)):
raise TypeError(f"rate must be a number, got {type(rate).__name__}")
if not math.isfinite(rate) or rate <= 0:
raise ValueError(f"rate must be a finite number > 0, got {rate}")
return float(rate)
def _validate_wait_options(blocking: bool, timeout: float | None) -> None:
"""Validate the ``blocking`` / ``timeout`` combination.
Args:
blocking: Whether the caller waits for a token.
timeout: Maximum seconds to wait, or ``None`` for no limit.
Raises:
TypeError: If ``blocking`` is not a bool or ``timeout`` is not a number.
ValueError: If ``timeout`` is negative/NaN or given with ``blocking=False``.
"""
if not isinstance(blocking, bool):
raise TypeError(f"blocking must be a bool, got {type(blocking).__name__}")
if timeout is None:
return
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
raise TypeError(f"timeout must be a number or None, got {type(timeout).__name__}")
if math.isnan(timeout) or timeout < 0:
raise ValueError(f"timeout must be >= 0, got {timeout}")
if not blocking:
raise ValueError("timeout is only meaningful with blocking=True")
def _validate_key(key: str) -> str:
"""Ensure a bucket key is a ``str``.
Args:
key: Candidate bucket key.
Returns:
The validated key.
Raises:
TypeError: If ``key`` is not a ``str``.
"""
if not isinstance(key, str):
raise TypeError(f"key must be a str, got {type(key).__name__}")
return key
# --------------------------------------------------------------------------- #
# Bucket state
# --------------------------------------------------------------------------- #
@dataclass(slots=True)
class _Bucket:
"""O(1) per-key state: a token count and the time it was last updated."""
tokens: float
updated_at: float
def refill(self, now: float, rate: float, capacity: float) -> None:
"""Lazily add the tokens accrued since ``updated_at``, capped at capacity.
Args:
now: Current monotonic time.
rate: Tokens per second.
capacity: Maximum tokens.
"""
elapsed = now - self.updated_at
if elapsed > 0:
self.tokens = min(capacity, self.tokens + elapsed * rate)
self.updated_at = now
def peek(self, now: float, rate: float, capacity: float) -> float:
"""Return the token count at ``now`` without mutating state.
Args:
now: Current monotonic time.
rate: Tokens per second.
capacity: Maximum tokens.
Returns:
The (fractional) number of tokens available.
"""
elapsed = max(0.0, now - self.updated_at)
return min(capacity, self.tokens + elapsed * rate)
# --------------------------------------------------------------------------- #
# Limiter
# --------------------------------------------------------------------------- #
class RateLimiter:
"""Per-key token-bucket rate limiter, safe for threads and asyncio tasks.
Example:
>>> limiter = RateLimiter(rate=5.0, capacity=10)
>>> limiter.try_acquire("user-42")
True
"""
def __init__(
self,
rate: float,
capacity: int,
max_keys: int = 10_000,
*,
clock: Clock | None = None,
sleep: SleepFunc | None = None,
async_sleep: AsyncSleepFunc | None = None,
) -> None:
"""Create a limiter.
Args:
rate: Tokens refilled per second (> 0).
capacity: Maximum tokens per bucket, i.e. the burst size (>= 1).
max_keys: LRU cap on the number of per-key buckets kept in memory.
clock: Monotonic time source. Defaults to ``time.monotonic``.
Injectable for deterministic tests; it must never go backwards.
sleep: Blocking sleep used by the sync path. Defaults to ``time.sleep``.
async_sleep: Awaitable sleep used by the async path. Defaults to
``asyncio.sleep``.
Raises:
TypeError: If an argument has the wrong type.
ValueError: If an argument is out of range.
"""
self._rate = _validate_rate(rate)
self._capacity = _validate_positive_int("capacity", capacity)
self._max_tokens = float(self._capacity)
self._max_keys = _validate_positive_int("max_keys", max_keys)
# Resolve defaults at construction time, so monkeypatching
# ``time.monotonic`` before construction is honoured.
self._clock: Clock = clock if clock is not None else time.monotonic
self._sleep: SleepFunc = sleep if sleep is not None else time.sleep
self._async_sleep: AsyncSleepFunc = (
async_sleep if async_sleep is not None else asyncio.sleep
)
self._buckets: OrderedDict[str, _Bucket] = OrderedDict()
self._lock = threading.Lock()
# ---- read-only properties ------------------------------------------- #
@property
def rate(self) -> float:
"""Tokens refilled per second."""
return self._rate
@property
def capacity(self) -> int:
"""Maximum tokens per bucket (burst size)."""
return self._capacity
@property
def max_keys(self) -> int:
"""Maximum number of per-key buckets kept in memory."""
return self._max_keys
def __len__(self) -> int:
"""Return the number of buckets currently tracked."""
with self._lock:
return len(self._buckets)
def __repr__(self) -> str:
return (
f"{type(self).__name__}(rate={self._rate}, capacity={self._capacity}, "
f"max_keys={self._max_keys})"
)
# ---- core (lock-protected, O(1), never suspends) --------------------- #
def _get_bucket(self, key: str, now: float) -> _Bucket:
"""Fetch or create ``key``'s bucket and mark it most-recently-used.
Must be called with ``self._lock`` held.
Args:
key: Bucket key.
now: Current monotonic time (used for a new bucket's timestamp).
Returns:
The bucket for ``key``.
"""
bucket = self._buckets.get(key)
if bucket is None:
bucket = _Bucket(tokens=self._max_tokens, updated_at=now)
self._buckets[key] = bucket
if len(self._buckets) > self._max_keys:
self._buckets.popitem(last=False) # evict LRU; its burst resets
else:
self._buckets.move_to_end(key)
return bucket
def _try_consume(self, key: str) -> float:
"""Atomically try to take one token from ``key``'s bucket.
Args:
key: Bucket key (already validated).
Returns:
``0.0`` if a token was consumed, otherwise the seconds until one
token will be available (always > 0).
"""
with self._lock:
now = self._clock()
bucket = self._get_bucket(key, now)
bucket.refill(now, self._rate, self._max_tokens)
if bucket.tokens >= 1.0 - _EPSILON:
bucket.tokens = max(0.0, bucket.tokens - 1.0)
return 0.0
return (1.0 - bucket.tokens) / self._rate
def _attempt(
self, key: str, blocking: bool, timeout: float | None, started_at: float
) -> float:
"""Make one acquisition attempt and decide what happens next.
Args:
key: Bucket key (already validated).
blocking: Whether to wait for a token.
timeout: Maximum total wait, or ``None``.
started_at: Monotonic time at which acquisition began.
Returns:
``0.0`` if acquired, otherwise the seconds to sleep before retrying.
Raises:
RateLimitExceeded: If no token is available and ``blocking`` is False.
RateLimitTimeout: If the next token cannot arrive before the deadline.
"""
retry_after = self._try_consume(key)
if retry_after == 0.0:
return 0.0
if not blocking:
raise RateLimitExceeded(key, retry_after)
if timeout is not None:
remaining = started_at + timeout - self._clock()
# Tokens only appear through refill, so if the next one is due after
# the deadline, waiting is pointless: fail fast.
if retry_after > remaining:
raise RateLimitTimeout(key, timeout, retry_after)
return retry_after
# ---- public API ------------------------------------------------------ #
def try_acquire(self, key: str = DEFAULT_KEY) -> bool:
"""Consume a token if one is available, without waiting.
Args:
key: Bucket key.
Returns:
``True`` if a token was consumed, ``False`` otherwise.
Raises:
TypeError: If ``key`` is not a ``str``.
"""
return self._try_consume(_validate_key(key)) == 0.0
def acquire(
self,
key: str = DEFAULT_KEY,
*,
blocking: bool = True,
timeout: float | None = None,
) -> None:
"""Acquire a token, sleeping the current thread if necessary.
Do not call this from inside a running event loop; use
:meth:`acquire_async` there.
Args:
key: Bucket key.
blocking: Wait for a token (``True``) or raise immediately (``False``).
timeout: Maximum seconds to wait when blocking; ``None`` = forever.
Raises:
TypeError: On invalid argument types.
ValueError: On invalid argument values.
RateLimitExceeded: If non-blocking and no token is available.
RateLimitTimeout: If blocking and ``timeout`` would be exceeded.
"""
key = _validate_key(key)
_validate_wait_options(blocking, timeout)
started_at = self._clock()
while (delay := self._attempt(key, blocking, timeout, started_at)) > 0.0:
self._sleep(delay)
async def acquire_async(
self,
key: str = DEFAULT_KEY,
*,
blocking: bool = True,
timeout: float | None = None,
) -> None:
"""Acquire a token, awaiting (never blocking the event loop) if needed.
Cancellation while waiting is safe: no token is consumed.
Args:
key: Bucket key.
blocking: Wait for a token (``True``) or raise immediately (``False``).
timeout: Maximum seconds to wait when blocking; ``None`` = forever.
Raises:
TypeError: On invalid argument types.
ValueError: On invalid argument values.
RateLimitExceeded: If non-blocking and no token is available.
RateLimitTimeout: If blocking and ``timeout`` would be exceeded.
"""
key = _validate_key(key)
_validate_wait_options(blocking, timeout)
started_at = self._clock()
while (delay := self._attempt(key, blocking, timeout, started_at)) > 0.0:
await self._async_sleep(delay)
def tokens_available(self, key: str = DEFAULT_KEY) -> float:
"""Return the (fractional) tokens currently available for ``key``.
This is pure introspection: it neither creates a bucket nor changes
LRU order. Unknown (or evicted) keys report a full bucket.
Args:
key: Bucket key.
Returns:
Tokens available, in ``[0.0, capacity]``.
Raises:
TypeError: If ``key`` is not a ``str``.
"""
key = _validate_key(key)
with self._lock:
bucket = self._buckets.get(key)
if bucket is None:
return self._max_tokens
return bucket.peek(self._clock(), self._rate, self._max_tokens)
def slot(
self,
key: str = DEFAULT_KEY,
*,
blocking: bool = True,
timeout: float | None = None,
) -> _Acquisition:
"""Return a context manager (sync or async) that acquires one token.
Example:
>>> with limiter.slot("user-42", timeout=1.0):
... call_api()
Args:
key: Bucket key.
blocking: Wait for a token or raise immediately.
timeout: Maximum seconds to wait when blocking.
Returns:
A context manager usable with ``with`` or ``async with``.
Raises:
TypeError: On invalid argument types.
ValueError: On invalid argument values.
"""
_validate_wait_options(blocking, timeout)
return _Acquisition(self, _validate_key(key), blocking, timeout)
def limit(
self,
*,
key_func: Callable[..., str] | None = None,
blocking: bool = True,
timeout: float | None = None,
) -> _RateLimitDecorator:
"""Shortcut for :func:`rate_limited` bound to this limiter.
Args:
key_func: Derives the bucket key from the call's arguments.
blocking: Wait for a token or raise immediately.
timeout: Maximum seconds to wait when blocking.
Returns:
A decorator for sync or async callables.
"""
return rate_limited(self, key_func=key_func, blocking=blocking, timeout=timeout)
# ---- context-manager protocol (default key, blocking, no timeout) --- #
def __enter__(self) -> Self:
self.acquire()
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
return None # never suppress exceptions
async def __aenter__(self) -> Self:
await self.acquire_async()
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
return None
class _Acquisition:
"""Context manager that acquires one token on entry (sync or async)."""
__slots__ = ("_limiter", "_key", "_blocking", "_timeout")
def __init__(
self, limiter: RateLimiter, key: str, blocking: bool, timeout: float | None
) -> None:
self._limiter = limiter
self._key = key
self._blocking = blocking
self._timeout = timeout
def __enter__(self) -> None:
self._limiter.acquire(self._key, blocking=self._blocking, timeout=self._timeout)
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
return None
async def __aenter__(self) -> None:
await self._limiter.acquire_async(
self._key, blocking=self._blocking, timeout=self._timeout
)
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
return None
# --------------------------------------------------------------------------- #
# Decorator
# --------------------------------------------------------------------------- #
class _RateLimitDecorator(Protocol):
"""Typed decorator that preserves sync/async signatures."""
@overload
def __call__(
self, func: Callable[P, Coroutine[Any, Any, R]], /
) -> Callable[P, Coroutine[Any, Any, R]]: ...
@overload
def __call__(self, func: Callable[P, R], /) -> Callable[P, R]: ...
def __call__(self, func: Callable[..., Any], /) -> Callable[..., Any]: ...
def _is_coroutine_callable(func: object) -> bool:
"""Return True for coroutine functions and objects with ``async __call__``."""
if inspect.iscoroutinefunction(func):
return True
call = getattr(func, "__call__", None)
return call is not None and not inspect.isfunction(func) and inspect.iscoroutinefunction(call)
def _is_async_generator_callable(func: object) -> bool:
"""Return True for async generator functions (incl. via ``__call__``)."""
if inspect.isasyncgenfunction(func):
return True
call = getattr(func, "__call__", None)
return call is not None and not inspect.isfunction(func) and inspect.isasyncgenfunction(call)
def rate_limited(
limiter: RateLimiter,
*,
key_func: Callable[..., str] | None = None,
blocking: bool = True,
timeout: float | None = None,
) -> _RateLimitDecorator:
"""Rate-limit a sync or async callable using ``limiter``.
The decorator detects coroutine functions and acquires tokens with
``await`` (never blocking the event loop); plain functions acquire with a
thread-blocking sleep. ``functools.wraps`` preserves ``__name__``,
``__doc__``, ``__wrapped__`` and therefore ``inspect.signature``.
When decorating methods, ``key_func`` receives ``self`` as its first
argument, exactly like the method itself. Apply ``@rate_limited`` *below*
``@staticmethod`` / ``@classmethod``.
Example:
>>> @rate_limited(limiter, key_func=lambda user_id: user_id)
... async def fetch_user_profile(user_id: str) -> dict: ...
Args:
limiter: The limiter that owns the buckets.
key_func: Called with the wrapped function's ``*args, **kwargs`` and
must return the ``str`` bucket key. Defaults to ``DEFAULT_KEY``
(one global bucket).
blocking: Wait for a token (``True``) or raise ``RateLimitExceeded``.
timeout: Maximum seconds to wait when blocking; ``None`` = forever.
Returns:
A decorator.
Raises:
TypeError: If ``limiter``/``key_func`` are invalid, or (at decoration
time) the target is not callable or is an async generator.
ValueError: On an invalid ``blocking``/``timeout`` combination.
"""
if not isinstance(limiter, RateLimiter):
raise TypeError(f"limiter must be a RateLimiter, got {type(limiter).__name__}")
if key_func is not None and not callable(key_func):
raise TypeError("key_func must be callable or None")
_validate_wait_options(blocking, timeout)
def resolve_key(args: tuple[object, ...], kwargs: dict[str, object]) -> str:
if key_func is None:
return DEFAULT_KEY
key = key_func(*args, **kwargs)
if not isinstance(key, str):
raise TypeError(f"key_func must return a str, got {type(key).__name__}")
return key
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
if not callable(func):
raise TypeError(f"@rate_limited target must be callable, got {type(func).__name__}")
if _is_async_generator_callable(func):
raise TypeError(
"@rate_limited does not support async generator functions; "
"acquire inside the generator with `async with limiter.slot(...)`"
)
if _is_coroutine_callable(func):
@functools.wraps(func)
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
await limiter.acquire_async(
resolve_key(args, kwargs), blocking=blocking, timeout=timeout
)
return await func(*args, **kwargs)
return async_wrapper
@functools.wraps(func)
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
limiter.acquire(resolve_key(args, kwargs), blocking=blocking, timeout=timeout)
return func(*args, **kwargs)
return sync_wrapper
return cast(_RateLimitDecorator, decorator)
# --------------------------------------------------------------------------- #
# Usage example
# --------------------------------------------------------------------------- #
if __name__ == "__main__":
api_limiter = RateLimiter(rate=5.0, capacity=3, max_keys=1_000)
@rate_limited(api_limiter, key_func=lambda user_id: f"profile:{user_id}", blocking=False)
def fetch_user_profile(user_id: str) -> dict[str, str]:
"""Pretend to call a profile service."""
return {"user_id": user_id, "plan": "pro" if user_id.startswith("a") else "free"}
@rate_limited(api_limiter, key_func=lambda user_id: f"orders:{user_id}", timeout=2.0)
async def fetch_user_orders(user_id: str) -> list[str]:
"""Pretend to call an orders service."""
await asyncio.sleep(0)
return [f"{user_id}-order-{n}" for n in range(2)]
def demo_sync() -> None:
print("== sync, non-blocking, per-user buckets (burst=3) ==")
for user_id in ["alice", "alice", "alice", "alice", "bob"]:
try:
print(f" ok {fetch_user_profile(user_id)}")
except RateLimitExceeded as exc:
print(f" deny {user_id}: retry after {exc.retry_after:.2f}s")
print(f" alice tokens left: {api_limiter.tokens_available('profile:alice'):.2f}")
async def demo_async() -> None:
print("== async, blocking, 5 calls for carol (3 burst + 2 refilled at 5/s) ==")
start = time.monotonic()
batches = await asyncio.gather(*(fetch_user_orders("carol") for _ in range(5)))
print(f" fetched {len(batches)} batches in {time.monotonic() - start:.2f}s")
print("== manual context manager ==")
async with api_limiter.slot("reports", timeout=1.0):
print(" generated nightly report")
demo_sync()
asyncio.run(demo_async())
Expected output (timings approximate):
== sync, non-blocking, per-user buckets (burst=3) ==
ok {'user_id': 'alice', 'plan': 'pro'}
ok {'user_id': 'alice', 'plan': 'pro'}
ok {'user_id': 'alice', 'plan': 'pro'}
deny alice: retry after 0.20s
ok {'user_id': 'bob', 'plan': 'free'}
alice tokens left: 0.00
== async, blocking, 5 calls for carol (3 burst + 2 refilled at 5/s) ==
fetched 5 batches in 0.40s
== manual context manager ==
generated nightly report
4. Test suite: test_token_bucket.py
All time passes through a fake clock. Its sleep and async_sleep advance the virtual clock, so nothing actually waits. The async tests use asyncio.run, so pytest-asyncio is not needed.
"""Deterministic tests for token_bucket. Runs in well under one second."""
from __future__ import annotations
import asyncio
import inspect
import threading
import time
import pytest
import token_bucket
from token_bucket import (
DEFAULT_KEY,
RateLimiter,
RateLimitExceeded,
RateLimitTimeout,
rate_limited,
)
class FakeClock:
"""Virtual monotonic clock; its sleeps advance time instantly."""
def __init__(self, start: float = 1_000.0) -> None:
self.now = start
self.sleeps: list[float] = []
def __call__(self) -> float:
return self.now
def advance(self, seconds: float) -> None:
self.now += seconds
def sleep(self, seconds: float) -> None:
self.sleeps.append(seconds)
self.now += seconds
async def async_sleep(self, seconds: float) -> None:
self.sleeps.append(seconds)
self.now += seconds
await asyncio.sleep(0) # still yield to the loop, like a real sleep
@pytest.fixture
def clock() -> FakeClock:
return FakeClock()
def make_limiter(
clock: FakeClock, rate: float = 1.0, capacity: int = 2, max_keys: int = 100
) -> RateLimiter:
return RateLimiter(
rate, capacity, max_keys,
clock=clock, sleep=clock.sleep, async_sleep=clock.async_sleep,
)
# ---------------------------------------------------------------- validation
@pytest.mark.parametrize("rate", [0, -1.0, float("nan"), float("inf")])
def test_invalid_rate_values_raise_value_error(rate: float) -> None:
with pytest.raises(ValueError, match="rate"):
RateLimiter(rate, 1)
@pytest.mark.parametrize("rate", ["5", None, True])
def test_invalid_rate_types_raise_type_error(rate: object) -> None:
with pytest.raises(TypeError, match="rate"):
RateLimiter(rate, 1) # type: ignore[arg-type]
@pytest.mark.parametrize("field", ["capacity", "max_keys"])
@pytest.mark.parametrize("value, exc", [(0, ValueError), (-3, ValueError), (1.5, TypeError), (True, TypeError)])
def test_invalid_capacity_and_max_keys(field: str, value: object, exc: type[Exception]) -> None:
kwargs: dict[str, object] = {"rate": 1.0, "capacity": 1, "max_keys": 1, field: value}
with pytest.raises(exc, match=field):
RateLimiter(**kwargs) # type: ignore[arg-type]
def test_negative_timeout_is_rejected(clock: FakeClock) -> None:
with pytest.raises(ValueError, match="timeout"):
make_limiter(clock).acquire(timeout=-0.1)
def test_timeout_with_non_blocking_is_rejected(clock: FakeClock) -> None:
limiter = make_limiter(clock)
with pytest.raises(ValueError, match="blocking=True"):
rate_limited(limiter, blocking=False, timeout=1.0)
def test_non_string_key_is_rejected(clock: FakeClock) -> None:
with pytest.raises(TypeError, match="key must be a str"):
make_limiter(clock).try_acquire(123) # type: ignore[arg-type]
def test_decorator_requires_a_rate_limiter() -> None:
with pytest.raises(TypeError, match="RateLimiter"):
rate_limited("not a limiter") # type: ignore[arg-type]
# ------------------------------------------------------------ bucket math
def test_new_bucket_starts_full(clock: FakeClock) -> None:
assert make_limiter(clock, capacity=10).tokens_available("fresh") == 10.0
def test_try_acquire_consumes_up_to_capacity_then_refuses(clock: FakeClock) -> None:
limiter = make_limiter(clock, capacity=3)
assert [limiter.try_acquire() for _ in range(4)] == [True, True, True, False]
def test_refill_is_lazy_fractional_and_capped(clock: FakeClock) -> None:
limiter = make_limiter(clock, rate=2.0, capacity=4)
for _ in range(4):
limiter.try_acquire()
clock.advance(0.25)
assert limiter.tokens_available() == pytest.approx(0.5)
clock.advance(100.0)
assert limiter.tokens_available() == 4.0
def test_retry_after_reflects_time_until_next_token(clock: FakeClock) -> None:
limiter = make_limiter(clock, rate=2.0, capacity=1)
limiter.acquire()
with pytest.raises(RateLimitExceeded) as first:
limiter.acquire(blocking=False)
assert first.value.retry_after == pytest.approx(0.5)
clock.advance(0.2)
with pytest.raises(RateLimitExceeded) as second:
limiter.acquire(blocking=False)
assert second.value.retry_after == pytest.approx(0.3)
assert second.value.key == DEFAULT_KEY
def test_float_drift_does_not_cause_infinite_retry(clock: FakeClock) -> None:
limiter = make_limiter(clock, rate=3.0, capacity=1)
for _ in range(4):
limiter.acquire()
assert sum(clock.sleeps) == pytest.approx(1.0)
assert len(clock.sleeps) == 3
def test_default_clock_is_monotonic_and_ignores_wall_clock(monkeypatch: pytest.MonkeyPatch) -> None:
fake = FakeClock()
monkeypatch.setattr(token_bucket.time, "monotonic", fake)
monkeypatch.setattr(token_bucket.time, "time", lambda: 0.0) # wall clock "jumps"
limiter = RateLimiter(rate=1.0, capacity=1)
assert limiter.try_acquire()
assert not limiter.try_acquire()
fake.advance(1.0)
assert limiter.try_acquire()
def test_no_background_threads_are_started(clock: FakeClock) -> None:
before = threading.active_count()
limiter = make_limiter(clock)
limiter.try_acquire("a")
clock.advance(10)
limiter.tokens_available("a")
assert threading.active_count() == before
# ------------------------------------------------------------ per-key + LRU
def test_keys_have_independent_buckets(clock: FakeClock) -> None:
limiter = make_limiter(clock, capacity=1)
assert limiter.try_acquire("alice")
assert not limiter.try_acquire("alice")
assert limiter.try_acquire("bob")
def test_lru_evicts_least_recently_used_and_resets_its_burst(clock: FakeClock) -> None:
limiter = make_limiter(clock, capacity=1, max_keys=2)
limiter.try_acquire("a")
limiter.try_acquire("b")
limiter.try_acquire("a") # refreshes a's recency (even though it fails)
limiter.try_acquire("c") # evicts b, the least recently used
assert len(limiter) == 2
assert limiter.tokens_available("a") == 0.0
assert limiter.try_acquire("b") # b came back with a full, reset bucket
def test_tokens_available_is_read_only(clock: FakeClock) -> None:
limiter = make_limiter(clock, capacity=1, max_keys=2)
assert limiter.tokens_available("ghost") == 1.0
assert len(limiter) == 0
limiter.try_acquire("a")
limiter.try_acquire("b")
limiter.tokens_available("a") # must NOT refresh recency
limiter.try_acquire("c") # so a is evicted
assert limiter.try_acquire("a")
# ------------------------------------------------------------ sync decorator
def test_sync_decorator_passes_through_return_value_and_metadata(clock: FakeClock) -> None:
limiter = make_limiter(clock)
def fetch_user_profile(user_id: str, *, verbose: bool = False) -> dict[str, str]:
"""Fetch a profile."""
return {"id": user_id}
wrapped = rate_limited(limiter)(fetch_user_profile)
assert wrapped("u1") == {"id": "u1"}
assert wrapped.__name__ == "fetch_user_profile"
assert wrapped.__doc__ == "Fetch a profile."
assert inspect.signature(wrapped) == inspect.signature(fetch_user_profile)
assert not inspect.iscoroutinefunction(wrapped)
def test_sync_blocking_sleeps_exactly_until_refill(clock: FakeClock) -> None:
limiter = make_limiter(clock, rate=2.0, capacity=1)
@rate_limited(limiter)
def ping() -> str:
return "pong"
assert [ping(), ping()] == ["pong", "pong"]
assert clock.sleeps == [pytest.approx(0.5)]
def test_sync_non_blocking_raises_without_calling_function(clock: FakeClock) -> None:
limiter = make_limiter(clock, capacity=1)
calls: list[int] = []
@rate_limited(limiter, blocking=False)
def work() -> None:
calls.append(1)
work()
with pytest.raises(RateLimitExceeded):
work()
assert calls == [1]
assert clock.sleeps == []
def test_sync_timeout_fails_fast_without_consuming(clock: FakeClock) -> None:
limiter = make_limiter(clock, rate=2.0, capacity=1)
@rate_limited(limiter, timeout=0.1)
def work() -> int:
return 1
work()
with pytest.raises(RateLimitTimeout) as info:
work()
assert isinstance(info.value, TimeoutError)
assert info.value.timeout == 0.1
assert info.value.retry_after == pytest.approx(0.5)
assert clock.sleeps == []
assert limiter.tokens_available() == 0.0
def test_sync_timeout_long_enough_succeeds(clock: FakeClock) -> None:
limiter = make_limiter(clock, rate=2.0, capacity=1)
@rate_limited(limiter, timeout=0.5)
def work() -> int:
return 7
assert work() == 7
assert work() == 7
assert clock.sleeps == [pytest.approx(0.5)]
def test_key_func_routes_calls_to_per_user_buckets(clock: FakeClock) -> None:
limiter = make_limiter(clock, capacity=1)
@rate_limited(limiter, key_func=lambda user_id: user_id, blocking=False)
def fetch(user_id: str) -> str:
return user_id
assert fetch("alice") == "alice"
assert fetch(user_id="bob") == "bob"
with pytest.raises(RateLimitExceeded) as info:
fetch("alice")
assert info.value.key == "alice"
def test_key_func_returning_non_string_raises_type_error(clock: FakeClock) -> None:
limiter = make_limiter(clock)
@rate_limited(limiter, key_func=lambda x: x) # type: ignore[arg-type, return-value]
def fetch(x: int) -> int:
return x
with pytest.raises(TypeError, match="key_func must return a str"):
fetch(42)
assert len(limiter) == 0
def test_wrapped_function_exceptions_propagate_and_token_is_spent(clock: FakeClock) -> None:
limiter = make_limiter(clock, capacity=2)
@rate_limited(limiter)
def explode() -> None:
raise ValueError("upstream failure")
with pytest.raises(ValueError, match="upstream failure"):
explode()
assert limiter.tokens_available() == 1.0
def test_decorating_async_generator_is_rejected(clock: FakeClock) -> None:
limiter = make_limiter(clock)
with pytest.raises(TypeError, match="async generator"):
@rate_limited(limiter)
async def stream(): # type: ignore[no-untyped-def]
yield 1
# ------------------------------------------------------------ async decorator
def test_async_decorator_stays_coroutine_function_and_returns_value(clock: FakeClock) -> None:
limiter = make_limiter(clock)
@rate_limited(limiter)
async def fetch_user_profile(user_id: str) -> dict[str, str]:
"""Async fetch."""
return {"id": user_id}
assert inspect.iscoroutinefunction(fetch_user_profile)
assert fetch_user_profile.__name__ == "fetch_user_profile"
assert asyncio.run(fetch_user_profile("u9")) == {"id": "u9"}
def test_async_path_uses_async_sleep_never_blocking_sleep(clock: FakeClock) -> None:
def forbidden_sleep(_: float) -> None:
raise AssertionError("blocking sleep used on the async path")
limiter = RateLimiter(2.0, 1, clock=clock, sleep=forbidden_sleep, async_sleep=clock.async_sleep)
@rate_limited(limiter)
async def work() -> int:
return 1
async def main() -> list[int]:
return [await work(), await work()]
assert asyncio.run(main()) == [1, 1]
assert clock.sleeps == [pytest.approx(0.5)]
def test_async_non_blocking_and_timeout_errors(clock: FakeClock) -> None:
limiter = make_limiter(clock, rate=2.0, capacity=1)
async def main() -> None:
await limiter.acquire_async()
with pytest.raises(RateLimitExceeded):
await limiter.acquire_async(blocking=False)
with pytest.raises(RateLimitTimeout):
await limiter.acquire_async(timeout=0.1)
asyncio.run(main())
assert clock.sleeps == []
def test_async_callable_object_is_detected(clock: FakeClock) -> None:
limiter = make_limiter(clock)
class Client:
async def __call__(self, x: int) -> int:
return x * 2
wrapped = rate_limited(limiter)(Client())
assert inspect.iscoroutinefunction(wrapped)
assert asyncio.run(wrapped(21)) == 42
def test_async_wrapped_exceptions_propagate(clock: FakeClock) -> None:
limiter = make_limiter(clock)
@rate_limited(limiter)
async def explode() -> None:
raise LookupError("missing")
with pytest.raises(LookupError, match="missing"):
asyncio.run(explode())
def test_async_blocking_tasks_all_complete_in_order(clock: FakeClock) -> None:
limiter = make_limiter(clock, rate=10.0, capacity=2)
@rate_limited(limiter)
async def work(i: int) -> int:
return i * 2
async def main() -> list[int]:
return await asyncio.gather(*(work(i) for i in range(6)))
assert asyncio.run(main()) == [0, 2, 4, 6, 8, 10]
assert clock.sleeps # the burst was exhausted, so someone had to wait
# ------------------------------------------------------------ context managers
def test_sync_context_managers_consume_and_propagate(clock: FakeClock) -> None:
limiter = make_limiter(clock, capacity=1)
with limiter as entered:
assert entered is limiter
assert limiter.tokens_available() == 0.0
with pytest.raises(RateLimitExceeded):
with limiter.slot(blocking=False):
pass
with pytest.raises(KeyError):
with limiter.slot("other"):
raise KeyError("boom")
def test_async_context_managers_consume_and_propagate(clock: FakeClock) -> None:
limiter = make_limiter(clock, rate=1.0, capacity=1)
async def main() -> None:
async with limiter:
pass
async with limiter.slot(timeout=1.0): # waits 1s of virtual time
pass
with pytest.raises(RuntimeError):
async with limiter.slot("k"):
raise RuntimeError("body failed")
asyncio.run(main())
assert clock.sleeps == [pytest.approx(1.0)]
# ------------------------------------------------------------ concurrency
def test_concurrent_threads_never_overspend(clock: FakeClock) -> None:
limiter = make_limiter(clock, capacity=100) # clock frozen: no refill
barrier = threading.Barrier(8)
hits: list[int] = []
def worker() -> None:
barrier.wait()
hits.append(sum(limiter.try_acquire("shared") for _ in range(50)))
threads = [threading.Thread(target=worker) for _ in range(8)]
for t in threads:
t.start()
for t in threads:
t.join()
assert sum(hits) == 100
def test_concurrent_tasks_never_overspend(clock: FakeClock) -> None:
limiter = make_limiter(clock, capacity=5)
@rate_limited(limiter, blocking=False)
async def work(i: int) -> int:
await asyncio.sleep(0)
return i
async def main() -> list[int | BaseException]:
return await asyncio.gather(*(work(i) for i in range(20)), return_exceptions=True)
results = asyncio.run(main())
errors = [r for r in results if isinstance(r, BaseException)]
assert len(results) - len(errors) == 5
assert all(isinstance(e, RateLimitExceeded) for e in errors)
def test_threads_and_tasks_together_never_overspend(clock: FakeClock) -> None:
limiter = make_limiter(clock, capacity=200)
thread_hits: list[int] = []
def thread_worker() -> None:
thread_hits.append(sum(limiter.try_acquire() for _ in range(100)))
async def task_worker() -> int:
hits = 0
for _ in range(25):
try:
await limiter.acquire_async(blocking=False)
hits += 1
except RateLimitExceeded:
pass
await asyncio.sleep(0)
return hits
async def main() -> list[int]:
return await asyncio.gather(*(task_worker() for _ in range(4)))
threads = [threading.Thread(target=thread_worker) for _ in range(4)]
for t in threads:
t.start()
task_hits = asyncio.run(main())
for t in threads:
t.join()
assert sum(thread_hits) + sum(task_hits) == 200
Run it:
pytest -q test_token_bucket.py
python token_bucket.py # usage demo
5. Dependencies
There are no runtime dependencies, so no requirements.txt is needed. The only development tool is pytest, which is used to run the tests and is not imported by the library.
6. Design decisions
Why there is no external library (ratelimit, aiolimiter, limits). The constraint is stdlib only. Those libraries also do not match the requirements:
ratelimitis sync-only and uses fixed windows.aiolimiteris asyncio-only and is not thread-safe.limitsbrings storage backends we don't need.
None of them provides one object that is safe from threads and tasks at the same time, with per-key LRU buckets. The algorithm itself is about 20 lines of arithmetic, so a dependency would add supply-chain and versioning risk without saving any real work.
Lock strategy. One threading.Lock protects all state, and its critical sections never suspend. That makes it safe for both threads and tasks: a task cannot await while holding the lock, so tasks cannot deadlock each other on one loop. Thread contention is limited to O(1) work. All waiting happens outside the lock. The module docstring explains why a per-key asyncio.Lock would have been weaker: it is not thread-safe and is tied to one loop.
Retry instead of reservation. Waiters sleep for retry_after and then try again, rather than reserving a token in advance (negative balance). This has three benefits:
- A cancelled task never wastes a token.
tokens_available()stays within[0, capacity].- Timeouts can fail fast.
The trade-off is that waiters are not served in FIFO order, which is documented.
Injectable clock and sleep. Injection makes the tests deterministic and keeps the suite fast (well under a second) without touching globals. The default resolves time.monotonic at construction, so monkeypatching it also works.
Epsilon tolerance (1e-6 tokens). Accumulated floating-point error can leave a bucket at 0.9999999 tokens right after a sleep that should have refilled it. The tolerance prevents endless tiny retries in that case. Because the tolerance is so small, it cannot meaningfully raise throughput.
Complexity.
| Operation | Time | Notes |
|---|---|---|
try_acquire / one acquire attempt |
O(1) | One dict lookup, move_to_end, and at most one popitem (amortised O(1)). No allocation for existing keys |
| New key | O(1) | One small _Bucket with slots=True (two floats) |
| Blocking acquire | O(1) per attempt | Usually one attempt and one sleep; retries only happen under contention |
tokens_available |
O(1) | Read-only |
| Memory | O(min(active keys, max_keys)) |
Each bucket is two floats plus an OrderedDict entry. No growth beyond max_keys |
Related prompts
Professional Code Generator
Generates clean, well-documented, production-ready code from your requirements, following best practices in any language.
JavaScript & React Development Expert
Generates production-grade, typed React and JavaScript code with tests, accessibility, and clear architectural reasoning.
Code Review Expert
Performs a rigorous senior-level code review covering correctness, design, performance, and security with prioritized, actionable fixes.
SQL Query Optimizer
Diagnoses a slow SQL query and returns an optimized rewrite, index plan, and execution-plan reasoning.