Server-Side Rate Limiting Implementation Plan
Pattern Application: Reflection (Self-Critique)
This is a significant security feature (50+ lines) - applying reflection pattern.
Architecture Overview
Service Boundary
- Utility Layer: Reusable rate limiting logic at
/src/lib/rate-limit-server.ts - API Layer: Integration at route handlers (chat, analyze, journal, thesis)
- Algorithm: Sliding window for accurate rate tracking
- Storage: In-memory Map (simple, effective for single-instance deployments)
Key Design Decisions
Approach A: Sliding Window Counter
- Pros: Accurate rate limiting, smooth traffic distribution
- Pros: Prevents burst attacks at window boundaries
- Cons: Slightly more complex than fixed window
Approach B: Fixed Window
- Pros: Simpler implementation
- Cons: Vulnerable to burst at window boundaries (2x limit possible)
- Cons: Less fair to legitimate users
Approach C: Token Bucket
- Pros: Allows controlled bursts
- Cons: More complex, may allow abuse patterns
- Cons: Harder to reason about for users
RECOMMENDATION: Approach A (Sliding Window) - Best balance of accuracy, fairness, and security.
Implementation Steps
Step 1: Create Rate Limit Utility
File: /Users/eddiebelaval/Development/deepstack/web/src/lib/rate-limit-server.ts
Features:
- Sliding window algorithm with configurable window size
- Per-IP tracking using NextRequest
- Automatic cleanup of expired entries
- Type-safe configuration
- Standard HTTP 429 responses with proper headers
Response Headers:
X-RateLimit-Limit: Total requests allowedX-RateLimit-Remaining: Requests remaining in windowX-RateLimit-Reset: Unix timestamp when limit resetsRetry-After: Seconds until requests allowed again
Edge Cases Handled:
- Missing IP addresses (localhost, proxies) - use fallback key
- Memory cleanup to prevent unbounded growth
- Clock skew tolerance
- Concurrent request handling
Step 2: Update API Routes
Routes to Protect:
/api/chat- Most critical (expensive LLM calls)/api/analyze- Moderate (external API calls)/api/journal- Lower priority (CRUD operations)/api/thesis- Lower priority (CRUD operations)
Configuration:
/api/chat: 20 requests/minute (AI calls are expensive)/api/analyze: 60 requests/minute (moderate)/api/journal: 100 requests/minute (standard CRUD)/api/thesis: 100 requests/minute (standard CRUD)
Integration Pattern:
// Early in handler, before expensive operations
const rateLimitResult = await checkRateLimit(request, config);
if (!rateLimitResult.success) {
return rateLimitResult.response; // 429 with headers
}
Step 3: Verification Checklist (PEV Pattern)
After implementation, verify:
- Can make requests within limit
- Blocked when limit exceeded
- Proper 429 response with headers
- Rate limit resets after window
- Different IPs tracked independently
- Memory doesn't grow unbounded
- Client-side rate-limit.ts can parse headers
Technology Stack
Core: TypeScript + Next.js Edge Runtime
Storage: In-memory Map (single instance)
Algorithm: Sliding Window Counter
IP Detection: NextRequest headers (x-forwarded-for, x-real-ip)
Scaling Considerations
Current Solution (In-Memory)
Works for: Single-instance deployments, moderate traffic Limitations:
- Lost on server restart
- Not shared across instances
- Memory bounded by single process
Future Scaling Options
- Redis: Distributed rate limiting across instances
- Upstash Redis: Serverless-friendly with global edge
- Database: Store rate limit data in Supabase/Postgres
- Cloudflare Rate Limiting: Move to edge layer
When to scale:
- Multiple server instances deployed
10K requests/minute
- Distributed architecture needed
Security Patterns
Rate Limiting Strategy
- Tiered limits: Different limits per endpoint based on cost
- IP-based: Primary identifier (simple, effective)
- Graceful degradation: Service stays up, just rate limited
Future Enhancements
- User-based limits: Track by authenticated user ID
- API keys: Different tiers for different customers
- Bypass tokens: Allow certain IPs/users through
- Dynamic limits: Adjust based on system load
Files to Create/Modify
New Files
/Users/eddiebelaval/Development/deepstack/web/src/lib/rate-limit-server.ts(new utility)
Modified Files
/Users/eddiebelaval/Development/deepstack/web/src/app/api/chat/route.ts/Users/eddiebelaval/Development/deepstack/web/src/app/api/analyze/route.ts/Users/eddiebelaval/Development/deepstack/web/src/app/api/journal/route.ts/Users/eddiebelaval/Development/deepstack/web/src/app/api/thesis/route.ts
Reflection: Self-Critique
Potential Issues:
- Memory leak risk: Need cleanup mechanism for old entries
- Solution: Periodic cleanup on each request, remove entries > 2x window
- Race conditions: Concurrent requests might bypass limit
- Solution: Acceptable for in-memory; use atomic ops if needed
- IP spoofing: Headers can be forged
- Solution: Trust reverse proxy headers, use multiple fallbacks
- Cold start: All limits reset on server restart
- Solution: Acceptable for now; use Redis for persistence if needed
Edge Cases:
- What if no IP available? Use fallback "unknown" key with stricter limit
- What about proxies/NAT? Multiple users, same IP - acceptable tradeoff
- Clock drift? Use consistent Date.now() throughout window
Simplification Opportunities:
- Could use library like
@upstash/ratelimit, but in-memory is simpler - Could implement leaky bucket, but sliding window is clearer
- Could add distributed locking, but overkill for single instance
Testing Strategy:
- Manual: Rapid requests to verify blocking
- Check headers in browser DevTools
- Verify reset after window expires
- Confirm different endpoints have different limits
Confidence Level
High Confidence on:
- Sliding window algorithm correctness
- Next.js Edge Runtime compatibility
- IP extraction patterns
- HTTP 429 response format
Medium Confidence on:
- Memory usage at scale (needs monitoring)
- Concurrent request handling (acceptable races)
Recommendation: This implementation is production-ready for single-instance deployments with moderate traffic. Monitor memory usage and migrate to Redis when scaling horizontally.