> ## Documentation Index
> Fetch the complete documentation index at: https://docs.turbostack.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Rate Limiting your API

> At the end of this tutorial, you'll have a rate limit to protect your API from abuses and attacks.

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](https://upstash.com) packages to apply rate limiting into our application.

## Setup Upstash

1. Sign up on [Upstash](https://console.upstash.com/login)
2. Create a new [Redis Database](https://console.upstash.com/redis).
3. Add the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` into your `.env.local` file.

```bash theme={null}
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`.

```ts theme={null}
import { ratelimit } from '@/lib/upstash';
```

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

```ts theme={null}
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.' })
}
```
