Rate limiting
provide.foundation.utils.rate_limiting
¶
TODO: Add module docstring.
Classes¶
TokenBucketRateLimiter
¶
TokenBucketRateLimiter(
capacity: float,
refill_rate: float,
time_source: Callable[[], float] | None = None,
)
A Token Bucket rate limiter for asyncio applications.
This limiter allows for bursts up to a specified capacity and refills tokens at a constant rate. It is designed to be thread-safe using an asyncio.Lock.
Initialize the TokenBucketRateLimiter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
capacity
|
float
|
The maximum number of tokens the bucket can hold (burst capacity). |
required |
refill_rate
|
float
|
The rate at which tokens are refilled per second. |
required |
time_source
|
Callable[[], float] | None
|
Optional callable that returns current time (for testing). Defaults to time.monotonic. |
None
|
Source code in provide/foundation/utils/rate_limiting.py
Functions¶
get_current_tokens
async
¶
Returns the current number of tokens, for testing/monitoring.
Source code in provide/foundation/utils/rate_limiting.py
is_allowed
async
¶
Check if a request is allowed based on available tokens.
This method is asynchronous and thread-safe. It refills tokens based on elapsed time and then attempts to consume a token.
Returns:
| Type | Description |
|---|---|
bool
|
True if the request is allowed, False otherwise. |