Upstash Ratelimit
Overview
@upstash/ratelimit implements distributed rate limiting on top of Upstash
Redis. Because state lives in Redis, every instance of a serverless function
or edge worker shares the same counters, which an in-memory limiter cannot
do. It ships three algorithms (fixed window, sliding window, token bucket),
per-identifier keys, optional in-memory blocking of already-limited
identifiers, and optional analytics.
When to Use This Skill
- Use when the user needs to limit requests per IP, user, API key, or tenant
across multiple serverless instances or regions.
- Use when protecting login, signup, form, webhook, or LLM endpoints from
abuse and returning
429 Too Many Requests.
- Use when choosing between fixed window, sliding window, and token bucket.
- Do not use for client-side retry/backoff against a third-party API's limits;
see
api-rate-limit-handler.
- Do not use for a single long-running process with no shared state; an
in-memory limiter is simpler there.
How It Works
Step 1: Install and configure
npm install @upstash/ratelimit @upstash/redis
Set UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN in the environment.
Step 2: Create the limiter once, outside the handler
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
export const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, "10 s"), // 10 requests per 10 seconds
prefix: "rl:api",
analytics: true,
});
Constructing the limiter at module scope lets the built-in ephemeral cache
short-circuit blocked identifiers without a Redis call.
Step 3: Call limit() with a stable identifier
const { success, limit, remaining, reset, pending } = await ratelimit.limit(userId);
success is false when the identifier is over its limit. reset is a Unix
timestamp in milliseconds. pending is a promise for background work
(analytics, multi-region sync); await it or pass it to waitUntil on edge
runtimes so the function is not frozen before it completes.
Examples
Example 1: Next.js middleware returning 429
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { NextResponse, type NextRequest } from "next/server";
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(20, "1 m"),
});
export async function middleware(request: NextRequest) {
const ip = request.headers.get("x-forwarded-for") ?? "anonymous";
const { success, limit, remaining, reset } = await ratelimit.limit(ip);
if (!success) {
return new NextResponse("Too Many Requests", {
status: 429,
headers: {
"X-RateLimit-Limit": String(limit),
"X-RateLimit-Remaining": String(remaining),
"X-RateLimit-Reset": String(reset),
"Retry-After": String(Math.ceil((reset - Date.now()) / 1000)),
},
});
}
return NextResponse.next();
}
export const config = { matcher: "/api/:path*" };
Example 2: Token bucket with per-plan limits
const limiters = {
free: new Ratelimit({
redis: Redis.fromEnv(),
prefix: "rl:free",
limiter: Ratelimit.tokenBucket(5, "10 s", 10), // refill 5 per 10 s, burst 10
}),
pro: new Ratelimit({
redis: Redis.fromEnv(),
prefix: "rl:pro",
limiter: Ratelimit.tokenBucket(50, "10 s", 100),
}),
};
const { success } = await limiters[plan].limit(apiKey);
Best Practices
- ✅ Use a stable, low-cardinality identifier (user id, API key, tenant) where
possible; fall back to IP only for anonymous traffic.
- ✅ Set a distinct
prefix per endpoint or plan so limits do not collide.
- ✅ Return
Retry-After and X-RateLimit-* headers with 429 responses.
- ✅ Prefer
slidingWindow for most APIs; use tokenBucket when short bursts
are acceptable; use fixedWindow when the lowest Redis cost matters.
- ❌ Don't construct a new
Ratelimit inside the request handler.
- ❌ Don't rely on
pending completing on its own in edge runtimes.
- ❌ Don't rate limit by
x-forwarded-for without validating it is set by
your proxy; clients can spoof it otherwise.
Limitations
- Requires an Upstash Redis database; it does not work with other Redis
servers or without network access.
- Each
limit() call is at least one HTTP round trip to Redis, so it adds
latency to every request it guards.
- Sliding window is an approximation that assumes an even spread of requests
in the previous window; it is not an exact log.
MultiRegionRatelimit trades strict accuracy for lower latency and does
not support the token bucket algorithm.
- If Redis is unreachable, the default
timeout (5 s) lets requests through
(reason: "timeout"); this fails open, not closed.
- This skill does not replace environment-specific validation, testing, or
expert review.
Security & Safety Notes
- Rate limiting is one layer of abuse protection, not authentication. Pair it
with auth and input validation.
- The Redis token grants full database access; keep it server-side.
- Changing limits in production can lock out legitimate users. Confirm the
numbers with the user before deploying stricter limits.
Common Pitfalls
- Problem: Every request is allowed even after the limit.
Solution: Each identifier must be the same string across requests;
check that the identifier is not
undefined or a fresh random value.
- Problem: Analytics are empty on Vercel Edge or Cloudflare Workers.
Solution: Pass
pending to waitUntil (ctx.waitUntil(pending)) so
the background request is not cancelled when the response is sent.
Related Skills
@upstash-redis - The client this package uses for storage.
@api-rate-limit-handler - Client-side backoff and retry when you are the
one being rate limited.
@upstash-qstash - Queue and smooth traffic to downstream services instead
of rejecting it.
Additional Resources
1---2name: upstash-ratelimit3description: "Add rate limiting to API routes, middleware, and edge functions with @upstash/ratelimit: sliding window, fixed window, and token bucket backed by Upstash Redis."4category: backend5risk: critical6source: self7source_type: self8date_added: "2026-08-31"9author: CahidArda10tags: [upstash, rate-limiting, redis, serverless, edge, middleware, 429]11tools: [claude, codex, cursor, gemini]12metadata:13 source: https://skillmd.com/skills/francostino/upstash-ratelimit14---1516# Upstash Ratelimit1718## Overview1920`@upstash/ratelimit` implements distributed rate limiting on top of Upstash21Redis. Because state lives in Redis, every instance of a serverless function22or edge worker shares the same counters, which an in-memory limiter cannot23do. It ships three algorithms (fixed window, sliding window, token bucket),24per-identifier keys, optional in-memory blocking of already-limited25identifiers, and optional analytics.2627## When to Use This Skill2829- Use when the user needs to limit requests per IP, user, API key, or tenant30 across multiple serverless instances or regions.31- Use when protecting login, signup, form, webhook, or LLM endpoints from32 abuse and returning `429 Too Many Requests`.33- Use when choosing between fixed window, sliding window, and token bucket.34- Do not use for client-side retry/backoff against a third-party API's limits;35 see `api-rate-limit-handler`.36- Do not use for a single long-running process with no shared state; an37 in-memory limiter is simpler there.3839## How It Works4041### Step 1: Install and configure4243```bash44npm install @upstash/ratelimit @upstash/redis45```4647Set `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` in the environment.4849### Step 2: Create the limiter once, outside the handler5051```typescript52import { Ratelimit } from "@upstash/ratelimit";53import { Redis } from "@upstash/redis";5455export const ratelimit = new Ratelimit({56 redis: Redis.fromEnv(),57 limiter: Ratelimit.slidingWindow(10, "10 s"), // 10 requests per 10 seconds58 prefix: "rl:api",59 analytics: true,60});61```6263Constructing the limiter at module scope lets the built-in ephemeral cache64short-circuit blocked identifiers without a Redis call.6566### Step 3: Call `limit()` with a stable identifier6768```typescript69const { success, limit, remaining, reset, pending } = await ratelimit.limit(userId);70```7172`success` is `false` when the identifier is over its limit. `reset` is a Unix73timestamp in milliseconds. `pending` is a promise for background work74(analytics, multi-region sync); await it or pass it to `waitUntil` on edge75runtimes so the function is not frozen before it completes.7677## Examples7879### Example 1: Next.js middleware returning 4298081```typescript82import { Ratelimit } from "@upstash/ratelimit";83import { Redis } from "@upstash/redis";84import { NextResponse, type NextRequest } from "next/server";8586const ratelimit = new Ratelimit({87 redis: Redis.fromEnv(),88 limiter: Ratelimit.slidingWindow(20, "1 m"),89});9091export async function middleware(request: NextRequest) {92 const ip = request.headers.get("x-forwarded-for") ?? "anonymous";93 const { success, limit, remaining, reset } = await ratelimit.limit(ip);9495 if (!success) {96 return new NextResponse("Too Many Requests", {97 status: 429,98 headers: {99 "X-RateLimit-Limit": String(limit),100 "X-RateLimit-Remaining": String(remaining),101 "X-RateLimit-Reset": String(reset),102 "Retry-After": String(Math.ceil((reset - Date.now()) / 1000)),103 },104 });105 }106 return NextResponse.next();107}108109export const config = { matcher: "/api/:path*" };110```111112### Example 2: Token bucket with per-plan limits113114```typescript115const limiters = {116 free: new Ratelimit({117 redis: Redis.fromEnv(),118 prefix: "rl:free",119 limiter: Ratelimit.tokenBucket(5, "10 s", 10), // refill 5 per 10 s, burst 10120 }),121 pro: new Ratelimit({122 redis: Redis.fromEnv(),123 prefix: "rl:pro",124 limiter: Ratelimit.tokenBucket(50, "10 s", 100),125 }),126};127128const { success } = await limiters[plan].limit(apiKey);129```130131## Best Practices132133- ✅ Use a stable, low-cardinality identifier (user id, API key, tenant) where134 possible; fall back to IP only for anonymous traffic.135- ✅ Set a distinct `prefix` per endpoint or plan so limits do not collide.136- ✅ Return `Retry-After` and `X-RateLimit-*` headers with 429 responses.137- ✅ Prefer `slidingWindow` for most APIs; use `tokenBucket` when short bursts138 are acceptable; use `fixedWindow` when the lowest Redis cost matters.139- ❌ Don't construct a new `Ratelimit` inside the request handler.140- ❌ Don't rely on `pending` completing on its own in edge runtimes.141- ❌ Don't rate limit by `x-forwarded-for` without validating it is set by142 your proxy; clients can spoof it otherwise.143144## Limitations145146- Requires an Upstash Redis database; it does not work with other Redis147 servers or without network access.148- Each `limit()` call is at least one HTTP round trip to Redis, so it adds149 latency to every request it guards.150- Sliding window is an approximation that assumes an even spread of requests151 in the previous window; it is not an exact log.152- `MultiRegionRatelimit` trades strict accuracy for lower latency and does153 not support the token bucket algorithm.154- If Redis is unreachable, the default `timeout` (5 s) lets requests through155 (`reason: "timeout"`); this fails open, not closed.156- This skill does not replace environment-specific validation, testing, or157 expert review.158159## Security & Safety Notes160161- Rate limiting is one layer of abuse protection, not authentication. Pair it162 with auth and input validation.163- The Redis token grants full database access; keep it server-side.164- Changing limits in production can lock out legitimate users. Confirm the165 numbers with the user before deploying stricter limits.166167## Common Pitfalls168169- **Problem:** Every request is allowed even after the limit.170 **Solution:** Each identifier must be the same string across requests;171 check that the identifier is not `undefined` or a fresh random value.172- **Problem:** Analytics are empty on Vercel Edge or Cloudflare Workers.173 **Solution:** Pass `pending` to `waitUntil` (`ctx.waitUntil(pending)`) so174 the background request is not cancelled when the response is sent.175176## Related Skills177178- `@upstash-redis` - The client this package uses for storage.179- `@api-rate-limit-handler` - Client-side backoff and retry when you are the180 one being rate limited.181- `@upstash-qstash` - Queue and smooth traffic to downstream services instead182 of rejecting it.183184## Additional Resources185186- [Upstash Ratelimit documentation](https://upstash.com/docs/redis/sdks/ratelimit-ts/overview)187- [@upstash/ratelimit on GitHub](https://github.com/upstash/ratelimit-js)188- [Algorithms guide](https://upstash.com/docs/redis/sdks/ratelimit-ts/algorithms)