Skip to content

Commit 5832d86

Browse files
committed
added the code to check elapsed time since last query and update token bucket accordingly
1 parent 541e22f commit 5832d86

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

src/rateLimiters/tokenBucket.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,11 @@ class TokenBucket implements RateLimiter {
6161
}
6262

6363
const bucket: RedisBucket = await JSON.parse(bucketJSON);
64-
// TODO check the timestamp on bucket and update however many tokens are supposed to be in there
6564

66-
const timeSinceLastQuery: number = timestamp - bucket.timestamp;
65+
const timeSinceLastQueryInSeconds: number = Math.min((timestamp - bucket.timestamp) / 60);
66+
const tokensToAdd = timeSinceLastQueryInSeconds * this.refillRate;
67+
const updatedTokenCount = bucket.tokens + tokensToAdd;
68+
bucket.tokens = updatedTokenCount > this.capacity ? 10 : updatedTokenCount;
6769

6870
if (bucket.tokens < tokens) {
6971
// reject the request, not enough tokens in bucket

0 commit comments

Comments
 (0)