0
# Rate Configuration
1
2
Rate definition and duration utilities for configuring rate limits with flexible time intervals and validation. The Rate class defines the core rate limiting rules while Duration provides convenient time constants.
3
4
## Capabilities
5
6
### Rate Definition
7
8
Core class for defining rate limit rules with limit and interval parameters.
9
10
```python { .api }
11
class Rate:
12
def __init__(self, limit: int, interval: Union[int, Duration]):
13
"""
14
Define a rate limit rule.
15
16
Parameters:
17
- limit: Number of requests allowed within the interval
18
- interval: Time interval in milliseconds (or Duration enum)
19
20
Properties:
21
- limit: int - Maximum number of requests
22
- interval: int - Time interval in milliseconds
23
"""
24
25
def __str__(self) -> str:
26
"""Human-readable rate representation."""
27
28
def __repr__(self) -> str:
29
"""Developer representation of rate."""
30
```
31
32
Usage example:
33
34
```python
35
from pyrate_limiter import Rate, Duration
36
37
# Basic rate definitions
38
rate1 = Rate(10, Duration.SECOND) # 10 requests per second
39
rate2 = Rate(100, Duration.MINUTE) # 100 requests per minute
40
rate3 = Rate(1000, Duration.HOUR) # 1000 requests per hour
41
42
# Using milliseconds directly
43
rate4 = Rate(5, 1000) # 5 requests per 1000ms (1 second)
44
45
# Multiple rates for complex limiting
46
rates = [
47
Rate(10, Duration.SECOND), # Burst protection
48
Rate(100, Duration.MINUTE), # Short-term limit
49
Rate(1000, Duration.HOUR), # Long-term limit
50
]
51
52
print(str(rate1)) # "limit=10/1.0s"
53
print(str(rate2)) # "limit=100/1.0m"
54
```
55
56
### Duration Constants
57
58
Convenient time interval constants with arithmetic operations support.
59
60
```python { .api }
61
class Duration(Enum):
62
SECOND = 1000
63
MINUTE = 60000
64
HOUR = 3600000
65
DAY = 86400000
66
WEEK = 604800000
67
68
def __mul__(self, multiplier: float) -> int:
69
"""Multiply duration by a factor."""
70
71
def __rmul__(self, multiplier: float) -> int:
72
"""Reverse multiply duration by a factor."""
73
74
def __add__(self, another_duration: Union["Duration", int]) -> int:
75
"""Add duration to another duration or integer."""
76
77
def __radd__(self, another_duration: Union["Duration", int]) -> int:
78
"""Reverse add duration to another duration or integer."""
79
80
def __int__(self) -> int:
81
"""Convert duration to integer milliseconds."""
82
83
def __eq__(self, duration: object) -> bool:
84
"""Compare duration equality."""
85
86
@staticmethod
87
def readable(value: int) -> str:
88
"""Convert milliseconds to human-readable format."""
89
```
90
91
Usage example:
92
93
```python
94
from pyrate_limiter import Duration, Rate
95
96
# Basic duration usage
97
print(Duration.SECOND) # Duration.SECOND
98
print(int(Duration.SECOND)) # 1000
99
print(Duration.MINUTE) # Duration.MINUTE
100
print(int(Duration.MINUTE)) # 60000
101
102
# Arithmetic operations
103
half_minute = Duration.MINUTE * 0.5 # 30000ms
104
two_hours = Duration.HOUR * 2 # 7200000ms
105
day_and_hour = Duration.DAY + Duration.HOUR # 90000000ms
106
107
# Using with Rate
108
rate = Rate(50, Duration.MINUTE * 5) # 50 requests per 5 minutes
109
rate = Rate(10, Duration.SECOND * 30) # 10 requests per 30 seconds
110
111
# Human-readable formatting
112
print(Duration.readable(1000)) # "1.0s"
113
print(Duration.readable(60000)) # "1.0m"
114
print(Duration.readable(3600000)) # "1.0h"
115
print(Duration.readable(86400000)) # "1.0d"
116
print(Duration.readable(1500)) # "1.5s"
117
```
118
119
### Rate Item
120
121
Wrapper class for individual rate-limited items with timestamps and weights.
122
123
```python { .api }
124
class RateItem:
125
def __init__(self, name: str, timestamp: int, weight: int = 1):
126
"""
127
Create a rate-limited item.
128
129
Parameters:
130
- name: Identifier for the item/resource
131
- timestamp: Timestamp in milliseconds
132
- weight: Weight/cost of the item (default: 1)
133
134
Properties:
135
- name: str - Item identifier
136
- timestamp: int - Item timestamp in milliseconds
137
- weight: int - Item weight/cost
138
"""
139
140
def __str__(self) -> str:
141
"""String representation of rate item."""
142
```
143
144
Usage example:
145
146
```python
147
from pyrate_limiter import RateItem
148
import time
149
150
# Create rate items
151
current_time = int(time.time() * 1000)
152
item1 = RateItem("user123", current_time)
153
item2 = RateItem("expensive_op", current_time, weight=5)
154
155
print(item1) # RateItem(name=user123, weight=1, timestamp=...)
156
print(item2) # RateItem(name=expensive_op, weight=5, timestamp=...)
157
158
# Rate items are used internally by Limiter
159
# but can be created manually for advanced use cases
160
```
161
162
### Rate Validation
163
164
Utility function for validating rate list ordering and consistency.
165
166
```python { .api }
167
def validate_rate_list(rates: List[Rate]) -> bool:
168
"""
169
Raise false if rates are incorrectly ordered.
170
171
Parameters:
172
- rates: List of rate configurations to validate
173
174
Returns:
175
- bool: True if rates are valid, False otherwise
176
177
Validation rules:
178
- Intervals must be in ascending order
179
- Limits must be in ascending order
180
- Rate ratios (limit/interval) must be in descending order
181
"""
182
```
183
184
Usage example:
185
186
```python
187
from pyrate_limiter import Rate, Duration, validate_rate_list
188
189
# Valid rate list (intervals and limits ascending, ratios descending)
190
valid_rates = [
191
Rate(10, Duration.SECOND), # 10/1000ms = 0.01 req/ms
192
Rate(100, Duration.MINUTE), # 100/60000ms = 0.00167 req/ms
193
Rate(1000, Duration.HOUR), # 1000/3600000ms = 0.00028 req/ms
194
]
195
196
# Invalid rate list
197
invalid_rates = [
198
Rate(100, Duration.MINUTE), # Wrong order
199
Rate(10, Duration.SECOND),
200
]
201
202
print(validate_rate_list(valid_rates)) # True
203
print(validate_rate_list(invalid_rates)) # False
204
```
205
206
## Advanced Rate Patterns
207
208
### Burst and Sustained Rates
209
210
Combine short and long interval rates for burst protection with sustained limits.
211
212
```python
213
from pyrate_limiter import Rate, Duration
214
215
# Allow bursts of 10/second but limit to 100/minute overall
216
burst_and_sustained = [
217
Rate(10, Duration.SECOND), # Burst protection
218
Rate(100, Duration.MINUTE), # Sustained rate
219
]
220
```
221
222
### Fractional Rates
223
224
Use multiplication for fractional rates.
225
226
```python
227
from pyrate_limiter import Rate, Duration
228
229
# 1 request every 2 seconds (0.5 requests per second)
230
slow_rate = Rate(1, Duration.SECOND * 2)
231
232
# 30 requests every 30 seconds (1 request per second average)
233
averaged_rate = Rate(30, Duration.SECOND * 30)
234
```
235
236
### Weighted Operations
237
238
Different operations can have different weights/costs.
239
240
```python
241
from pyrate_limiter import Limiter, Rate, Duration
242
243
limiter = Limiter(Rate(100, Duration.MINUTE))
244
245
# Light operations (weight=1, default)
246
limiter.try_acquire("read_operation")
247
248
# Heavy operations (weight=10)
249
limiter.try_acquire("expensive_computation", weight=10)
250
251
# Bulk operations (weight=50)
252
limiter.try_acquire("batch_processing", weight=50)
253
```