generated from cds-snc/project-template
-
Notifications
You must be signed in to change notification settings - Fork 0
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
feat: token bucket rate limiting #91
Merged
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a8d5013
feat: token bucket rate limiting
craigzour 4961354
refactor: rename cache to redisClientAdapter
craigzour 5ea9b5b
refactored a few things
craigzour 3340dfa
adjust rate limiter configuration and add comment on some of the opti…
craigzour 0cb1327
add missing keyprefix to insurance limiters
craigzour 8adcc0e
remove useless log and fix unit test
craigzour 5dbcad7
change test mock to make it easier to understand
craigzour 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 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains 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 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 |
---|---|---|
|
@@ -4,6 +4,11 @@ export enum EnvironmentMode { | |
Production = "production", | ||
} | ||
|
||
export type TokenBucketConfiguration = { | ||
capacity: number; | ||
numberOfSecondsBeforeRefill: number; | ||
}; | ||
|
||
// AWS SDK | ||
|
||
export const AWS_REGION: string = "ca-central-1"; | ||
|
@@ -30,6 +35,18 @@ export const LOCALSTACK_ENDPOINT: string | undefined = loadOptionalEnvVar( | |
"LOCALSTACK_ENDPOINT", | ||
); | ||
|
||
// Rate limiting | ||
|
||
export const lowRateLimiterConfiguration: TokenBucketConfiguration = { | ||
capacity: 500, | ||
numberOfSecondsBeforeRefill: 60, | ||
}; | ||
|
||
export const highRateLimiterConfiguration: TokenBucketConfiguration = { | ||
capacity: 1000, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The high capacity token bucket is not going to be used for now as the web app feature to enable it is not a priority at the moment. |
||
numberOfSecondsBeforeRefill: 60, | ||
}; | ||
|
||
// Redis | ||
|
||
export const REDIS_URL: string = loadRequiredEnvVar("REDIS_URL"); | ||
|
This file contains 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 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
6 changes: 3 additions & 3 deletions
6
src/lib/utils/cache.ts → ...b/integration/redis/redisClientAdapter.ts
This file contains 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
File renamed without changes.
This file contains 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 |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import { getTokenBucketRateLimiterAssociatedToForm } from "@lib/rateLimiting/tokenBucketProvider.js"; | ||
import type { RateLimiterRes } from "rate-limiter-flexible"; | ||
|
||
export type BucketStatus = { | ||
bucketCapacity: number; | ||
remainingTokens: number; | ||
numberOfMillisecondsBeforeRefill: number; | ||
}; | ||
|
||
export type ConsumeTokenResult = { | ||
wasAbleToConsumeToken: boolean; | ||
bucketStatus: BucketStatus; | ||
}; | ||
|
||
export async function consumeTokenIfAvailable( | ||
formId: string, | ||
): Promise<ConsumeTokenResult> { | ||
const tokenBucket = await getTokenBucketRateLimiterAssociatedToForm(formId); | ||
|
||
try { | ||
const consumptionResult = await tokenBucket.consume(formId); | ||
|
||
return { | ||
wasAbleToConsumeToken: true, | ||
bucketStatus: buildBucketStatus(tokenBucket.points, consumptionResult), | ||
}; | ||
} catch (rateLimiterRes) { | ||
// Since our token buckets have an `insuranceLimiter` set up, the consume function promise can only be rejected with a `RateLimiterRes` object | ||
return { | ||
wasAbleToConsumeToken: false, | ||
bucketStatus: buildBucketStatus( | ||
tokenBucket.points, | ||
rateLimiterRes as RateLimiterRes, | ||
), | ||
}; | ||
} | ||
} | ||
|
||
export async function refundConsumedToken(formId: string): Promise<void> { | ||
const tokenBucket = await getTokenBucketRateLimiterAssociatedToForm(formId); | ||
await tokenBucket.reward(formId); | ||
} | ||
|
||
function buildBucketStatus( | ||
bucketCapacity: number, | ||
rateLimiterResponse: RateLimiterRes, | ||
): BucketStatus { | ||
return { | ||
bucketCapacity: bucketCapacity, | ||
remainingTokens: rateLimiterResponse.remainingPoints, | ||
numberOfMillisecondsBeforeRefill: rateLimiterResponse.msBeforeNext, | ||
}; | ||
} |
This file contains 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 |
---|---|---|
@@ -0,0 +1,77 @@ | ||
import { | ||
type RateLimiterAbstract, | ||
RateLimiterMemory, | ||
RateLimiterRedis, | ||
} from "rate-limiter-flexible"; | ||
import { RedisConnector } from "@lib/integration/redis/redisConnector.js"; | ||
import { | ||
highRateLimiterConfiguration, | ||
lowRateLimiterConfiguration, | ||
} from "@config"; | ||
import { getValueFromRedis } from "@lib/integration/redis/redisClientAdapter.js"; | ||
import { logMessage } from "@lib/logging/logger.js"; | ||
|
||
const REDIS_RATE_LIMIT_KEY_PREFIX: string = "rate-limit"; | ||
|
||
const redisClient = await RedisConnector.getInstance().then( | ||
(instance) => instance.client, | ||
); | ||
|
||
/** | ||
* From the official documentation: | ||
* `inMemoryBlockOnConsumed`: Can be used against DDoS attacks. In-memory blocking works in current process memory and for consume method only. | ||
* It blocks a key in memory for msBeforeNext milliseconds from the last consume result, if inMemoryBlockDuration is | ||
* not set. This helps to avoid extra requests. inMemoryBlockOnConsumed value is supposed to be equal or more than | ||
* points option. Sometimes it is not necessary to increment counter on store, if all points are consumed already. | ||
* `insuranceLimiter`: Instance of RateLimiterAbstract extended object to store limits, when database comes up with any error. | ||
*/ | ||
|
||
const lowCapacityTokenBucket = new RateLimiterRedis({ | ||
keyPrefix: "low-capacity-token-bucket", | ||
storeClient: redisClient, | ||
useRedisPackage: true, | ||
points: lowRateLimiterConfiguration.capacity, | ||
duration: lowRateLimiterConfiguration.numberOfSecondsBeforeRefill, | ||
inMemoryBlockOnConsumed: lowRateLimiterConfiguration.capacity, | ||
insuranceLimiter: new RateLimiterMemory({ | ||
keyPrefix: "backup-low-capacity-token-bucket", | ||
points: lowRateLimiterConfiguration.capacity, | ||
duration: lowRateLimiterConfiguration.numberOfSecondsBeforeRefill, | ||
}), | ||
}); | ||
|
||
const highCapacityTokenBucket = new RateLimiterRedis({ | ||
keyPrefix: "high-capacity-token-bucket", | ||
storeClient: redisClient, | ||
useRedisPackage: true, | ||
points: highRateLimiterConfiguration.capacity, | ||
duration: highRateLimiterConfiguration.numberOfSecondsBeforeRefill, | ||
inMemoryBlockOnConsumed: highRateLimiterConfiguration.capacity, | ||
insuranceLimiter: new RateLimiterMemory({ | ||
keyPrefix: "backup-high-capacity-token-bucket", | ||
points: highRateLimiterConfiguration.capacity, | ||
duration: highRateLimiterConfiguration.numberOfSecondsBeforeRefill, | ||
}), | ||
}); | ||
|
||
export function getTokenBucketRateLimiterAssociatedToForm( | ||
formId: string, | ||
): Promise<RateLimiterAbstract> { | ||
return getValueFromRedis(`${REDIS_RATE_LIMIT_KEY_PREFIX}:${formId}`) | ||
.then((value) => { | ||
switch (value) { | ||
case "high": | ||
return highCapacityTokenBucket; | ||
default: | ||
return lowCapacityTokenBucket; | ||
} | ||
}) | ||
.catch((error) => { | ||
logMessage.warn( | ||
error, | ||
`[token-bucket-provider] Failed to retrieve token bucket capacity for form ${formId}. Will use low capacity bucket by default`, | ||
); | ||
|
||
return lowCapacityTokenBucket; | ||
}); | ||
} |
This file contains 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,12 +1,18 @@ | ||
import type { Request, Response, NextFunction } from "express"; | ||
import { logMessage } from "@lib/logging/logger.js"; | ||
import { refundConsumedToken } from "@lib/rateLimiting/tokenBucketLimiter.js"; | ||
|
||
export function globalErrorHandlerMiddleware( | ||
export async function globalErrorHandlerMiddleware( | ||
error: Error, | ||
_request: Request, | ||
request: Request, | ||
response: Response, | ||
_next: NextFunction, | ||
): void { | ||
): Promise<void> { | ||
logMessage.error(error, "Global unhandled error"); | ||
|
||
if (request.tokenConsumedOnFormId !== undefined) { | ||
craigzour marked this conversation as resolved.
Show resolved
Hide resolved
|
||
await refundConsumedToken(request.tokenConsumedOnFormId); | ||
} | ||
|
||
response.sendStatus(500); | ||
} |
This file contains 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,9 +1,49 @@ | ||
import type { NextFunction, Request, Response } from "express"; | ||
import { consumeTokenIfAvailable } from "@lib/rateLimiting/tokenBucketLimiter.js"; | ||
import { logMessage } from "@lib/logging/logger.js"; | ||
|
||
export function rateLimiterMiddleware( | ||
_request: Request, | ||
_response: Response, | ||
export async function rateLimiterMiddleware( | ||
request: Request, | ||
response: Response, | ||
next: NextFunction, | ||
): void { | ||
next(); | ||
): Promise<void> { | ||
try { | ||
const formId = request.params.formId; | ||
|
||
const consumeTokenResult = await consumeTokenIfAvailable(formId); | ||
|
||
response.header({ | ||
"X-RateLimit-Limit": consumeTokenResult.bucketStatus.bucketCapacity, | ||
"X-RateLimit-Remaining": consumeTokenResult.bucketStatus.remainingTokens, | ||
"X-RateLimit-Reset": new Date( | ||
Date.now() + | ||
consumeTokenResult.bucketStatus.numberOfMillisecondsBeforeRefill, | ||
), | ||
}); | ||
|
||
if (consumeTokenResult.wasAbleToConsumeToken === false) { | ||
response.header({ | ||
"Retry-After": | ||
consumeTokenResult.bucketStatus.numberOfMillisecondsBeforeRefill / | ||
1000, | ||
}); | ||
|
||
logMessage.info( | ||
`[rate-limiter] Form ${formId} consumed all ${consumeTokenResult.bucketStatus.bucketCapacity} tokens. Bucket will be refilled in ${consumeTokenResult.bucketStatus.numberOfMillisecondsBeforeRefill / 1000} seconds`, | ||
); | ||
|
||
response.sendStatus(429); | ||
return; | ||
} | ||
|
||
request.tokenConsumedOnFormId = formId; | ||
|
||
next(); | ||
} catch (error) { | ||
next( | ||
new Error("[middleware] Internal error with rate limiter", { | ||
cause: error, | ||
}), | ||
); | ||
} | ||
} |
This file contains 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 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A maximum of 500 requests per minute is going to be what we ask our prototyping partners to follow for V1. When the Rate limiter is released we will actually be able to see whether it is a good starting point for our users.