-
Notifications
You must be signed in to change notification settings - Fork 72
feat: implement rate limiting with Redis #174
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
sujal111
wants to merge
1
commit into
AOSSIE-Org:main
Choose a base branch
from
sujal111:feature/rate-limiting
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.
+139
−5
Open
Changes from all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| from fastapi import APIRouter, Request, Depends | ||
| from fastapi_ratelimiter import rate_limiter | ||
|
|
||
| router = APIRouter(prefix="/test", tags=["test"]) | ||
|
|
||
| @router.get("/unlimited") | ||
| async def unlimited(): | ||
| """Unlimited endpoint for testing.""" | ||
| return {"message": "This is an unlimited endpoint"} | ||
|
|
||
| @router.get("/limited") | ||
| @rate_limiter.limit("5/minute") | ||
| async def limited(request: Request): | ||
| """Limited endpoint (5 requests per minute).""" | ||
| return { | ||
| "message": "This is a rate-limited endpoint (5 requests per minute)", | ||
| "remaining": request.state.rate_limit_remaining, | ||
| "reset": request.state.rate_limit_reset | ||
| } | ||
|
|
||
| @router.get("/user-limited") | ||
| @rate_limiter.limit("10/minute", key_func=lambda r: f"user:{r.client.host}") | ||
| async def user_limited(request: Request): | ||
| """User-specific rate limited endpoint (10 requests per minute per user).""" | ||
| return { | ||
| "message": "This is a user-specific rate-limited endpoint (10 requests per minute per user)", | ||
| "remaining": request.state.rate_limit_remaining, | ||
| "reset": request.state.rate_limit_reset | ||
| } |
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,55 @@ | ||
| import os | ||
| from typing import Optional | ||
| from fastapi import FastAPI, Request, status | ||
| from fastapi.responses import JSONResponse | ||
| from fastapi_ratelimiter import RedisDependencyMarker, RedisSettings, RateLimiter | ||
| from fastapi_ratelimiter.ratelimiting import RateLimitExceeded | ||
|
|
||
| # Configure Redis settings | ||
| redis_settings = RedisSettings( | ||
| host=os.getenv("REDIS_HOST", "localhost"), | ||
| port=int(os.getenv("REDIS_PORT", 6379)), | ||
| db=int(os.getenv("REDIS_DB", 0)), | ||
| password=os.getenv("REDIS_PASSWORD"), | ||
| ssl=os.getenv("REDIS_SSL", "false").lower() == "true", | ||
| ) | ||
|
|
||
| # Initialize the rate limiter | ||
| rate_limiter = RateLimiter( | ||
| redis_settings=redis_settings, | ||
| default_limits=["1000 per day", "100 per hour"], | ||
| default_limits_per_method=True, | ||
| default_limits_exempt_when=lambda request: request.method == "OPTIONS", | ||
| ) | ||
|
|
||
| async def rate_limit_exception_handler(request: Request, exc: RateLimitExceeded): | ||
| """Handle rate limit exceeded exceptions with a JSON response.""" | ||
| return JSONResponse( | ||
| status_code=status.HTTP_429_TOO_MANY_REQUESTS, | ||
| content={ | ||
| "detail": f"Rate limit exceeded. Try again in {exc.retry_after} seconds.", | ||
| "retry_after": exc.retry_after, | ||
| }, | ||
| headers={"Retry-After": str(exc.retry_after)}, | ||
| ) | ||
|
|
||
| def get_user_identifier(request: Request) -> str: | ||
| """Extract user identifier from request for rate limiting.""" | ||
| # Try to get user ID from JWT or session | ||
| auth_header = request.headers.get("Authorization") | ||
| if auth_header and auth_header.startswith("Bearer "): | ||
| token = auth_header.split(" ")[1] | ||
| return f"user:{token[:8]}" # Simplified token-based identifier | ||
|
|
||
| # Fall back to IP-based rate limiting | ||
| client_ip = request.client.host if request.client else "unknown" | ||
| return f"ip:{client_ip}" | ||
|
|
||
| def setup_rate_limiter(app: FastAPI): | ||
| """Set up rate limiting for the FastAPI application.""" | ||
| # Add rate limiter middleware | ||
| app.add_middleware(rate_limiter.middleware) | ||
| app.add_exception_handler(RateLimitExceeded, rate_limit_exception_handler) | ||
|
|
||
| # Add rate limiter to app state for easy access in routes | ||
| app.state.rate_limiter = rate_limiter |
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,15 @@ | ||
| fastapi==0.109.2 | ||
| uvicorn[standard]==0.27.1 | ||
| python-dotenv==1.0.1 | ||
| pydantic==2.7.1 | ||
| python-multipart==0.0.9 | ||
| httpx==0.27.0 | ||
| websockets==12.0 | ||
| python-jose[cryptography]==3.3.0 | ||
| passlib[bcrypt]==1.7.4 | ||
| python-multipart==0.0.9 | ||
| sqlalchemy==2.0.28 | ||
| psycopg2-binary==2.9.9 | ||
| python-jose[cryptography]==3.3.0 | ||
| python-multipart==0.0.9 | ||
| python-dotenv==1.0.1 |
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,11 @@ | ||
| from fastapi import FastAPI | ||
| import uvicorn | ||
|
|
||
| app = FastAPI() | ||
|
|
||
| @app.get("/") | ||
| async def read_root(): | ||
| return {"message": "Devr.AI Backend is running!"} | ||
|
|
||
| if __name__ == "__main__": | ||
| uvicorn.run("test_server:app", host="0.0.0.0", port=8000, reload=True) |
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.
Fix Redis password default to avoid auth mismatch and weak default
The new Redis service wiring and decoupling Falkordb ports look good, but this line is risky:
If
REDIS_PASSWORDisn’t set, Redis will requireyour_secure_passwordwhileapp.core.rate_limiter.redis_settingswill try connecting with no password, causing auth failures and leaving an extremely weak default secret in any environment that forgets to set it.Consider instead requiring the env var explicitly:
and ensure
REDIS_PASSWORDis always set via.env/ secrets for both Redis and the backend. Also double‑check thatREDIS_HOSTfor the app is set to the service nameredisso connections work correctly in this compose network.Also applies to: 63-64, 78-79