Aller au contenu
Skillpedia
Automatisations48k · #6071

upstash-ratelimit

Ce qu’il fait

Cet outil vous aide à contrôler le nombre de fois qu'un utilisateur ou un système peut accéder à une partie précise d'un site ou d'une application pendant une certaine durée. Il prévient les abus en empêchant quelqu'un d'envoyer trop de requêtes trop rapidement.

Quand l’utiliser

  • ✓Protéger les formulaires de contact contre le spam.
  • ✓Limiter les tentatives de connexion pour prévenir les attaques.
  • ✓Contrôler l'utilisation de l'API pour éviter la surcharge.

Lien du skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/upstash-ratelimit/SKILL.md

Copiez-le et collez-le dans votre IA (Claude, ChatGPT ou Cursor) en lui demandant de suivre les instructions.

Comment l’utiliser

Le plus simple : copiez le message et collez-le dans votre IA. Elle lit le skill et suit les instructions.

Message prêt à coller

Utilise ce skill pour m’aider : https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/upstash-ratelimit/SKILL.md Lis le fichier SKILL.md de ce lien et suis ses instructions pour ma tâche.
Envie que votre IA trouve seule des skills comme celui-ci ?Installez le MCP gratuit de Skillpedia : une ligne, et elle cherche parmi 15 000+ skills avant chaque tâche.Installer en 1 minute →

Exemple de demande à votre IA

“Je souhaite limiter l'accès à ma page de connexion à 5 tentatives maximum par minute et par utilisateur.”

5 nouveaux skills par semaine. 1 minute de lecture.

Comment ça marche

L'outil utilise une base de données appelée Redis pour compter les requêtes. À chaque accès à une ressource protégée, un compteur est mis à jour dans Redis. Si le compteur atteint la limite, l'accès est bloqué temporairement.

Contenu technique (SKILL.md original)

Texte original de l’auteur, en anglais, directement depuis 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.

…

Questions fréquentes

Que se passe-t-il lorsque la limite est atteinte ?

La personne qui a dépassé la limite reçoit un message d'erreur (code 429) et ne peut plus accéder à la ressource pendant un certain temps.

Puis-je définir des limites différentes pour différents utilisateurs ?

Oui, vous pouvez définir des limites en fonction d'identifiants uniques, comme l'identifiant de l'utilisateur, la clé API ou même l'adresse IP.

Ai-je besoin d'un serveur spécial pour l'utiliser ?

Oui, cet outil nécessite une base de données Upstash Redis, qui est un service distinct.

Détails

Description originale de l’auteur

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

Popularité

Étoiles GitHub
48k
Position au classement
#6071
Licence
MIT
Mis à jour
15/10/2026

Ce skill vous est-il utile ?

0

Connectez-vous pour voter.

Commentaires

  • …

Autres skills de ce dépôt

Skills similaires