# @upstash/ratelimit setup: pick the algorithm that fits your bursts

## Basic setup

npm install @upstash/ratelimit @upstash/redis

import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(10, "10 s"),
  analytics: true,
  prefix: "@upstash/ratelimit",
});

const { success } = await ratelimit.limit("api");
if (!success) {
  return new Response("Too many requests", { status: 429 });
}

Use a user ID, API key, or IP as the identifier to limit per caller, or
a constant string to limit globally.

## Which algorithm

- Fixed window (10 per 10s): cheapest (2-3 commands per limit call).
  Bursts can leak through at window boundaries.
- Sliding window: smoother, fixes the boundary burst, costs more
  (4-5 commands per call) and is only an approximation.
- Token bucket: constant-rate processing with configurable burst via
  maxTokens. Most expensive computationally.

All three support dynamic limits. Token bucket is not supported in the
multi-region setup.

## Cost awareness

Each limit() call runs Lua plus bookkeeping commands. With analytics
on, add one more command per call. At 1M requests a day on sliding
window with analytics, that is roughly 5M commands a day: budget for
it or use fixed window.

## Other methods

- blockUntilReady: wait until the limiter allows the request.
- resetUsedTokens: clear state for an identifier.
- getRemaining: check remaining quota without consuming.