@@ -8,10 +8,10 @@ Each user has their own bucket of tokens that gets refilled at a set interval. A
88
99## Memory storage
1010
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.
1212
1313``` ts
14- export class TokenBucket <_Key > {
14+ export class TokenBucketRateLimit <_Key > {
1515 public max: number ;
1616 public refillIntervalSeconds: number ;
1717
@@ -35,7 +35,7 @@ export class TokenBucket<_Key> {
3535 }
3636 const refill = Math .floor ((now - bucket .refilledAt ) / (this .refillIntervalSeconds * 1000 ));
3737 bucket .count = Math .min (bucket .count + refill , this .max );
38- bucket .refilledAt = now ;
38+ bucket .refilledAt = bucket . refilledAt + refill * this . refillIntervalSeconds ;
3939 if (bucket .count < cost ) {
4040 return false ;
4141 }
@@ -53,9 +53,9 @@ interface Bucket {
5353
5454``` ts
5555// 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 );
5757
58- if (! bucket .consume (ip , 1 )) {
58+ if (! ratelimit .consume (ip , 1 )) {
5959 throw new Error (" Too many requests" );
6060}
6161```
@@ -88,7 +88,7 @@ for i = 1, #fields, 2 do
8888end
8989local refill = math.floor ((now - refilledAt ) / refillIntervalSeconds )
9090count = math.min (count + refill , max )
91- refilledAt = now
91+ refilledAt = refilledAt + refill * refillIntervalSeconds
9292if count < cost then
9393 return {0 }
9494end
@@ -106,7 +106,7 @@ const SCRIPT_SHA = await client.scriptLoad(script);
106106Reference the script with the hash.
107107
108108``` ts
109- export class TokenBucket {
109+ export class TokenBucketRateLimit {
110110 private storageKey: string ;
111111
112112 public max: number ;
@@ -136,9 +136,9 @@ export class TokenBucket {
136136``` ts
137137// Bucket that has 10 tokens max and refills at a rate of 2 tokens/sec.
138138// 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 );
140140
141- const valid = await bucket .consume (ip , 1 );
141+ const valid = await ratelimit .consume (ip , 1 );
142142if (! valid ) {
143143 throw new Error (" Too many requests" );
144144}
0 commit comments