From 5c50a0a0d5f2308ff64271a8542ef9f6721bc812 Mon Sep 17 00:00:00 2001 From: pilcrow Date: Mon, 9 Dec 2024 10:07:45 +0900 Subject: [PATCH] Update token bucket rate limit (#1756) --- pages/rate-limit/token-bucket.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/pages/rate-limit/token-bucket.md b/pages/rate-limit/token-bucket.md index 5c8b3883c..4eb093b2c 100644 --- a/pages/rate-limit/token-bucket.md +++ b/pages/rate-limit/token-bucket.md @@ -8,10 +8,10 @@ Each user has their own bucket of tokens that gets refilled at a set interval. A ## Memory storage -This will only work if memory is persisted across requests. It won't work in serverless environments. +This requires the server to persist its memory across requests and will not work in serverless environments. ```ts -export class TokenBucket<_Key> { +export class TokenBucketRateLimit<_Key> { public max: number; public refillIntervalSeconds: number; @@ -35,7 +35,7 @@ export class TokenBucket<_Key> { } const refill = Math.floor((now - bucket.refilledAt) / (this.refillIntervalSeconds * 1000)); bucket.count = Math.min(bucket.count + refill, this.max); - bucket.refilledAt = now; + bucket.refilledAt = bucket.refilledAt + refill * this.refillIntervalSeconds; if (bucket.count < cost) { return false; } @@ -53,9 +53,9 @@ interface Bucket { ```ts // Bucket that has 10 tokens max and refills at a rate of 2 tokens/sec -const bucket = new TokenBucket(10, 2); +const ratelimit = new TokenBucketRateLimit(10, 2); -if (!bucket.consume(ip, 1)) { +if (!ratelimit.consume(ip, 1)) { throw new Error("Too many requests"); } ``` @@ -88,7 +88,7 @@ for i = 1, #fields, 2 do end local refill = math.floor((now - refilledAt) / refillIntervalSeconds) count = math.min(count + refill, max) -refilledAt = now +refilledAt = refilledAt + refill * refillIntervalSeconds if count < cost then return {0} end @@ -106,7 +106,7 @@ const SCRIPT_SHA = await client.scriptLoad(script); Reference the script with the hash. ```ts -export class TokenBucket { +export class TokenBucketRateLimit { private storageKey: string; public max: number; @@ -136,9 +136,9 @@ export class TokenBucket { ```ts // Bucket that has 10 tokens max and refills at a rate of 2 tokens/sec. // Ensure that the storage key is unique. -const bucket = new TokenBucket("global_ip", 10, 2); +const ratelimit = new TokenBucketRateLimit("global_ip", 10, 2); -const valid = await bucket.consume(ip, 1); +const valid = await ratelimit.consume(ip, 1); if (!valid) { throw new Error("Too many requests"); }