@@ -8,10 +8,10 @@ Each user has their own bucket of tokens that gets refilled at a set interval. A
8
8
9
9
## Memory storage
10
10
11
- This will only work if memory is persisted across requests. It won't work in serverless environments.
11
+ This requires the server to persist its memory across requests and will not work in serverless environments.
12
12
13
13
``` ts
14
- export class TokenBucket <_Key > {
14
+ export class TokenBucketRateLimit <_Key > {
15
15
public max: number ;
16
16
public refillIntervalSeconds: number ;
17
17
@@ -35,7 +35,7 @@ export class TokenBucket<_Key> {
35
35
}
36
36
const refill = Math .floor ((now - bucket .refilledAt ) / (this .refillIntervalSeconds * 1000 ));
37
37
bucket .count = Math .min (bucket .count + refill , this .max );
38
- bucket .refilledAt = now ;
38
+ bucket .refilledAt = bucket . refilledAt + refill * this . refillIntervalSeconds ;
39
39
if (bucket .count < cost ) {
40
40
return false ;
41
41
}
@@ -53,9 +53,9 @@ interface Bucket {
53
53
54
54
``` ts
55
55
// Bucket that has 10 tokens max and refills at a rate of 2 tokens/sec
56
- const bucket = new TokenBucket <string >(10 , 2 );
56
+ const ratelimit = new TokenBucketRateLimit <string >(10 , 2 );
57
57
58
- if (! bucket .consume (ip , 1 )) {
58
+ if (! ratelimit .consume (ip , 1 )) {
59
59
throw new Error (" Too many requests" );
60
60
}
61
61
```
@@ -88,7 +88,7 @@ for i = 1, #fields, 2 do
88
88
end
89
89
local refill = math.floor ((now - refilledAt ) / refillIntervalSeconds )
90
90
count = math.min (count + refill , max )
91
- refilledAt = now
91
+ refilledAt = refilledAt + refill * refillIntervalSeconds
92
92
if count < cost then
93
93
return {0 }
94
94
end
@@ -106,7 +106,7 @@ const SCRIPT_SHA = await client.scriptLoad(script);
106
106
Reference the script with the hash.
107
107
108
108
``` ts
109
- export class TokenBucket {
109
+ export class TokenBucketRateLimit {
110
110
private storageKey: string ;
111
111
112
112
public max: number ;
@@ -136,9 +136,9 @@ export class TokenBucket {
136
136
``` ts
137
137
// Bucket that has 10 tokens max and refills at a rate of 2 tokens/sec.
138
138
// Ensure that the storage key is unique.
139
- const bucket = new TokenBucket (" global_ip" , 10 , 2 );
139
+ const ratelimit = new TokenBucketRateLimit (" global_ip" , 10 , 2 );
140
140
141
- const valid = await bucket .consume (ip , 1 );
141
+ const valid = await ratelimit .consume (ip , 1 );
142
142
if (! valid ) {
143
143
throw new Error (" Too many requests" );
144
144
}
0 commit comments