API Reference¶
Complete API documentation for LLMRateLimiter.
Main Module¶
The main module exports all public classes and functions.
LLM Rate Limiter - Client-side rate limiting for LLM API calls.
This library provides FIFO queue-based rate limiting to prevent hitting provider rate limits (TPM/RPM) when calling LLM APIs.
Basic usage (recommended: specify input and output tokens separately): >>> from llmratelimiter import RateLimiter >>> >>> limiter = RateLimiter("redis://localhost:6379", "gpt-4", tpm=100_000, rpm=100) >>> await limiter.acquire(input_tokens=3000, output_tokens=2000) >>> response = await openai.chat.completions.create(...)
With existing Redis client
from llmratelimiter import RateLimiter from redis.asyncio import Redis
redis = Redis(host="localhost", port=6379) limiter = RateLimiter(redis=redis, model="gpt-4", tpm=100_000, rpm=100) await limiter.acquire(input_tokens=3000, output_tokens=2000)
With connection manager (includes retry with exponential backoff): >>> from llmratelimiter import RateLimiter, RedisConnectionManager, RetryConfig >>> >>> manager = RedisConnectionManager( ... "redis://localhost:6379", ... retry_config=RetryConfig(max_retries=3, base_delay=0.1), ... ) >>> limiter = RateLimiter(manager, "gpt-4", tpm=100_000, rpm=100) >>> await limiter.acquire(input_tokens=3000, output_tokens=2000)
Split mode example (GCP Vertex AI): >>> limiter = RateLimiter( ... "redis://localhost:6379", "gemini-1.5-pro", ... input_tpm=4_000_000, output_tpm=128_000, rpm=360 ... ) >>> result = await limiter.acquire(input_tokens=5000, output_tokens=2048) >>> response = await vertex_ai.generate(...) >>> await limiter.adjust(result.record_id, actual_output=response.output_tokens)
AWS Bedrock with burndown rate (output tokens count 5x toward TPM): >>> limiter = RateLimiter( ... "redis://localhost:6379", "claude-sonnet", ... tpm=100_000, rpm=100, burndown_rate=5.0 ... ) >>> await limiter.acquire(input_tokens=3000, output_tokens=1000) # TPM consumption: 3000 + (5.0 * 1000) = 8000 tokens
RateLimiter ¶
Unified rate limiter for LLM API calls.
Supports combined TPM, split TPM, or both based on the configuration.
Simple URL example
limiter = RateLimiter("redis://localhost:6379", "gpt-4", tpm=100_000, rpm=100) await limiter.acquire(tokens=5000)
Split mode example (GCP Vertex AI): >>> limiter = RateLimiter("redis://localhost", "gemini-1.5-pro", ... input_tpm=4_000_000, output_tpm=128_000, rpm=360) >>> result = await limiter.acquire(input_tokens=5000, output_tokens=2048) >>> await limiter.adjust(result.record_id, actual_output=1500)
With existing Redis client
limiter = RateLimiter(redis=existing_client, model="gpt-4", tpm=100_000, rpm=100)
With connection manager (includes retry support): >>> manager = RedisConnectionManager("redis://localhost", retry_config=RetryConfig()) >>> limiter = RateLimiter(manager, "gpt-4", tpm=100_000, rpm=100)
With config object (advanced): >>> config = RateLimitConfig(tpm=100_000, rpm=100, burst_multiplier=1.5) >>> limiter = RateLimiter("redis://localhost", "gpt-4", config=config)
AWS Bedrock with burndown rate (output tokens count 5x): >>> limiter = RateLimiter("redis://localhost", "claude-sonnet", ... tpm=100_000, rpm=100, burndown_rate=5.0) >>> await limiter.acquire(input_tokens=3000, output_tokens=1000) # TPM consumption: 3000 + (5.0 * 1000) = 8000 tokens
Azure OpenAI with RPS smoothing (burst prevention): >>> limiter = RateLimiter("redis://localhost", "gpt-4", ... tpm=300_000, rpm=600, smooth_requests=True) # Auto-calculates RPS = 600/60 = 10, enforces 100ms minimum gap
>>> limiter = RateLimiter("redis://localhost", "gpt-4",
... tpm=300_000, rpm=600, rps=8)
# Explicit RPS, auto-enables smoothing, enforces 125ms minimum gap
has_combined_limit
property
¶
Whether this limiter has a combined TPM limit.
is_split_mode
property
¶
Whether this limiter uses split input/output TPM limits.
__init__ ¶
__init__(
redis: RedisClient | None = None,
model: str | None = None,
config: RateLimitConfig | None = None,
*,
tpm: int = 0,
rpm: int = 0,
input_tpm: int = 0,
output_tpm: int = 0,
window_seconds: int = 60,
burst_multiplier: float = 1.0,
burndown_rate: float = 1.0,
smooth_requests: bool = True,
rps: int = 0,
smoothing_interval: float = 1.0,
password: str | None = None,
db: int = 0,
max_connections: int = 10,
retry_config: RetryConfig | None = None,
redis_client: Redis
| RedisConnectionManager
| None = None,
model_name: str | None = None,
) -> None
Initialize the rate limiter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redis
|
RedisClient | None
|
Redis URL string, async Redis client, or RedisConnectionManager. |
None
|
model
|
str | None
|
Name of the model (used for Redis key namespace). |
None
|
config
|
RateLimitConfig | None
|
Configuration for rate limits (optional if using kwargs). |
None
|
tpm
|
int
|
Combined tokens per minute limit. |
0
|
rpm
|
int
|
Requests per minute limit. |
0
|
input_tpm
|
int
|
Input tokens per minute limit (split mode). |
0
|
output_tpm
|
int
|
Output tokens per minute limit (split mode). |
0
|
window_seconds
|
int
|
Sliding window duration in seconds. |
60
|
burst_multiplier
|
float
|
Multiplier for burst capacity. |
1.0
|
burndown_rate
|
float
|
Output token multiplier for combined TPM (default 1.0). AWS Bedrock Claude models use 5.0. |
1.0
|
smooth_requests
|
bool
|
Enable RPS smoothing to prevent burst-triggered rate limits. When True, auto-calculates RPS from RPM. Default True. |
True
|
rps
|
int
|
Explicit requests-per-second limit. When set > 0, auto-enables smoothing. Set to 0 to auto-calculate from RPM when smooth_requests=True. |
0
|
smoothing_interval
|
float
|
Evaluation window in seconds for RPS enforcement. Azure uses 1.0s intervals. Default 1.0. |
1.0
|
password
|
str | None
|
Redis password (for URL connections). |
None
|
db
|
int
|
Redis database number (for URL connections). |
0
|
max_connections
|
int
|
Maximum connections in pool (for URL connections). |
10
|
retry_config
|
RetryConfig | None
|
Retry configuration for URL-based connections. |
None
|
redis_client
|
Redis | RedisConnectionManager | None
|
Deprecated, use 'redis' parameter. |
None
|
model_name
|
str | None
|
Deprecated, use 'model' parameter. |
None
|
acquire
async
¶
acquire(
*,
tokens: int | None = None,
input_tokens: int | None = None,
output_tokens: int = 0,
) -> AcquireResult
Acquire rate limit capacity.
For combined mode with pre-calculated tokens, use tokens parameter: await limiter.acquire(tokens=5000) # Burndown rate is NOT applied - value is used directly
For separate input/output tracking, use input_tokens/output_tokens: await limiter.acquire(input_tokens=5000, output_tokens=2048) # Burndown rate IS applied: effective = input + (burndown_rate * output)
With burndown rate (e.g., AWS Bedrock with burndown_rate=5.0): await limiter.acquire(input_tokens=3000, output_tokens=1000) # TPM consumption: 3000 + (5.0 * 1000) = 8000 tokens
Blocks until capacity is available (FIFO ordering), then returns. On Redis failure (after retries if configured), allows the request (graceful degradation).
Note: The burndown_rate is only applied when using input_tokens/output_tokens. When using the tokens= parameter, it is assumed the burndown calculation has already been done by the caller. Split input/output TPM limits are not affected by burndown_rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
int | None
|
Pre-calculated total tokens (burndown already applied if needed). |
None
|
input_tokens
|
int | None
|
Number of input tokens. |
None
|
output_tokens
|
int
|
Number of output tokens (default 0). |
0
|
Returns:
| Type | Description |
|---|---|
AcquireResult
|
AcquireResult with slot time, wait time, queue position, and record ID. |
adjust
async
¶
Adjust the output tokens for a consumption record.
Use this when the actual output tokens differ from the estimate. This frees up capacity if actual < estimated, or uses more if actual > estimated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record_id
|
str
|
The record ID from the acquire() result. |
required |
actual_output
|
int
|
The actual number of output tokens. |
required |
get_status
async
¶
Get current rate limit status.
Returns:
| Type | Description |
|---|---|
RateLimitStatus
|
RateLimitStatus with current usage and limits. |
RateLimitConfig
dataclass
¶
Unified configuration for rate limiting.
Supports combined TPM, split TPM, or both. Set unused limits to 0 to disable.
Combined mode only
RateLimitConfig(tpm=100_000, rpm=100)
Split mode only
RateLimitConfig(input_tpm=4_000_000, output_tpm=128_000, rpm=360)
Mixed mode (all three limits): RateLimitConfig(tpm=100_000, input_tpm=80_000, output_tpm=20_000, rpm=100) # Request must satisfy ALL constraints
Disabling limits
- Set rpm=0 to disable request rate limiting
- Set tpm=0 to disable combined token limiting
- Set input_tpm=0 or output_tpm=0 to disable that specific limit
Burndown rate (AWS Bedrock): RateLimitConfig(tpm=100_000, rpm=100, burndown_rate=5.0) # TPM consumption = input_tokens + (burndown_rate * output_tokens)
RPS smoothing (Azure OpenAI burst prevention): RateLimitConfig(tpm=300_000, rpm=600, smooth_requests=True) # Auto-calculates RPS = 600/60 = 10, enforces 100ms minimum gap
RateLimitConfig(tpm=300_000, rpm=600, rps=8)
# Explicit RPS, auto-enables smoothing, enforces 125ms minimum gap
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpm
|
int
|
Requests per minute limit. Set to 0 to disable. |
required |
tpm
|
int
|
Combined tokens per minute limit (input + output). Set to 0 to disable. |
0
|
input_tpm
|
int
|
Input tokens per minute limit. Set to 0 to disable. |
0
|
output_tpm
|
int
|
Output tokens per minute limit. Set to 0 to disable. |
0
|
window_seconds
|
int
|
Sliding window duration in seconds. |
60
|
burst_multiplier
|
float
|
Multiplier for burst capacity above base limits. |
1.0
|
burndown_rate
|
float
|
Output token multiplier for combined TPM (default 1.0). AWS Bedrock Claude models use 5.0. |
1.0
|
smooth_requests
|
bool
|
Enable RPS smoothing to prevent burst-triggered rate limits. When True, auto-calculates RPS from RPM. Default True. |
True
|
rps
|
int
|
Explicit requests-per-second limit. When set > 0, auto-enables smoothing. Set to 0 to auto-calculate from RPM when smooth_requests=True. |
0
|
smoothing_interval
|
float
|
Evaluation window in seconds for RPS enforcement. Azure uses 1.0s intervals. Default 1.0. |
1.0
|
effective_rps
property
¶
Calculate effective RPS limit.
Returns:
| Type | Description |
|---|---|
float
|
Explicit rps if set, otherwise rpm/60 if smoothing enabled, else 0. |
has_combined_limit
property
¶
Whether this config has a combined TPM limit.
is_smoothing_enabled
property
¶
Whether RPS smoothing is active.
Smoothing is enabled when either: - smooth_requests=True (auto-calculate RPS from RPM) - rps > 0 (explicit RPS, auto-enables smoothing)
is_split_mode
property
¶
Whether this config uses split input/output TPM limits.
RedisConnectionManager ¶
Manages Redis connections with pooling and retry support.
Example with URL
async with RedisConnectionManager("redis://localhost:6379") as manager: ... client = manager.client ... await client.ping()
Example with host/port: >>> manager = RedisConnectionManager( ... host="localhost", ... port=6379, ... retry_config=RetryConfig(max_retries=5, base_delay=0.2), ... ) >>> limiter = RateLimiter(manager, "gpt-4", tpm=100_000, rpm=100)
__init__ ¶
__init__(
url: str | None = None,
*,
host: str = "localhost",
port: int = 6379,
db: int = 0,
password: str | None = None,
max_connections: int = 10,
retry_config: RetryConfig | None = None,
decode_responses: bool = True,
**redis_kwargs: Any,
) -> None
Initialize the connection manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str | None
|
Redis URL (e.g., "redis://localhost:6379/0", "rediss://..." for SSL). |
None
|
host
|
str
|
Redis server hostname (used if url is not provided). |
'localhost'
|
port
|
int
|
Redis server port (used if url is not provided). |
6379
|
db
|
int
|
Redis database number. |
0
|
password
|
str | None
|
Redis password. |
None
|
max_connections
|
int
|
Maximum connections in the pool. |
10
|
retry_config
|
RetryConfig | None
|
Configuration for retry behavior. Defaults to RetryConfig(). |
None
|
decode_responses
|
bool
|
Whether to decode responses to strings. |
True
|
**redis_kwargs
|
Any
|
Additional arguments passed to Redis client. |
{}
|
RetryConfig
dataclass
¶
Configuration for retry behavior with exponential backoff.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_retries
|
int
|
Maximum number of retry attempts (0 = no retries). |
3
|
base_delay
|
float
|
Initial delay in seconds before first retry. |
0.1
|
max_delay
|
float
|
Maximum delay in seconds between retries. |
5.0
|
exponential_base
|
float
|
Multiplier for exponential backoff (delay * base^attempt). |
2.0
|
jitter
|
float
|
Random jitter factor (0.0 to 1.0) to prevent thundering herd. |
0.1
|
Example
config = RetryConfig(max_retries=3, base_delay=0.1)
Retry delays: ~0.1s, ~0.2s, ~0.4s (with jitter)¶
AcquireResult
dataclass
¶
Result from an acquire() call.
Attributes:
| Name | Type | Description |
|---|---|---|
slot_time |
float
|
The timestamp when the request is scheduled to execute. |
wait_time |
float
|
Time in seconds the caller waited (or will wait). |
queue_position |
int
|
Position in the FIFO queue (0 if immediate). |
record_id |
str
|
Unique ID for this consumption record (for adjust()). |
RateLimitStatus
dataclass
¶
Current status of a rate limiter.
Unified status for both combined and split mode limiters. Unused fields are set to 0.
Combined mode (tpm > 0): - tokens_used/tokens_limit contain combined token usage - input_tokens_used/input_tokens_limit are 0 - output_tokens_used/output_tokens_limit are 0
Split mode (input_tpm/output_tpm > 0): - tokens_used/tokens_limit are 0 - input_tokens_used/input_tokens_limit contain input token usage - output_tokens_used/output_tokens_limit contain output token usage
Attributes:
| Name | Type | Description |
|---|---|---|
model |
str
|
The model name this limiter is for. |
window_seconds |
int
|
The sliding window duration. |
tokens_used |
int
|
Current combined tokens consumed (combined mode). |
tokens_limit |
int
|
Maximum combined tokens allowed (combined mode). |
input_tokens_used |
int
|
Current input tokens consumed (split mode). |
input_tokens_limit |
int
|
Maximum input tokens allowed (split mode). |
output_tokens_used |
int
|
Current output tokens consumed (split mode). |
output_tokens_limit |
int
|
Maximum output tokens allowed (split mode). |
requests_used |
int
|
Current requests in the window. |
requests_limit |
int
|
Maximum requests allowed per window. |
queue_depth |
int
|
Number of pending requests (slot_time > now). |
Configuration¶
Configuration dataclasses for rate limits and retry behavior.
Configuration dataclasses for rate limiters.
RateLimitConfig
dataclass
¶
Unified configuration for rate limiting.
Supports combined TPM, split TPM, or both. Set unused limits to 0 to disable.
Combined mode only
RateLimitConfig(tpm=100_000, rpm=100)
Split mode only
RateLimitConfig(input_tpm=4_000_000, output_tpm=128_000, rpm=360)
Mixed mode (all three limits): RateLimitConfig(tpm=100_000, input_tpm=80_000, output_tpm=20_000, rpm=100) # Request must satisfy ALL constraints
Disabling limits
- Set rpm=0 to disable request rate limiting
- Set tpm=0 to disable combined token limiting
- Set input_tpm=0 or output_tpm=0 to disable that specific limit
Burndown rate (AWS Bedrock): RateLimitConfig(tpm=100_000, rpm=100, burndown_rate=5.0) # TPM consumption = input_tokens + (burndown_rate * output_tokens)
RPS smoothing (Azure OpenAI burst prevention): RateLimitConfig(tpm=300_000, rpm=600, smooth_requests=True) # Auto-calculates RPS = 600/60 = 10, enforces 100ms minimum gap
RateLimitConfig(tpm=300_000, rpm=600, rps=8)
# Explicit RPS, auto-enables smoothing, enforces 125ms minimum gap
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rpm
|
int
|
Requests per minute limit. Set to 0 to disable. |
required |
tpm
|
int
|
Combined tokens per minute limit (input + output). Set to 0 to disable. |
0
|
input_tpm
|
int
|
Input tokens per minute limit. Set to 0 to disable. |
0
|
output_tpm
|
int
|
Output tokens per minute limit. Set to 0 to disable. |
0
|
window_seconds
|
int
|
Sliding window duration in seconds. |
60
|
burst_multiplier
|
float
|
Multiplier for burst capacity above base limits. |
1.0
|
burndown_rate
|
float
|
Output token multiplier for combined TPM (default 1.0). AWS Bedrock Claude models use 5.0. |
1.0
|
smooth_requests
|
bool
|
Enable RPS smoothing to prevent burst-triggered rate limits. When True, auto-calculates RPS from RPM. Default True. |
True
|
rps
|
int
|
Explicit requests-per-second limit. When set > 0, auto-enables smoothing. Set to 0 to auto-calculate from RPM when smooth_requests=True. |
0
|
smoothing_interval
|
float
|
Evaluation window in seconds for RPS enforcement. Azure uses 1.0s intervals. Default 1.0. |
1.0
|
Source code in src/llmratelimiter/config.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | |
effective_rps
property
¶
Calculate effective RPS limit.
Returns:
| Type | Description |
|---|---|
float
|
Explicit rps if set, otherwise rpm/60 if smoothing enabled, else 0. |
has_combined_limit
property
¶
Whether this config has a combined TPM limit.
is_smoothing_enabled
property
¶
Whether RPS smoothing is active.
Smoothing is enabled when either: - smooth_requests=True (auto-calculate RPS from RPM) - rps > 0 (explicit RPS, auto-enables smoothing)
is_split_mode
property
¶
Whether this config uses split input/output TPM limits.
__post_init__ ¶
Validate configuration values.
Source code in src/llmratelimiter/config.py
RetryConfig
dataclass
¶
Configuration for retry behavior with exponential backoff.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_retries
|
int
|
Maximum number of retry attempts (0 = no retries). |
3
|
base_delay
|
float
|
Initial delay in seconds before first retry. |
0.1
|
max_delay
|
float
|
Maximum delay in seconds between retries. |
5.0
|
exponential_base
|
float
|
Multiplier for exponential backoff (delay * base^attempt). |
2.0
|
jitter
|
float
|
Random jitter factor (0.0 to 1.0) to prevent thundering herd. |
0.1
|
Example
config = RetryConfig(max_retries=3, base_delay=0.1)
Retry delays: ~0.1s, ~0.2s, ~0.4s (with jitter)¶
Source code in src/llmratelimiter/config.py
__post_init__ ¶
Validate configuration values.
Source code in src/llmratelimiter/config.py
Connection Management¶
Redis connection pooling and retry logic.
Redis connection management with pooling and retry support.
RedisConnectionManager ¶
Manages Redis connections with pooling and retry support.
Example with URL
async with RedisConnectionManager("redis://localhost:6379") as manager: ... client = manager.client ... await client.ping()
Example with host/port: >>> manager = RedisConnectionManager( ... host="localhost", ... port=6379, ... retry_config=RetryConfig(max_retries=5, base_delay=0.2), ... ) >>> limiter = RateLimiter(manager, "gpt-4", tpm=100_000, rpm=100)
Source code in src/llmratelimiter/connection.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
__aenter__
async
¶
__aexit__
async
¶
__init__ ¶
__init__(
url: str | None = None,
*,
host: str = "localhost",
port: int = 6379,
db: int = 0,
password: str | None = None,
max_connections: int = 10,
retry_config: RetryConfig | None = None,
decode_responses: bool = True,
**redis_kwargs: Any,
) -> None
Initialize the connection manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str | None
|
Redis URL (e.g., "redis://localhost:6379/0", "rediss://..." for SSL). |
None
|
host
|
str
|
Redis server hostname (used if url is not provided). |
'localhost'
|
port
|
int
|
Redis server port (used if url is not provided). |
6379
|
db
|
int
|
Redis database number. |
0
|
password
|
str | None
|
Redis password. |
None
|
max_connections
|
int
|
Maximum connections in the pool. |
10
|
retry_config
|
RetryConfig | None
|
Configuration for retry behavior. Defaults to RetryConfig(). |
None
|
decode_responses
|
bool
|
Whether to decode responses to strings. |
True
|
**redis_kwargs
|
Any
|
Additional arguments passed to Redis client. |
{}
|
Source code in src/llmratelimiter/connection.py
close
async
¶
Close all connections in the pool.
Source code in src/llmratelimiter/connection.py
calculate_delay ¶
Calculate delay for a retry attempt with exponential backoff and jitter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attempt
|
int
|
The retry attempt number (0-indexed). |
required |
config
|
RetryConfig
|
Retry configuration. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Delay in seconds before the next retry. |
Source code in src/llmratelimiter/connection.py
retry_with_backoff
async
¶
retry_with_backoff(
operation: Callable[[], Awaitable[T]],
config: RetryConfig,
operation_name: str = "operation",
) -> T
Execute an async operation with exponential backoff retry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
operation
|
Callable[[], Awaitable[T]]
|
Async callable to execute. |
required |
config
|
RetryConfig
|
Retry configuration. |
required |
operation_name
|
str
|
Name for logging purposes. |
'operation'
|
Returns:
| Type | Description |
|---|---|
T
|
Result of the operation. |
Raises:
| Type | Description |
|---|---|
Exception
|
The last exception if all retries are exhausted. |
Source code in src/llmratelimiter/connection.py
Rate Limiter¶
The main rate limiter implementation.
Unified rate limiter implementation.
RateLimiter ¶
Unified rate limiter for LLM API calls.
Supports combined TPM, split TPM, or both based on the configuration.
Simple URL example
limiter = RateLimiter("redis://localhost:6379", "gpt-4", tpm=100_000, rpm=100) await limiter.acquire(tokens=5000)
Split mode example (GCP Vertex AI): >>> limiter = RateLimiter("redis://localhost", "gemini-1.5-pro", ... input_tpm=4_000_000, output_tpm=128_000, rpm=360) >>> result = await limiter.acquire(input_tokens=5000, output_tokens=2048) >>> await limiter.adjust(result.record_id, actual_output=1500)
With existing Redis client
limiter = RateLimiter(redis=existing_client, model="gpt-4", tpm=100_000, rpm=100)
With connection manager (includes retry support): >>> manager = RedisConnectionManager("redis://localhost", retry_config=RetryConfig()) >>> limiter = RateLimiter(manager, "gpt-4", tpm=100_000, rpm=100)
With config object (advanced): >>> config = RateLimitConfig(tpm=100_000, rpm=100, burst_multiplier=1.5) >>> limiter = RateLimiter("redis://localhost", "gpt-4", config=config)
AWS Bedrock with burndown rate (output tokens count 5x): >>> limiter = RateLimiter("redis://localhost", "claude-sonnet", ... tpm=100_000, rpm=100, burndown_rate=5.0) >>> await limiter.acquire(input_tokens=3000, output_tokens=1000) # TPM consumption: 3000 + (5.0 * 1000) = 8000 tokens
Azure OpenAI with RPS smoothing (burst prevention): >>> limiter = RateLimiter("redis://localhost", "gpt-4", ... tpm=300_000, rpm=600, smooth_requests=True) # Auto-calculates RPS = 600/60 = 10, enforces 100ms minimum gap
>>> limiter = RateLimiter("redis://localhost", "gpt-4",
... tpm=300_000, rpm=600, rps=8)
# Explicit RPS, auto-enables smoothing, enforces 125ms minimum gap
Source code in src/llmratelimiter/limiter.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
has_combined_limit
property
¶
Whether this limiter has a combined TPM limit.
is_split_mode
property
¶
Whether this limiter uses split input/output TPM limits.
__init__ ¶
__init__(
redis: RedisClient | None = None,
model: str | None = None,
config: RateLimitConfig | None = None,
*,
tpm: int = 0,
rpm: int = 0,
input_tpm: int = 0,
output_tpm: int = 0,
window_seconds: int = 60,
burst_multiplier: float = 1.0,
burndown_rate: float = 1.0,
smooth_requests: bool = True,
rps: int = 0,
smoothing_interval: float = 1.0,
password: str | None = None,
db: int = 0,
max_connections: int = 10,
retry_config: RetryConfig | None = None,
redis_client: Redis
| RedisConnectionManager
| None = None,
model_name: str | None = None,
) -> None
Initialize the rate limiter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redis
|
RedisClient | None
|
Redis URL string, async Redis client, or RedisConnectionManager. |
None
|
model
|
str | None
|
Name of the model (used for Redis key namespace). |
None
|
config
|
RateLimitConfig | None
|
Configuration for rate limits (optional if using kwargs). |
None
|
tpm
|
int
|
Combined tokens per minute limit. |
0
|
rpm
|
int
|
Requests per minute limit. |
0
|
input_tpm
|
int
|
Input tokens per minute limit (split mode). |
0
|
output_tpm
|
int
|
Output tokens per minute limit (split mode). |
0
|
window_seconds
|
int
|
Sliding window duration in seconds. |
60
|
burst_multiplier
|
float
|
Multiplier for burst capacity. |
1.0
|
burndown_rate
|
float
|
Output token multiplier for combined TPM (default 1.0). AWS Bedrock Claude models use 5.0. |
1.0
|
smooth_requests
|
bool
|
Enable RPS smoothing to prevent burst-triggered rate limits. When True, auto-calculates RPS from RPM. Default True. |
True
|
rps
|
int
|
Explicit requests-per-second limit. When set > 0, auto-enables smoothing. Set to 0 to auto-calculate from RPM when smooth_requests=True. |
0
|
smoothing_interval
|
float
|
Evaluation window in seconds for RPS enforcement. Azure uses 1.0s intervals. Default 1.0. |
1.0
|
password
|
str | None
|
Redis password (for URL connections). |
None
|
db
|
int
|
Redis database number (for URL connections). |
0
|
max_connections
|
int
|
Maximum connections in pool (for URL connections). |
10
|
retry_config
|
RetryConfig | None
|
Retry configuration for URL-based connections. |
None
|
redis_client
|
Redis | RedisConnectionManager | None
|
Deprecated, use 'redis' parameter. |
None
|
model_name
|
str | None
|
Deprecated, use 'model' parameter. |
None
|
Source code in src/llmratelimiter/limiter.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
acquire
async
¶
acquire(
*,
tokens: int | None = None,
input_tokens: int | None = None,
output_tokens: int = 0,
) -> AcquireResult
Acquire rate limit capacity.
For combined mode with pre-calculated tokens, use tokens parameter: await limiter.acquire(tokens=5000) # Burndown rate is NOT applied - value is used directly
For separate input/output tracking, use input_tokens/output_tokens: await limiter.acquire(input_tokens=5000, output_tokens=2048) # Burndown rate IS applied: effective = input + (burndown_rate * output)
With burndown rate (e.g., AWS Bedrock with burndown_rate=5.0): await limiter.acquire(input_tokens=3000, output_tokens=1000) # TPM consumption: 3000 + (5.0 * 1000) = 8000 tokens
Blocks until capacity is available (FIFO ordering), then returns. On Redis failure (after retries if configured), allows the request (graceful degradation).
Note: The burndown_rate is only applied when using input_tokens/output_tokens. When using the tokens= parameter, it is assumed the burndown calculation has already been done by the caller. Split input/output TPM limits are not affected by burndown_rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
int | None
|
Pre-calculated total tokens (burndown already applied if needed). |
None
|
input_tokens
|
int | None
|
Number of input tokens. |
None
|
output_tokens
|
int
|
Number of output tokens (default 0). |
0
|
Returns:
| Type | Description |
|---|---|
AcquireResult
|
AcquireResult with slot time, wait time, queue position, and record ID. |
Source code in src/llmratelimiter/limiter.py
adjust
async
¶
Adjust the output tokens for a consumption record.
Use this when the actual output tokens differ from the estimate. This frees up capacity if actual < estimated, or uses more if actual > estimated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record_id
|
str
|
The record ID from the acquire() result. |
required |
actual_output
|
int
|
The actual number of output tokens. |
required |
Source code in src/llmratelimiter/limiter.py
get_status
async
¶
Get current rate limit status.
Returns:
| Type | Description |
|---|---|
RateLimitStatus
|
RateLimitStatus with current usage and limits. |
Source code in src/llmratelimiter/limiter.py
Models¶
Data models for results and status.
Result dataclasses for rate limiter operations.
AcquireResult
dataclass
¶
Result from an acquire() call.
Attributes:
| Name | Type | Description |
|---|---|---|
slot_time |
float
|
The timestamp when the request is scheduled to execute. |
wait_time |
float
|
Time in seconds the caller waited (or will wait). |
queue_position |
int
|
Position in the FIFO queue (0 if immediate). |
record_id |
str
|
Unique ID for this consumption record (for adjust()). |
Source code in src/llmratelimiter/models.py
RateLimitStatus
dataclass
¶
Current status of a rate limiter.
Unified status for both combined and split mode limiters. Unused fields are set to 0.
Combined mode (tpm > 0): - tokens_used/tokens_limit contain combined token usage - input_tokens_used/input_tokens_limit are 0 - output_tokens_used/output_tokens_limit are 0
Split mode (input_tpm/output_tpm > 0): - tokens_used/tokens_limit are 0 - input_tokens_used/input_tokens_limit contain input token usage - output_tokens_used/output_tokens_limit contain output token usage
Attributes:
| Name | Type | Description |
|---|---|---|
model |
str
|
The model name this limiter is for. |
window_seconds |
int
|
The sliding window duration. |
tokens_used |
int
|
Current combined tokens consumed (combined mode). |
tokens_limit |
int
|
Maximum combined tokens allowed (combined mode). |
input_tokens_used |
int
|
Current input tokens consumed (split mode). |
input_tokens_limit |
int
|
Maximum input tokens allowed (split mode). |
output_tokens_used |
int
|
Current output tokens consumed (split mode). |
output_tokens_limit |
int
|
Maximum output tokens allowed (split mode). |
requests_used |
int
|
Current requests in the window. |
requests_limit |
int
|
Maximum requests allowed per window. |
queue_depth |
int
|
Number of pending requests (slot_time > now). |