@upstash/ratelimit 2.2.0 → 2.2.1-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/index.d.mts +30 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +23 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +23 -1
- package/dist/index.mjs.map +1 -1
- package/docs/algorithms.mdx +169 -0
- package/docs/costs.mdx +112 -0
- package/docs/features.mdx +262 -0
- package/docs/gettingstarted.mdx +220 -0
- package/docs/methods.mdx +206 -0
- package/docs/overview.mdx +159 -0
- package/docs/traffic-protection.mdx +110 -0
- package/package.json +1 -1
- package/src/analytics.ts +110 -0
- package/src/cache.ts +55 -0
- package/src/constants.ts +14 -0
- package/src/deny-list/deny-list.ts +124 -0
- package/src/deny-list/index.ts +1 -0
- package/src/deny-list/ip-deny-list.ts +131 -0
- package/src/deny-list/scripts.ts +26 -0
- package/src/deny-list/time.ts +20 -0
- package/src/duration.ts +37 -0
- package/src/hash.ts +29 -0
- package/src/index.ts +18 -0
- package/src/lua-scripts/hash.ts +95 -0
- package/src/lua-scripts/multi.ts +86 -0
- package/src/lua-scripts/reset.ts +23 -0
- package/src/lua-scripts/single.ts +237 -0
- package/src/multi.ts +610 -0
- package/src/ratelimit.ts +506 -0
- package/src/single.ts +676 -0
- package/src/telemetry.ts +43 -0
- package/src/types.ts +132 -0
- package/src/version.ts +1 -0
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Ratelimit TypeScript SDK Algorithms
|
|
3
|
+
sidebarTitle: Ratelimiting Algorithms
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
We provide different algorithms to use out of the box. Each has pros and cons.
|
|
7
|
+
|
|
8
|
+
## Fixed Window
|
|
9
|
+
|
|
10
|
+
This algorithm divides time into fixed durations/windows. For example each
|
|
11
|
+
window is 10 seconds long. When a new request comes in, the current time is used
|
|
12
|
+
to determine the window and a counter is increased. If the counter is larger
|
|
13
|
+
than the set limit, the request is rejected.
|
|
14
|
+
|
|
15
|
+
<Tip>
|
|
16
|
+
In fixed & sliding window algorithms, the reset time is based on fixed time boundaries (which depend on the period), not on when the first request was made. So two requests made right before the window ends still count toward the current window, and limits reset at the start of the next window.
|
|
17
|
+
</Tip>
|
|
18
|
+
|
|
19
|
+
### Pros
|
|
20
|
+
|
|
21
|
+
- Very cheap in terms of data size and computation
|
|
22
|
+
- Newer requests are not starved due to a high burst in the past
|
|
23
|
+
- Supports [dynamic limits](/redis/sdks/ratelimit-ts/features#dynamic-limits)
|
|
24
|
+
|
|
25
|
+
### Cons
|
|
26
|
+
|
|
27
|
+
- Can cause high bursts at the window boundaries to leak through
|
|
28
|
+
- Causes request stampedes if many users are trying to access your server,
|
|
29
|
+
whenever a new window begins
|
|
30
|
+
|
|
31
|
+
### Usage
|
|
32
|
+
|
|
33
|
+
Create a new ratelimiter, that allows 10 requests per 10 seconds.
|
|
34
|
+
|
|
35
|
+
<Tabs>
|
|
36
|
+
<Tab title="Regional">
|
|
37
|
+
```ts
|
|
38
|
+
const ratelimit = new Ratelimit({
|
|
39
|
+
redis: Redis.fromEnv(),
|
|
40
|
+
limiter: Ratelimit.fixedWindow(10, "10 s"),
|
|
41
|
+
});
|
|
42
|
+
```
|
|
43
|
+
</Tab>
|
|
44
|
+
<Tab title="Multi Regional">
|
|
45
|
+
```ts
|
|
46
|
+
const ratelimit = new MultiRegionRatelimit({
|
|
47
|
+
redis: [
|
|
48
|
+
new Redis({
|
|
49
|
+
/* auth */
|
|
50
|
+
}),
|
|
51
|
+
new Redis({
|
|
52
|
+
/* auth */
|
|
53
|
+
})
|
|
54
|
+
],
|
|
55
|
+
limiter: MultiRegionRatelimit.fixedWindow(10, "10 s"),
|
|
56
|
+
});
|
|
57
|
+
```
|
|
58
|
+
</Tab>
|
|
59
|
+
</Tabs>
|
|
60
|
+
|
|
61
|
+
## Sliding Window
|
|
62
|
+
|
|
63
|
+
Builds on top of fixed window but instead of a fixed window, we use a rolling
|
|
64
|
+
window. Take this example: We have a rate limit of 10 requests per 1 minute. We
|
|
65
|
+
divide time into 1 minute slices, just like in the fixed window algorithm.
|
|
66
|
+
Window 1 will be from 00:00:00 to 00:01:00 (HH:MM:SS). Let's assume it is
|
|
67
|
+
currently 00:01:15 and we have received 4 requests in the first window and 5
|
|
68
|
+
requests so far in the current window. The approximation to determine if the
|
|
69
|
+
request should pass works like this:
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
limit = 10
|
|
73
|
+
|
|
74
|
+
// 4 request from the old window, weighted + requests in current window
|
|
75
|
+
rate = 4 * ((60 - 15) / 60) + 5 = 8
|
|
76
|
+
|
|
77
|
+
return rate < limit // True means we should allow the request
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### Pros
|
|
81
|
+
|
|
82
|
+
- Solves the issue near boundary from fixed window.
|
|
83
|
+
- Supports [dynamic limits](/redis/sdks/ratelimit-ts/features#dynamic-limits)
|
|
84
|
+
|
|
85
|
+
### Cons
|
|
86
|
+
|
|
87
|
+
- More expensive in terms of storage and computation
|
|
88
|
+
- Is only an approximation, because it assumes a uniform request flow in the
|
|
89
|
+
previous window, but this is fine in most cases
|
|
90
|
+
|
|
91
|
+
### Usage
|
|
92
|
+
|
|
93
|
+
Create a new ratelimiter, that allows 10 requests per 10 seconds.
|
|
94
|
+
|
|
95
|
+
<Tabs>
|
|
96
|
+
<Tab title="Regional">
|
|
97
|
+
```ts
|
|
98
|
+
const ratelimit = new Ratelimit({
|
|
99
|
+
redis: Redis.fromEnv(),
|
|
100
|
+
limiter: Ratelimit.slidingWindow(10, "10 s"),
|
|
101
|
+
});
|
|
102
|
+
```
|
|
103
|
+
</Tab>
|
|
104
|
+
<Tab title="Multi Regional">
|
|
105
|
+
**Warning:** Using sliding window algorithm with the multiregion setup results in large number of
|
|
106
|
+
commands in Redis and long request processing times. If you want to keep the number of commands
|
|
107
|
+
low, we recommend using the [fixed window algorithm in multi region setup](/redis/sdks/ratelimit-ts/algorithms#fixed-window).
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
const ratelimit = new MultiRegionRatelimit({
|
|
111
|
+
redis: [
|
|
112
|
+
new Redis({
|
|
113
|
+
/* auth */
|
|
114
|
+
}),
|
|
115
|
+
new Redis({
|
|
116
|
+
/* auth */
|
|
117
|
+
})
|
|
118
|
+
],
|
|
119
|
+
limiter: MultiRegionRatelimit.slidingWindow(10, "10 s"),
|
|
120
|
+
});
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
</Tab>
|
|
124
|
+
</Tabs>
|
|
125
|
+
|
|
126
|
+
<Tip>
|
|
127
|
+
`reset` field in the [`limit`](/redis/sdks/ratelimit-ts/methods#limit) and [`getRemaining`](/redis/sdks/ratelimit-ts/methods#getremaining) methods of sliding window do not
|
|
128
|
+
provide an exact reset time. Instead, the reset time is the start time of
|
|
129
|
+
the next window.
|
|
130
|
+
</Tip>
|
|
131
|
+
|
|
132
|
+
## Token Bucket
|
|
133
|
+
|
|
134
|
+
Consider a bucket filled with `{maxTokens}` tokens that refills constantly at
|
|
135
|
+
`{refillRate}` per `{interval}`. Every request will remove one token from the
|
|
136
|
+
bucket and if there is no token to take, the request is rejected.
|
|
137
|
+
|
|
138
|
+
### Pros
|
|
139
|
+
|
|
140
|
+
- Bursts of requests are smoothed out and you can process them at a constant
|
|
141
|
+
rate.
|
|
142
|
+
- Allows to set a higher initial burst limit by setting `maxTokens` higher than
|
|
143
|
+
`refillRate`
|
|
144
|
+
- Supports [dynamic limits](/redis/sdks/ratelimit-ts/features#dynamic-limits)
|
|
145
|
+
|
|
146
|
+
### Cons
|
|
147
|
+
|
|
148
|
+
- Expensive in terms of computation
|
|
149
|
+
|
|
150
|
+
### Usage
|
|
151
|
+
|
|
152
|
+
Create a new bucket, that refills 5 tokens every 10 seconds and has a maximum
|
|
153
|
+
size of 10.
|
|
154
|
+
|
|
155
|
+
<Tabs>
|
|
156
|
+
<Tab title="Regional">
|
|
157
|
+
```ts
|
|
158
|
+
const ratelimit = new Ratelimit({
|
|
159
|
+
redis: Redis.fromEnv(),
|
|
160
|
+
limiter: Ratelimit.tokenBucket(5, "10 s", 10),
|
|
161
|
+
analytics: true,
|
|
162
|
+
});
|
|
163
|
+
```
|
|
164
|
+
</Tab>
|
|
165
|
+
|
|
166
|
+
<Tab title="Multi Regional">
|
|
167
|
+
_Not yet supported for `MultiRegionRatelimit`_
|
|
168
|
+
</Tab>
|
|
169
|
+
</Tabs>
|
package/docs/costs.mdx
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Costs
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
This page details the cost of the Ratelimit algorithms in terms of the number of Redis commands. Note that these are calculated for Regional Ratelimits. For [Multi Region Ratelimit](/redis/sdks/ratelimit-ts/features#multi-region), costs will be higher. Additionally, if a Global Upstash Redis is used as the database, number of commands should be calculated as `(1+readRegionCount) * writeCommandCount + readCommandCount` and plus 1 if analytics is enabled.
|
|
6
|
+
|
|
7
|
+
The Rate Limit SDK minimizes Redis calls to reduce latency overhead and cost. Number of commands executed by the Rate Limit algorithm depends on the chosen algorithm, as well as the state of the algorithm and the caching.
|
|
8
|
+
|
|
9
|
+
#### Algorithm State
|
|
10
|
+
|
|
11
|
+
By state of the algorithm, we refer to the entry in our Redis store regarding some identifier `ip1`. You can imagine that there is a state for every identifier. We name these states in the following manner for the purpose of attributing costs to each one:
|
|
12
|
+
|
|
13
|
+
| State | Success | Explanation |
|
|
14
|
+
| ------------ | ------- | ------------------------------------------------------------------------ |
|
|
15
|
+
| First | true | First time the Ratelimit was called with identifier `ip1` |
|
|
16
|
+
| Intermediate | true | Second or some other time the Ratelimit was called with identifier `ip1` |
|
|
17
|
+
| Rate-Limited | false | Requests with identifier `ip1` which are rate limited. |
|
|
18
|
+
|
|
19
|
+
For instance, first time we call the algorithm with `ip1`, `PEXPIRE` is called so that the key expires after some time. In the following calls, we still use the same script but don't call `PEXPIRE`. In the rate-limited state, we may avoid using Redis altogether if we can make use of the cache.
|
|
20
|
+
|
|
21
|
+
#### Cache Result
|
|
22
|
+
|
|
23
|
+
We distinguish the two cases when the identifier `ip1` is found in cache, resulting in a "hit" and the case when the identifier `ip1` is not found in the cache, resulting in a "miss". The cache only exists in the runtime environment and is independent of the Redis database. The state of the cache is especially relevant for serverless contexts, where the cache will usually be empty because of a cold start.
|
|
24
|
+
|
|
25
|
+
| Result | Explanation |
|
|
26
|
+
| ------ | ------------------------------------------------------------------------------------------------------- |
|
|
27
|
+
| Hit | Identifier `ip1` is found in the runtime cache |
|
|
28
|
+
| Miss | Identifier `ip1` is not found in cache or the value in the cache doesn't block (rate-limit) the request |
|
|
29
|
+
|
|
30
|
+
An identifier is saved in the cache only when a request is rate limited after a call to the Redis database. The request to Redis returns a timestamp for the time when such a request won't be rate limited anymore. We save this timestamp in the cache and this allows us to reject any request before this timestamp without having to consult the Redis database.
|
|
31
|
+
|
|
32
|
+
See the [section on caching](/redis/sdks/ratelimit-ts/features) for more details.
|
|
33
|
+
|
|
34
|
+
# Costs
|
|
35
|
+
|
|
36
|
+
### `limit()`
|
|
37
|
+
|
|
38
|
+
#### Fixed Window
|
|
39
|
+
|
|
40
|
+
| Cache Result | Algorithm State | Command Count | Commands |
|
|
41
|
+
| ------------ | --------------- | ------------- | ------------------- |
|
|
42
|
+
| Hit/Miss | First | 3 | EVAL, INCR, PEXPIRE |
|
|
43
|
+
| Hit/Miss | Intermediate | 2 | EVAL, INCR |
|
|
44
|
+
| Miss | Rate-Limited | 2 | EVAL, INCR |
|
|
45
|
+
| Hit | Rate-Limited | 0 | _utilized cache_ |
|
|
46
|
+
|
|
47
|
+
#### Sliding Window
|
|
48
|
+
|
|
49
|
+
| Cache Result | Algorithm State | Command Count | Commands |
|
|
50
|
+
| ------------ | --------------- | ------------- | ----------------------------- |
|
|
51
|
+
| Hit/Miss | First | 5 | EVAL, GET, GET, INCR, PEXPIRE |
|
|
52
|
+
| Hit/Miss | Intermediate | 4 | EVAL, GET, GET, INCR |
|
|
53
|
+
| Miss | Rate-Limited | 3 | EVAL, GET, GET |
|
|
54
|
+
| Hit | Rate-Limited | 0 | _utilized cache_ |
|
|
55
|
+
|
|
56
|
+
#### Token Bucket
|
|
57
|
+
|
|
58
|
+
| Cache Result | Algorithm State | Command Count | Commands |
|
|
59
|
+
| ------------ | ------------------ | ------------- | --------------------------- |
|
|
60
|
+
| Hit/Miss | First/Intermediate | 4 | EVAL, HMGET, HSET, PEXPIRE |
|
|
61
|
+
| Miss | Rate-Limited | 2 | EVAL, HMGET |
|
|
62
|
+
| Hit | Rate-Limited | 0 | _utilized cache_ |
|
|
63
|
+
|
|
64
|
+
### `getRemaining()`
|
|
65
|
+
|
|
66
|
+
This method doesn't use the cache or it doesn't have a state it depends on. Therefore, every call
|
|
67
|
+
results in the same number of commands in Redis.
|
|
68
|
+
|
|
69
|
+
| Algorithm | Command Count | Commands |
|
|
70
|
+
| -------------- | ------------- | -------------- |
|
|
71
|
+
| Fixed Window | 2 | EVAL, GET |
|
|
72
|
+
| Sliding Window | 3 | EVAL, GET, GET |
|
|
73
|
+
| Token Bucket | 2 | EVAL, HMGET |
|
|
74
|
+
|
|
75
|
+
### `resetUsedTokens()`
|
|
76
|
+
|
|
77
|
+
This method starts with a `SCAN` command and deletes every key that matches with `DEL` commands:
|
|
78
|
+
|
|
79
|
+
| Algorithm | Command Count | Commands |
|
|
80
|
+
| -------------- | ------------- | -------------------- |
|
|
81
|
+
| Fixed Window | 3 | EVAL, SCAN, DEL |
|
|
82
|
+
| Sliding Window | 4 | EVAL, SCAN, DEL, DEL |
|
|
83
|
+
| Token Bucket | 3 | EVAL, SCAN, DEL |
|
|
84
|
+
|
|
85
|
+
### `blockUntilReady()`
|
|
86
|
+
|
|
87
|
+
Works the same as `limit()`.
|
|
88
|
+
|
|
89
|
+
# Deny List
|
|
90
|
+
|
|
91
|
+
Enabling deny lists introduces a cost of 2 additional command per `limit` call.
|
|
92
|
+
|
|
93
|
+
Values passed in `identifier`, `ip`, `userAgent` and `country` are checked with a single `SMISMEMBER` command.
|
|
94
|
+
The other command is TTL which is for checking the status of the current ip deny list to figure out whether
|
|
95
|
+
it is expired, valid or disabled.
|
|
96
|
+
|
|
97
|
+
If [Auto IP deny list](/redis/sdks/ratelimit-ts/traffic-protection#auto-ip-deny-list) is enabled,
|
|
98
|
+
the Ratelimit SDK will update the ip deny list everyday, in the first `limit` invocation after 2 AM UTC.
|
|
99
|
+
This will consume 9 commands per day.
|
|
100
|
+
|
|
101
|
+
If a value is found in the deny list at redis, the client saves this value in the cache and denies
|
|
102
|
+
any further requests with that value for a minute without calling Redis (except for analytics).
|
|
103
|
+
|
|
104
|
+
# Analytics
|
|
105
|
+
|
|
106
|
+
If analytics is enabled, all calls of `limit` will result in 1 more command since `ZINCRBY` will be called to update the analytics.
|
|
107
|
+
|
|
108
|
+
# Dynamic Limits
|
|
109
|
+
|
|
110
|
+
When [dynamic limits](/redis/sdks/ratelimit-ts/features#dynamic-limits) are enabled, each `limit` and `getRemaining` call will execute one additional command.
|
|
111
|
+
|
|
112
|
+
Both `setDynamicLimit` and `getDynamicLimit` execute 1 command each.
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Ratelimit TypeScript SDK Features
|
|
3
|
+
sidebarTitle: Features
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
## Caching
|
|
7
|
+
|
|
8
|
+
For extreme load or denial of service attacks, it might be too expensive to call
|
|
9
|
+
redis for every incoming request, just to find out it should be blocked because
|
|
10
|
+
they have exceeded the limit.
|
|
11
|
+
|
|
12
|
+
You can use an ephemeral in memory cache by passing some variable of type
|
|
13
|
+
`Map<string, number>` as the `ephemeralCache` option:
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
const cache = new Map(); // must be outside of your serverless function handler
|
|
17
|
+
|
|
18
|
+
// ...
|
|
19
|
+
|
|
20
|
+
const ratelimit = new Ratelimit({
|
|
21
|
+
// ...
|
|
22
|
+
ephemeralCache: cache,
|
|
23
|
+
});
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
By default, `ephemeralCache` will be initialized with `new Map()` if no value is provided
|
|
27
|
+
as the `ephemeralCache` parameter. To disable the cache, one must pass `ephemeralCache: false`.
|
|
28
|
+
|
|
29
|
+
If enabled, the ratelimiter will keep track of the blocked identifiers and their
|
|
30
|
+
reset timestamps. When a request is received with some identifier `ip1` before the reset time of
|
|
31
|
+
`ip1`, the request will be denied without having to call Redis. [`reason` field of the
|
|
32
|
+
limit response will be `cacheBlock`](/redis/sdks/ratelimit-ts/methods#limit)
|
|
33
|
+
|
|
34
|
+
In serverless environments this is only possible if you create the cache or ratelimiter
|
|
35
|
+
instance outside of your handler function. While the function is still hot, the
|
|
36
|
+
ratelimiter can block requests without having to request data from Redis, thus
|
|
37
|
+
saving time and money.
|
|
38
|
+
|
|
39
|
+
See the section on how caching impacts the cost in the
|
|
40
|
+
[costs page](/redis/sdks/ratelimit-ts/costs#cache-result).
|
|
41
|
+
|
|
42
|
+
## Timeout
|
|
43
|
+
|
|
44
|
+
You can define an optional timeout in milliseconds, after which the request will
|
|
45
|
+
be allowed to pass regardless of what the current limit is. This can be useful
|
|
46
|
+
if you don't want network issues to cause your application to reject requests.
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
const ratelimit = new Ratelimit({
|
|
50
|
+
redis: Redis.fromEnv(),
|
|
51
|
+
limiter: Ratelimit.slidingWindow(10, "10 s"),
|
|
52
|
+
timeout: 1000, // 1 second
|
|
53
|
+
analytics: true,
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Default value of the timeout is 5 seconds if no `timeout` is provided. When response
|
|
58
|
+
is success because of a timeout, this is shown in
|
|
59
|
+
[the `reason` field of the limit method](/redis/sdks/ratelimit-ts/methods#limit).
|
|
60
|
+
|
|
61
|
+
## Analytics & Dashboard
|
|
62
|
+
|
|
63
|
+
Another feature of the rate limiting algorithm is to collect analytics.
|
|
64
|
+
|
|
65
|
+
By default, analytics is disabled. To enable analytics, simply set the `analytics` parameter to `true`:
|
|
66
|
+
|
|
67
|
+
```js
|
|
68
|
+
const ratelimit = new Ratelimit({
|
|
69
|
+
redis,
|
|
70
|
+
analytics: true,
|
|
71
|
+
limiter: Ratelimit.slidingWindow(60, "10s"),
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Everytime we call `ratelimit.limit()`, analytics will be sent to the Redis database
|
|
76
|
+
([see costs page](/redis/sdks/ratelimit-ts/costs#analytics))
|
|
77
|
+
and information about the hour, identifier and the number of rate limit success and
|
|
78
|
+
failures will be collected. This information can be viewed from the Upstash console.
|
|
79
|
+
|
|
80
|
+
If you are using rate limiting in Cloudflare Workers, Vercel Edge or a similar environment,
|
|
81
|
+
you need to make sure that the analytics request is delivered correctly to the Redis.
|
|
82
|
+
Otherwise, you may observe lower numbers than the actual number of calls.
|
|
83
|
+
|
|
84
|
+
To make sure that the request completes, you can use the `pending` field returned by
|
|
85
|
+
the `limit` method. See the
|
|
86
|
+
[Asynchronous synchronization between databases](/redis/sdks/ratelimit-ts/features#asynchronous-synchronization-between-databases)
|
|
87
|
+
section to see how `pending` can be used.
|
|
88
|
+
|
|
89
|
+
### Dashboard
|
|
90
|
+
|
|
91
|
+
If the analytics is enabled, you can find information about how many requests were made
|
|
92
|
+
with which identifiers and how many of the requests were blocked from the [Rate Limit
|
|
93
|
+
dashboard in Upstash Console](https://console.upstash.com/ratelimit).
|
|
94
|
+
|
|
95
|
+
To find the dashboard, simply click the three dots and choose the "Rate Limit Analytics" tab:
|
|
96
|
+
|
|
97
|
+

|
|
98
|
+
|
|
99
|
+
In the dashboard, you can find information on how many requests were accepted, how many were blocked
|
|
100
|
+
and how many were received in total. Additionally, you can see requests over time; top allowed, rate limited
|
|
101
|
+
and denied requests.
|
|
102
|
+
|
|
103
|
+

|
|
104
|
+
|
|
105
|
+
**Allowed requests** show the identifiers of the requests which succeeded. **Rate limited requests** show the
|
|
106
|
+
identifiers of the requests which were blocked because they surpassed the limit. **Denied requests** show the identifier,
|
|
107
|
+
user agent, country, or the IP address which caused the request to fail.
|
|
108
|
+
|
|
109
|
+
If you are using a custom prefix, you need to use the same in the dashboard’s top left corner.
|
|
110
|
+
|
|
111
|
+
## Using Multiple Limits
|
|
112
|
+
|
|
113
|
+
Sometimes you might want to apply different limits to different users. For
|
|
114
|
+
example you might want to allow 10 requests per 10 seconds for free users, but
|
|
115
|
+
60 requests per 10 seconds for paid users.
|
|
116
|
+
|
|
117
|
+
Here's how you could do that:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { Redis } from "@upstash/redis";
|
|
121
|
+
import { Ratelimit } from "@upstash/ratelimit";
|
|
122
|
+
|
|
123
|
+
const redis = Redis.fromEnv();
|
|
124
|
+
|
|
125
|
+
const ratelimit = {
|
|
126
|
+
free: new Ratelimit({
|
|
127
|
+
redis,
|
|
128
|
+
analytics: true,
|
|
129
|
+
prefix: "ratelimit:free",
|
|
130
|
+
limiter: Ratelimit.slidingWindow(10, "10s"),
|
|
131
|
+
}),
|
|
132
|
+
paid: new Ratelimit({
|
|
133
|
+
redis,
|
|
134
|
+
analytics: true,
|
|
135
|
+
prefix: "ratelimit:paid",
|
|
136
|
+
limiter: Ratelimit.slidingWindow(60, "10s"),
|
|
137
|
+
}),
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
await ratelimit.free.limit(ip);
|
|
141
|
+
// or for a paid user you might have an email or userId available:
|
|
142
|
+
await ratelimit.paid.limit(userId);
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Custom Rates
|
|
146
|
+
|
|
147
|
+
When we call `limit`, it subtracts 1 from the number of calls/tokens available in
|
|
148
|
+
the timeframe by default. But there are use cases where we may want to subtract different
|
|
149
|
+
numbers depending on the request.
|
|
150
|
+
|
|
151
|
+
Consider a case where we receive some input from the user either alone or in batches.
|
|
152
|
+
If we want to rate limit based on the number of inputs the user can send, we need a way of
|
|
153
|
+
specifying what value to subtract.
|
|
154
|
+
|
|
155
|
+
This is possible thanks to the `rate` parameter. Simply call the `limit` method like the
|
|
156
|
+
following:
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
const { success } = await ratelimit.limit("identifier", { rate: batchSize });
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
This way, the algorithm will subtract `batchSize` instead of 1.
|
|
163
|
+
|
|
164
|
+
## Multi Region
|
|
165
|
+
|
|
166
|
+
Let's assume you have customers in the US and Europe. In this case you can
|
|
167
|
+
create 2 separate global redis databases on [Upstash](https://console.upstash.com)
|
|
168
|
+
(one with its primary in US and the other in Europe) and your users will enjoy
|
|
169
|
+
the latency of whichever db is closest to them.
|
|
170
|
+
|
|
171
|
+
Using a single Redis instance with replicas in different regions cannot offer
|
|
172
|
+
the same performance as `MultiRegionRatelimit` because all write commands have
|
|
173
|
+
to go through the primary, increasing latency in other regions.
|
|
174
|
+
|
|
175
|
+
Using a single redis instance has the downside of providing low latencies only
|
|
176
|
+
to the part of your userbase closest to the deployed db. That's why we also
|
|
177
|
+
built `MultiRegionRatelimit` which replicates the state across multiple redis
|
|
178
|
+
databases as well as offering lower latencies to more of your users.
|
|
179
|
+
|
|
180
|
+
`MultiRegionRatelimit` does this by checking the current limit in the closest db
|
|
181
|
+
and returning immediately. Only afterwards will the state be asynchronously
|
|
182
|
+
replicated to the other databases leveraging
|
|
183
|
+
[CRDTs](https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type). Due
|
|
184
|
+
to the nature of distributed systems, there is no way to guarantee the set
|
|
185
|
+
ratelimit is not exceeded by a small margin. This is the tradeoff for reduced
|
|
186
|
+
global latency.
|
|
187
|
+
|
|
188
|
+
### Usage
|
|
189
|
+
|
|
190
|
+
The API is the same, except for asking for multiple redis instances:
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
import { MultiRegionRatelimit } from "@upstash/ratelimit"; // for deno: see above
|
|
194
|
+
import { Redis } from "@upstash/redis";
|
|
195
|
+
|
|
196
|
+
// Create a new ratelimiter, that allows 10 requests per 10 seconds
|
|
197
|
+
const ratelimit = new MultiRegionRatelimit({
|
|
198
|
+
redis: [
|
|
199
|
+
new Redis({
|
|
200
|
+
/* auth */
|
|
201
|
+
}),
|
|
202
|
+
new Redis({
|
|
203
|
+
/* auth */
|
|
204
|
+
}),
|
|
205
|
+
new Redis({
|
|
206
|
+
/* auth */
|
|
207
|
+
}),
|
|
208
|
+
],
|
|
209
|
+
limiter: MultiRegionRatelimit.slidingWindow(10, "10 s"),
|
|
210
|
+
analytics: true,
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
// Use a constant string to limit all requests with a single ratelimit
|
|
214
|
+
// Or use a userID, apiKey or ip address for individual limits.
|
|
215
|
+
const identifier = "api";
|
|
216
|
+
const { success } = await ratelimit.limit(identifier);
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
### Asynchronous synchronization between databases
|
|
220
|
+
|
|
221
|
+
The MultiRegion setup will do some synchronization between databases after
|
|
222
|
+
returning the current limit. This can lead to problems on Cloudflare Workers and
|
|
223
|
+
therefore Vercel Edge functions, because dangling promises must be taken care
|
|
224
|
+
of:
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
const { pending } = await ratelimit.limit("id");
|
|
228
|
+
context.waitUntil(pending);
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
See more information on `context.waitUntil` at
|
|
232
|
+
[Cloudflare](https://developers.cloudflare.com/workers/runtime-apis/context/#waituntil)
|
|
233
|
+
and [Vercel](https://vercel.com/docs/functions/edge-middleware/middleware-api#waituntil).
|
|
234
|
+
You can also utilize [`waitUntil` from Vercel Functions API](https://vercel.com/docs/functions/functions-api-reference#waituntil).
|
|
235
|
+
|
|
236
|
+
## Dynamic Limits
|
|
237
|
+
|
|
238
|
+
Dynamic limits allow you to change rate limits at runtime without recreating the rate limiter instance. This is useful when you need to adjust limits based on user tiers, system load, or other dynamic factors.
|
|
239
|
+
|
|
240
|
+
To enable dynamic limits, set the `dynamicLimits` option to `true` when creating the rate limiter:
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
const ratelimit = new Ratelimit({
|
|
244
|
+
redis: Redis.fromEnv(),
|
|
245
|
+
limiter: Ratelimit.slidingWindow(10, "10s"),
|
|
246
|
+
dynamicLimits: true, // Enable dynamic limits
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
// Set a global dynamic limit
|
|
250
|
+
await ratelimit.setDynamicLimit({ limit: 5 });
|
|
251
|
+
|
|
252
|
+
// All subsequent limit checks use the new limit
|
|
253
|
+
const { success } = await ratelimit.limit("user_123");
|
|
254
|
+
|
|
255
|
+
// Get current dynamic limit
|
|
256
|
+
const currentLimit = await ratelimit.getDynamicLimit(); // returns 5
|
|
257
|
+
|
|
258
|
+
// Remove dynamic limit (falls back to default)
|
|
259
|
+
await ratelimit.setDynamicLimit({ limit: false });
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Dynamic limits work with the following single region algorithms: `fixedWindow`, `slidingWindow`, `tokenBucket`, Multi region algrorithms aren't supported.
|