Skip to content
Shell
6.4 KB
Raw Blame

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 allowed
  • X-RateLimit-Remaining: Requests remaining in window
  • X-RateLimit-Reset: Unix timestamp when limit resets
  • Retry-After: Seconds until requests allowed again

Edge Cases Handled:

  1. Missing IP addresses (localhost, proxies) - use fallback key
  2. Memory cleanup to prevent unbounded growth
  3. Clock skew tolerance
  4. Concurrent request handling

Step 2: Update API Routes

Routes to Protect:

  1. /api/chat - Most critical (expensive LLM calls)
  2. /api/analyze - Moderate (external API calls)
  3. /api/journal - Lower priority (CRUD operations)
  4. /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

  1. Redis: Distributed rate limiting across instances
  2. Upstash Redis: Serverless-friendly with global edge
  3. Database: Store rate limit data in Supabase/Postgres
  4. 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

  1. User-based limits: Track by authenticated user ID
  2. API keys: Different tiers for different customers
  3. Bypass tokens: Allow certain IPs/users through
  4. Dynamic limits: Adjust based on system load

Files to Create/Modify

New Files

  1. /Users/eddiebelaval/Development/deepstack/web/src/lib/rate-limit-server.ts (new utility)

Modified Files

  1. /Users/eddiebelaval/Development/deepstack/web/src/app/api/chat/route.ts
  2. /Users/eddiebelaval/Development/deepstack/web/src/app/api/analyze/route.ts
  3. /Users/eddiebelaval/Development/deepstack/web/src/app/api/journal/route.ts
  4. /Users/eddiebelaval/Development/deepstack/web/src/app/api/thesis/route.ts

Reflection: Self-Critique

Potential Issues:

  1. Memory leak risk: Need cleanup mechanism for old entries
    • Solution: Periodic cleanup on each request, remove entries > 2x window
  2. Race conditions: Concurrent requests might bypass limit
    • Solution: Acceptable for in-memory; use atomic ops if needed
  3. IP spoofing: Headers can be forged
    • Solution: Trust reverse proxy headers, use multiple fallbacks
  4. Cold start: All limits reset on server restart
    • Solution: Acceptable for now; use Redis for persistence if needed

Edge Cases:

  1. What if no IP available? Use fallback "unknown" key with stricter limit
  2. What about proxies/NAT? Multiple users, same IP - acceptable tradeoff
  3. 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.