Rate limiting is a critical technique to ensure the stability and performance of your system. By controlling the number of requests a user or client can make within a given time frame, you protect your API from overuse, abuse, or even potential attacks, like DDoS.

TurboStack uses Upstash packages to apply rate limiting into our application.

Setup Upstash

  1. Sign up on Upstash
  2. Create a new Redis Database.
  3. Add the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN into your .env.local file.
UPSTASH_REDIS_REST_URL={{YOUR_REDIS_DATABASE_GENERATED_URL}}
UPSTASH_REDIS_REST_TOKEN={{YOUR_REDIS_DATABASE_AUTHENTICATION_TOKEN}}

Rate limiting an API Route

TurboStack have an util function called ratelimit, resided at apps/web/lib/upstash/ratelimit.ts.

import { ratelimit } from '@/lib/upstash';

To apply a certain ratelimit into an API Route, you can do as the following example:

import { ipAddress } from '@vercel/functions';
import { ratelimit } from '@/lib/upstash';

export async function GET(req: Request) {
  const numberOfRequests = 100
  const interval  '5 m'
  const ip = ipAddress(req);

  const { success } = await ratelimit(
    numberOfRequests,
    interval
  ).limit(`a-dynamic-key:${ip}`)

  if (!success) {
    return new Response('Rate Limit exceeded. Try again later', { status: 403 })
  }

  return NextResponse.json({ message: 'This request was handled successfully.' })
}