upstash-ratelimit
它能做什么
这个工具可以控制用户或系统在一定时间内访问网站或应用某个特定部分的次数。通过阻止有人在短时间内发出过多请求,它能防止滥用。
适用场景
- ✓保护联系表单免受垃圾信息骚扰。
- ✓限制登录尝试次数,防止攻击。
- ✓控制 API 的使用量,避免过载。
技能链接
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/upstash-ratelimit/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“我想限制每个用户每分钟最多只能尝试登录 5 次,访问我的登录页面。”
每周 5 个新技能,1 分钟读完。
工作原理
这个工具使用名为 Redis 的数据库来统计请求次数。每当有人访问受保护的内容时,Redis 中的计数器就会更新。如果计数达到上限,访问将被暂时阻止。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
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
prefixper endpoint or plan so limits do not collide. - ✅ Return
Retry-AfterandX-RateLimit-*headers with 429 responses. - ✅ Prefer
slidingWindowfor most APIs; usetokenBucketwhen short bursts are acceptable; usefixedWindowwhen the lowest Redis cost matters. - ❌ Don't construct a new
Ratelimitinside the request handler. - ❌ Don't rely on
pendingcompleting on its own in edge runtimes. - ❌ Don't rate limit by
x-forwarded-forwithout 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.
…
常见问题
达到上限后会发生什么?
超出限制的用户会收到一条错误信息(429 状态码),并且在一段时间内无法访问该资源。
我可以为不同的用户设置不同的限制吗?
可以,你可以根据用户 ID、API 密钥,甚至 IP 地址等唯一标识来设置限制。
使用这个工具需要专门的服务器吗?
需要,这个工具要求使用 Upstash Redis 数据库,它是一项独立的服务。
详情
作者的原始描述
Add rate limiting to API routes, middleware, and edge functions with @upstash/ratelimit: sliding window, fixed window, and token bucket backed by Upstash Redis.
热度
- GitHub 星标
- 48k
- 排名
- #6071
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …
同一仓库的更多技能
00-andruia-consultant
48k帮你的智能体启动或改进 AI 项目。它可以分析代码、推荐工具,并用西班牙语制定行动计划。
007
48k让你的智能体执行安全审计和威胁建模。它有助于保护项目免受攻击和漏洞的威胁。
10-andruia-skill-smith
48k帮你的智能体创建或改进 AI 工具。它可以定义工具的工作方式、编写文档,并验证其结构。
20-andruia-niche-intelligence
48k让你的智能体创建某个特定行业的摘要。它有助于借助可靠的信息来源,了解项目的背景、规则、使用模式和风险。