Branchwell

AI Resource Pro / website / docs / rate-limiting.md

Show the source

Rate Limiting System

This document explains how rate limiting works in the AI Resource Pro API and how to apply it to new API routes.

Overview

The API uses Upstash Redis to implement rate limiting on all CREATE, UPDATE, and DELETE operations. This helps protect the API from abuse and ensures fair usage.

Rate limits are set as follows:

  • Create operations: 10 requests per minute
  • Update operations: 20 requests per minute
  • Delete operations: 10 requests per minute
  • Authentication operations: 5 requests per 30 seconds

Implementation Details

Rate limiting is implemented using the @upstash/ratelimit library. There are two ways to apply rate limiting to an API route:

1. Direct Implementation

import { applyRateLimit, createRateLimit } from '@/lib/rate-limit';

export async function POST(request: NextRequest) {
  // Apply rate limiting
  const rateLimitResult = await applyRateLimit(request, createRateLimit);
  if (rateLimitResult && 'status' in rateLimitResult) {
    return rateLimitResult;
  }
  
  // Your handler code here
  
  // Add rate limit headers to the response
  const headers = rateLimitResult?.headers || new Headers();
  return NextResponse.json(data, { 
    status: 201,
    headers
  });
}

For new API routes, we recommend using the middleware approach for cleaner code:

import { withCreateRateLimit } from '@/lib/rate-limit-middleware';

// Define your handler without rate limiting
async function createHandler(request: NextRequest) {
  // Your handler code here
  return NextResponse.json(data, { status: 201 });
}

// Export the handler with rate limiting applied
export const POST = withCreateRateLimit(createHandler);

Rate Limit Headers

When rate limiting is applied, the following headers are included in the response:

  • X-RateLimit-Limit: Maximum number of requests allowed in the time window
  • X-RateLimit-Remaining: Number of requests remaining in the current time window
  • X-RateLimit-Reset: Timestamp when the rate limit will reset

Testing Rate Limits

You can test rate limits using the scripts/test-rate-limit.sh script:

# Run from the project root
./scripts/test-rate-limit.sh

This script will make multiple requests to the API until it hits the rate limit, then display information about the rate limiting behavior.

Identifying Users for Rate Limiting

By default, rate limiting is based on the client's IP address. You can customize this by providing an identifier function:

// Custom identifier based on user ID or API key
const customIdentifier = (req: NextRequest) => {
  return req.headers.get('x-api-key') || req.ip || 'anonymous';
};

export const POST = withCreateRateLimit(createHandler, customIdentifier);

Troubleshooting

If rate limiting is not working as expected:

  1. Check that Redis is configured correctly in the environment variables
  2. Verify that the rate limiter is being applied to the route
  3. Make sure the response includes the rate limit headers
  4. Check the server logs for any rate limit errors