Neural Code Reviewer

AI-Powered
feat: Add rate limiting to API endpoints
PR #847 · opened by @developer · 3 files changed · +127 -23
src/middleware/rateLimit.ts
import { Redis } from 'ioredis';
+ import { RateLimiter } from '@/lib/rate-limiter';
+ import { logger } from '@/lib/logger';
- const limit = 100;
+ const RATE_LIMIT = parseInt(process.env.RATE_LIMIT || '100');
+ const WINDOW_MS = 60 * 1000;
+ export async function rateLimit(req: Request) {
+ const ip = req.headers.get('x-forwarded-for');
+ const key = `rate:${ip}`;
+ const limiter = new RateLimiter(RATE_LIMIT, WINDOW_MS);
+ return limiter.check(key);
+ }
AI REVIEW Analysis Results
SECURITY
The x-forwarded-for header can be spoofed. Consider using a trusted proxy configuration or falling back to req.socket.remoteAddress for accurate client identification.
SUGGESTION
The RateLimiter instance is created per-request. Move instantiation outside the function to reuse the Redis connection pool and reduce overhead.
PERFORMANCE
Consider using a sliding window algorithm instead of fixed windows to prevent burst traffic at window boundaries. The current implementation allows up to 2x the rate limit during window transitions.
87
Approved with suggestions. Code quality is high. 3 items to address before merge.