-
Notifications
You must be signed in to change notification settings - Fork 134
add rate limits #123
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
Open
ctate
wants to merge
3
commits into
main
Choose a base branch
from
ctate/rate-limit
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
add rate limits #123
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| import { Ratelimit } from "@upstash/ratelimit"; | ||
| import { Redis } from "@upstash/redis"; | ||
|
|
||
| type RateLimitResult = { | ||
| allowed: boolean; | ||
| remaining: number; | ||
| resetAt: Date; | ||
| }; | ||
|
|
||
| // Create Redis client with KV_ prefix | ||
| const redis = new Redis({ | ||
| url: process.env.KV_REST_API_URL ?? "", | ||
| token: process.env.KV_REST_API_TOKEN ?? "", | ||
| }); | ||
|
|
||
| // AI generation: 50 requests per hour | ||
| const aiRatelimit = new Ratelimit({ | ||
| redis, | ||
| limiter: Ratelimit.slidingWindow(50, "1 h"), | ||
| prefix: "ratelimit:ai", | ||
| }); | ||
|
|
||
| // Webhook execution: 1000 requests per hour | ||
| const webhookRatelimit = new Ratelimit({ | ||
| redis, | ||
| limiter: Ratelimit.slidingWindow(1000, "1 h"), | ||
| prefix: "ratelimit:webhook", | ||
| }); | ||
|
|
||
| /** | ||
| * Check rate limit for AI generation requests | ||
| */ | ||
| export async function checkAIRateLimit( | ||
| userId: string | ||
| ): Promise<RateLimitResult> { | ||
| const { success, remaining, reset } = await aiRatelimit.limit(userId); | ||
|
|
||
| return { | ||
| allowed: success, | ||
| remaining, | ||
| resetAt: new Date(reset), | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Check rate limit for workflow executions | ||
| */ | ||
| export async function checkExecutionRateLimit( | ||
| userId: string | ||
| ): Promise<RateLimitResult> { | ||
| const { success, remaining, reset } = await webhookRatelimit.limit(userId); | ||
|
|
||
| return { | ||
| allowed: success, | ||
| remaining, | ||
| resetAt: new Date(reset), | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Get rate limit headers for response | ||
| */ | ||
| export function getRateLimitHeaders(result: RateLimitResult): HeadersInit { | ||
| return { | ||
| "X-RateLimit-Remaining": result.remaining.toString(), | ||
| "X-RateLimit-Reset": result.resetAt.toISOString(), | ||
| }; | ||
| } | ||
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
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.
Missing validation for required environment variables
KV_REST_API_URLandKV_REST_API_TOKEN. Using empty string defaults will cause rate limiting to fail at runtime with unhelpful error messages.View Details
Analysis
Missing validation for required Upstash Redis environment variables
What fails: Rate limiting fails at runtime when
KV_REST_API_URLorKV_REST_API_TOKENenvironment variables are not set. The rate limiter module initializes successfully without these credentials (lazy-evaluated), but any attempt to check rate limits throws an unhelpful error.How to reproduce:
KV_REST_API_URLandKV_REST_API_TOKENto empty/undefined in environment/api/ai/generate)Result: Error
Failed to parse URL from /pipelineis thrown whenaiRatelimit.limit()is called, which gets caught by the route's try-catch and returned as a generic 500 error to the client with message:"Failed to parse URL from /pipeline".Expected: Module should fail fast at startup with clear error message:
"Missing required environment variables for rate limiting: KV_REST_API_URL and KV_REST_API_TOKEN. Please configure your Upstash Redis credentials in your environment."Why this matters: Without validation at startup, developers see a cryptic error message at runtime instead of knowing exactly which environment variables are missing. This makes debugging deployments much harder. Compare to industry standard practice where required configuration is validated on application startup.
Tested with: @upstash/redis 1.35.7, @upstash/ratelimit 2.0.7 - confirmed that empty string credentials pass initialization but fail on first API call with Invalid URL error.