# Source: https://upstash.com/docs/redis/overall/ratelimit.md

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

# Getting Started

## Create your Redis instance

For the rate limit to work, we need to create an Upstash Redis and get its credentials. To create an Upstash Redis, you can follow the [Upstash Redis "Get Started" guide](/redis/overall/getstarted).

## Add Ratelimit to Your Project

Once we have a Redis instance, next step is adding the rate limit to your project in its most basic form.

### Install Ratelimit

First, we need to install `@upstash/ratelimit`:

<Tabs>
  <Tab title="npm">
    ```bash  theme={"system"}
    npm install @upstash/ratelimit
    ```
  </Tab>

  <Tab title="deno">
    ```ts  theme={"system"}
    import { Ratelimit } from "https://cdn.skypack.dev/@upstash/ratelimit@latest";
    ```
  </Tab>
</Tabs>

### Add Ratelimit to Your Endpoint

Next step is to add Ratelimit to your endpoint. In the example below, you can see how to initialize a Ratelimit and use it:

```ts  theme={"system"}
import { Ratelimit } from "@upstash/ratelimit"; // for deno: see above
import { Redis } from "@upstash/redis";

// Create a new ratelimiter, that allows 10 requests per 10 seconds
const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(10, "10 s"),
  analytics: true,
  /**
   * Optional prefix for the keys used in redis. This is useful if you want to share a redis
   * instance with other applications and want to avoid key collisions. The default prefix is
   * "@upstash/ratelimit"
   */
  prefix: "@upstash/ratelimit",
});

// Use a constant string to limit all requests with a single ratelimit
// Or use a userID, apiKey or ip address for individual limits.
const identifier = "api";
const { success } = await ratelimit.limit(identifier);

if (!success) {
  return "Unable to process at this time";
}
doExpensiveCalculation();
return "Here you go!";
```

For Cloudflare Workers and Fastly Compute\@Edge, you can use the following imports:

```ts  theme={"system"}
import { Redis } from "@upstash/redis/cloudflare"; // for cloudflare workers and pages
import { Redis } from "@upstash/redis/fastly"; // for fastly compute@edge
```

In this example, we initialize a Ratelimit with an Upstash Redis. The Uptash Redis instance is created from the environment variables and passed to the Ratelimit instance. Then, we check the access rate using the `ratelimit.limit(identifier)` method. If the `success` field is true, we allow the expensive calculation to go through.

For more examples, see the [Examples](/redis/sdks/ratelimit-ts/overview#examples).

### Set Environment Variables

Final step is to update the environment variables so that the Ratelimit can communicate with the Upstash Redis. `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables must be set in order for the `Redis.fromEnv()` command to work. You can get the values of these environment variables from the [Upstash Console](https://console.upstash.com/redis) by navigating to the page of the Redis instance you created.

An alternative of using the `Redis.fromEnv()` method is to pass the variables yourself. This can be useful if you save these environment variables with a different name:

```ts  theme={"system"}
new Redis({
  url: "https://****.upstash.io",
  token: "********",
});
```

Here is how you can set the environment variables in different cases:

<Tabs>
  <Tab title="Vercel">
    Go to the "Settings" tab in your project. In the menu to the left, click "Environment Variables". Add `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables and their values.
  </Tab>

  <Tab title="Cloudflare Worker (Wrangler)">
    Run:

    ```
    npx wrangler secret put UPSTASH_REDIS_REST_URL
    ```

    When prompted, enter the value of `UPSTASH_REDIS_REST_URL` when prompted. Do the same for `UPSTASH_REDIS_REST_TOKEN`:

    ```
    npx wrangler secret put UPSTASH_REDIS_REST_TOKEN
    ```
  </Tab>

  <Tab title="Local Nextjs Project">
    Go to the `.env.local` file and add the environment variables:

    ```
    UPSTASH_REDIS_REST_URL=****
    UPSTASH_REDIS_REST_TOKEN=****
    ```
  </Tab>
</Tabs>

## Serverless Environments

When we use ratelimit in a serverless environment like CloudFlare Workers or Vercel Edge,
we need to be careful about making sure that the rate limiting operations complete correctly
before the runtime ends after returning the response.

This is important in two cases where we do some operations in the background asynchronously after `limit` is called:

1. Using MultiRegion: synchronize Redis instances in different regions
2. Enabling analytics: send analytics to Redis

In these cases, we need to wait for these operations to finish before sending the response to the user. Otherwise, the runtime will end and we won't be able to complete our chores.

In order to wait for these operations to finish, use the `pending` promise:

```ts  theme={"system"}
const { pending } = await ratelimit.limit("id");
context.waitUntil(pending);
```

See more information on `context.waitUntil` at
[Cloudflare](https://developers.cloudflare.com/workers/runtime-apis/context/#waituntil)
and [Vercel](https://vercel.com/docs/functions/edge-middleware/middleware-api#waituntil).
You can also utilize [`waitUntil` from Vercel Functions API](https://vercel.com/docs/functions/functions-api-reference#waituntil).

## Customizing the Ratelimit Algorithm

There are several algorithms we can use for rate limiting. Explore the different rate-limiting algorithms available; how they work, their advantages and disadvantages in the [Algorithms page](/redis/sdks/ratelimit-ts/algorithms). You can learn about the **cost in terms of the number of commands**, by referring to the [Costs page](/redis/sdks/ratelimit-ts/costs).

## Methods

In our example, we only used the `limit` method. There are other methods we can use in the Ratelimit. These are:

* `blockUntilReady`: Process a request only when the rate-limiting algorithm allows it.
* `resetUsedTokens`: Reset the rate limiter state for some identifier.
* `getRemaining`: Get the remaining tokens/requests left for some identifier.

To learn more about these methods, refer to the [Methods page](/redis/sdks/ratelimit-ts/methods).

## Features

To configure the your Ratelimit according to your needs, you can make use of several features:

<CardGroup cols={2}>
  <Card title="Caching" icon="shield-halved" href="/redis/sdks/ratelimit-ts/features#caching">
    Handle blocked requests without having to call your Redis Database
  </Card>

  <Card title="Timeout" icon="stopwatch" href="/redis/sdks/ratelimit-ts/features#timeout">
    If the Redis call of the ratelimit is not resolved in some timeframe, allow
    the request by default
  </Card>

  <Card title="Analytics & Dashboard" icon="magnifying-glass-chart" href="/redis/sdks/ratelimit-ts/features#analytics-and-dashboard">
    Collect information on which identifiers made how many requests and how many
    were blocked
  </Card>

  <Card title="Traffic Protection" icon="lock" href="/redis/sdks/ratelimit-ts/traffic-protection">
    Create a deny list to block requests based on user agents, countries, IP
    addresses an more
  </Card>

  <Card title="Custom Rates" icon="chart-simple" href="/redis/sdks/ratelimit-ts/features#custom-rates">
    Consume different amounts of tokens in different requests (example: limiting
    based on request/response size)
  </Card>

  <Card title="Multi Region" icon="globe" href="/redis/sdks/ratelimit-ts/features#multi-region">
    Utilize several Redis databases in different regions to serve users faster
  </Card>

  <Card title="Multiple Limits" icon="gears" href="/redis/sdks/ratelimit-ts/features#using-multiple-limits">
    Use different limits for different kinds of requests (example: paid and free
    users)
  </Card>

  <Card title="Dynamic Limits" icon="sliders" href="/redis/sdks/ratelimit-ts/features#dynamic-limits">
    Change rate limits at runtime without recreating the rate limiter instance
  </Card>
</CardGroup>

For more information about the features, see the [Features page](/redis/sdks/ratelimit-ts/features).