or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async.mdindex.mdrate-limit-items.mdstorage.mdstrategies.mdutilities.md

rate-limit-items.mddocs/

0

# Rate Limit Items

1

2

Rate limit items define the parameters for rate limiting including the limit amount, time window granularity, and optional namespace for categorization. Each item represents a specific rate limit configuration that can be applied to different identifiers.

3

4

## Capabilities

5

6

### Base Rate Limit Item

7

8

The foundational class for all rate limit items, providing common functionality for key generation, expiry calculation, and granularity matching.

9

10

```python { .api }

11

class RateLimitItem:

12

"""Base class for rate limit items with configurable granularity"""

13

14

def __init__(self, amount: int, multiples: int | None = 1, namespace: str = "LIMITER"):

15

"""

16

Initialize a rate limit item.

17

18

Args:

19

amount: The rate limit amount (number of requests allowed)

20

multiples: Multiple of the granularity period (default: 1)

21

namespace: Category for the specific rate limit (default: "LIMITER")

22

"""

23

24

def get_expiry(self) -> int:

25

"""

26

Get the duration the limit is enforced for in seconds.

27

28

Returns:

29

Duration in seconds based on granularity and multiples

30

"""

31

32

def key_for(self, *identifiers: str | int | float | bytes) -> str:

33

"""

34

Construct a key for the current limit and identifiers.

35

36

Args:

37

identifiers: List of values to append to the key for uniqueness

38

39

Returns:

40

String key identifying this resource with identifiers

41

"""

42

43

@classmethod

44

def check_granularity_string(cls, granularity_string: str) -> bool:

45

"""

46

Check if this class matches a granularity string.

47

48

Args:

49

granularity_string: String like "second", "minute", etc.

50

51

Returns:

52

True if the granularity matches this item type

53

"""

54

```

55

56

### Time-Based Rate Limit Items

57

58

Concrete implementations for different time granularities, each with predefined time periods.

59

60

```python { .api }

61

class RateLimitItemPerSecond(RateLimitItem):

62

"""Rate limit item with 1-second granularity"""

63

GRANULARITY: Granularity # (1, "second")

64

65

class RateLimitItemPerMinute(RateLimitItem):

66

"""Rate limit item with 1-minute granularity"""

67

GRANULARITY: Granularity # (60, "minute")

68

69

class RateLimitItemPerHour(RateLimitItem):

70

"""Rate limit item with 1-hour granularity"""

71

GRANULARITY: Granularity # (3600, "hour")

72

73

class RateLimitItemPerDay(RateLimitItem):

74

"""Rate limit item with 1-day granularity"""

75

GRANULARITY: Granularity # (86400, "day")

76

77

class RateLimitItemPerMonth(RateLimitItem):

78

"""Rate limit item with 1-month granularity (30 days)"""

79

GRANULARITY: Granularity # (2592000, "month")

80

81

class RateLimitItemPerYear(RateLimitItem):

82

"""Rate limit item with 1-year granularity (365 days)"""

83

GRANULARITY: Granularity # (31104000, "year")

84

```

85

86

## Usage Examples

87

88

### Creating Rate Limit Items

89

90

```python

91

from limits import (

92

RateLimitItemPerSecond,

93

RateLimitItemPerMinute,

94

RateLimitItemPerHour,

95

RateLimitItemPerDay

96

)

97

98

# Simple rate limits

99

requests_per_second = RateLimitItemPerSecond(10) # 10 requests per second

100

api_calls_per_minute = RateLimitItemPerMinute(100) # 100 calls per minute

101

uploads_per_hour = RateLimitItemPerHour(50) # 50 uploads per hour

102

downloads_per_day = RateLimitItemPerDay(1000) # 1000 downloads per day

103

104

# Rate limits with custom time multiples

105

burst_limit = RateLimitItemPerSecond(20, multiples=5) # 20 requests per 5 seconds

106

weekly_limit = RateLimitItemPerDay(7000, multiples=7) # 7000 requests per 7 days

107

108

# Rate limits with custom namespaces

109

user_api_limit = RateLimitItemPerMinute(60, namespace="USER_API")

110

admin_api_limit = RateLimitItemPerMinute(300, namespace="ADMIN_API")

111

```

112

113

### Working with Rate Limit Keys

114

115

```python

116

from limits import RateLimitItemPerMinute

117

118

# Create a rate limit item

119

rate_limit = RateLimitItemPerMinute(100, namespace="API")

120

121

# Generate keys for different identifiers

122

user_key = rate_limit.key_for("user", "12345")

123

# Returns: "API/user/12345/100/1/minute"

124

125

ip_key = rate_limit.key_for("192.168.1.1")

126

# Returns: "API/192.168.1.1/100/1/minute"

127

128

endpoint_key = rate_limit.key_for("endpoint", "/api/users", "POST")

129

# Returns: "API/endpoint//api/users/POST/100/1/minute"

130

131

# Check expiry duration

132

expiry_seconds = rate_limit.get_expiry() # Returns: 60

133

```

134

135

### Granularity Checking

136

137

```python

138

from limits import RateLimitItemPerMinute, RateLimitItemPerHour

139

140

# Check if rate limit items match granularity strings

141

minute_item = RateLimitItemPerMinute(10)

142

hour_item = RateLimitItemPerHour(100)

143

144

print(minute_item.check_granularity_string("minute")) # True

145

print(minute_item.check_granularity_string("hour")) # False

146

print(hour_item.check_granularity_string("hour")) # True

147

```

148

149

## Constants and Types

150

151

```python { .api }

152

from typing import NamedTuple

153

154

class Granularity(NamedTuple):

155

"""Defines a time granularity"""

156

seconds: int # Duration in seconds

157

name: str # Human-readable name

158

159

# Predefined time granularities

160

TIME_TYPES: dict[str, Granularity] = {

161

"second": Granularity(1, "second"),

162

"minute": Granularity(60, "minute"),

163

"hour": Granularity(3600, "hour"),

164

"day": Granularity(86400, "day"),

165

"month": Granularity(2592000, "month"), # 30 days

166

"year": Granularity(31104000, "year") # 365 days

167

}

168

169

# Registry mapping granularity names to rate limit classes

170

GRANULARITIES: dict[str, type[RateLimitItem]]

171

```