-
Notifications
You must be signed in to change notification settings - Fork 0
Use Redis Cache for Critical Paths #145
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
d01a9dc
use redis cache for critical paths
devksingh4 7cb9a6d
fix syntax error
devksingh4 8e0c787
try a fix
devksingh4 ed26f3a
fix unit tests (finally)
devksingh4 d5a8af0
make ioredis external
devksingh4 3ffadd9
remove fastify-cron
devksingh4 7f99c46
freeze event loop
devksingh4 ebf4ee8
fix authorization func
devksingh4 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,66 +1,60 @@ | ||
| import { | ||
| ConditionalCheckFailedException, | ||
| UpdateItemCommand, | ||
| DynamoDBClient, | ||
| } from "@aws-sdk/client-dynamodb"; | ||
| import { genericConfig } from "common/config.js"; | ||
| import { Redis } from "ioredis"; // Make sure you have ioredis installed (npm install ioredis) | ||
|
|
||
| interface RateLimitParams { | ||
| ddbClient: DynamoDBClient; | ||
| redisClient: Redis; | ||
| rateLimitIdentifier: string; | ||
| duration: number; | ||
| limit: number; | ||
| userIdentifier: string; | ||
| } | ||
|
|
||
| interface RateLimitResult { | ||
| limited: boolean; | ||
| resetTime: number; | ||
| used: number; | ||
| } | ||
|
|
||
| const LUA_SCRIPT_INCREMENT_AND_EXPIRE = ` | ||
| local count = redis.call("INCR", KEYS[1]) | ||
| -- If the count is 1, this means the key was just created by INCR (first request in this window). | ||
| -- So, we set its expiration time to the end of the current window. | ||
| if tonumber(count) == 1 then | ||
| redis.call("EXPIREAT", KEYS[1], ARGV[1]) | ||
| end | ||
| return count | ||
| `; | ||
|
|
||
| export async function isAtLimit({ | ||
| ddbClient, | ||
| redisClient, | ||
| rateLimitIdentifier, | ||
| duration, | ||
| limit, | ||
| userIdentifier, | ||
| }: RateLimitParams): Promise<{ | ||
| limited: boolean; | ||
| resetTime: number; | ||
| used: number; | ||
| }> { | ||
| }: RateLimitParams): Promise<RateLimitResult> { | ||
| if (duration <= 0) { | ||
| throw new Error("Rate limit duration must be a positive number."); | ||
| } | ||
| if (limit < 0) { | ||
| throw new Error("Rate limit must be a non-negative number."); | ||
| } | ||
|
|
||
| const nowInSeconds = Math.floor(Date.now() / 1000); | ||
| const timeWindow = Math.floor(nowInSeconds / duration) * duration; | ||
| const PK = `rate-limit:${rateLimitIdentifier}:${userIdentifier}:${timeWindow}`; | ||
| const timeWindowStart = Math.floor(nowInSeconds / duration) * duration; | ||
| const key = `rate-limit:${rateLimitIdentifier}:${userIdentifier}:${timeWindowStart}`; | ||
| const expiryTimestamp = timeWindowStart + duration; | ||
|
|
||
| try { | ||
| const result = await ddbClient.send( | ||
| new UpdateItemCommand({ | ||
| TableName: genericConfig.RateLimiterDynamoTableName, | ||
| Key: { | ||
| PK: { S: PK }, | ||
| SK: { S: "counter" }, | ||
| }, | ||
| UpdateExpression: "ADD #rateLimitCount :inc SET #ttl = :ttl", | ||
| ConditionExpression: | ||
| "attribute_not_exists(#rateLimitCount) OR #rateLimitCount <= :limit", | ||
| ExpressionAttributeValues: { | ||
| ":inc": { N: "1" }, | ||
| ":limit": { N: limit.toString() }, | ||
| ":ttl": { N: (timeWindow + duration).toString() }, | ||
| }, | ||
| ExpressionAttributeNames: { | ||
| "#rateLimitCount": "rateLimitCount", | ||
| "#ttl": "ttl", | ||
| }, | ||
| ReturnValues: "UPDATED_NEW", | ||
| ReturnValuesOnConditionCheckFailure: "ALL_OLD", | ||
| }), | ||
| ); | ||
| return { | ||
| limited: false, | ||
| used: parseInt(result.Attributes?.rateLimitCount.N || "1", 10), | ||
| resetTime: timeWindow + duration, | ||
| }; | ||
| } catch (error) { | ||
| if (error instanceof ConditionalCheckFailedException) { | ||
| return { limited: true, resetTime: timeWindow + duration, used: limit }; | ||
| } | ||
| throw error; | ||
| } | ||
| const currentUsedCount = (await redisClient.eval( | ||
| LUA_SCRIPT_INCREMENT_AND_EXPIRE, | ||
| 1, // Number of keys | ||
| key, // KEYS[1] | ||
| expiryTimestamp.toString(), // ARGV[1] | ||
| )) as number; // The script returns the count, which is a number. | ||
| const isLimited = currentUsedCount > limit; | ||
| const resetTime = expiryTimestamp; | ||
|
|
||
| return { | ||
| limited: isLimited, | ||
| resetTime, | ||
| used: isLimited ? limit : currentUsedCount, | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.