본문으로 건너뛰기
Skillpedia
자동화48k · #6071

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에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/upstash-ratelimit/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“로그인 페이지에 대해 사용자당 1분에 최대 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 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.

…

자주 묻는 질문

한도에 도달하면 어떻게 되나요?

한도를 넘은 사람은 오류 메시지(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.

repo: sickn33/agentic-awesome-skills

인기도

GitHub 스타
48k
순위
#6071
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬