/rate-limit

Upstash limits on Next.js routes with trusted identifiers, 429 headers and outage rules.

Build·Traffic → Limits·54 installs·verified in Claude Code·MIT
$npx skills add tushaarmehtaa/tushar-skills --skill rate-limit -g -a claude-code -y

Then type /rate-limit in Claude Code, or describe the task and let it pick the skill.

What you get back contract tests · 10 Oct 2026

claude · tallyroom

Using /rate-limit
  • Redis down → rejects with 503
  • Spoofed IP headers ignored
  • 12 tests pass
Both routes are limited, and they stay shut when Redis is down.
Claude Code 2.1.295·2m 32s·9 files changed
  • I've added both routes with stubbed OCR and email, and both are rate-limited with Upstash. The tests and the production build pass. I haven't seen a request get through yet: the Upstash credentials in .env.local are fake test values, so every request I sent ended at the "Redis unreachable" path.
  • Why it rejects when Redis is down: both routes cost money or send email, so they reject rather than run unmetered. Upstash's library lets a request through when Redis is slow, so I treat that case as an outage too.
  • A client-supplied x-forwarded-for is ignored, so spoofing it doesn't get around the limit.
CaveatRan with test keys; never called a live Upstash database.

Measured before → after

RouteLimited byLimitIf Redis is down
POST /api/receipts/scanclient IPburst of 5, then about 1 every 2 minutesrejects with 503 and Retry-After: 30
everyone combined300 per hour, a cap on total OCR spendrejects with 503
POST /api/invitesclient IP10 per hourrejects with 503
recipient email (stored as a hash)3 per 24 hours, so nobody can flood one inboxrejects with 503

Input → output from the run

What was asked
We're adding two API routes to Tallyroom: POST /api/receipts/scan, which calls a paid OCR service, and POST /api/invites, which emails an invite link. Create them (stub the OCR and email parts) and stop people from hammering them. Upstash Redis credentials are in .env.local.
lib/rate-limit.js (new)
// Policy table. Each route checks its rules in order and stops at the first block.
export const policies = {
  receiptScan: () => [
    // Per client: a handful of scans in a burst, about one every 2 minutes after that.
    { name: "receipt-scan:ip", limiter: limiter("receipt-scan:ip", Ratelimit.tokenBucket(1, "2 m", 5)) },
    // Global ceiling on paid OCR calls. Caps spend even if someone rotates IPs.
    { name: "receipt-scan:global", limiter: limiter("receipt-scan:global", Ratelimit.fixedWindow(300, "1 h")), key: "all" },
  ],
  invites: () => [
    { name: "invites:ip", limiter: limiter("invites:ip", Ratelimit.slidingWindow(10, "1 h")) },
    // Per recipient: stops anyone from flooding one inbox with invites.
    { name: "invites:recipient", limiter: limiter("invites:recipient", Ratelimit.slidingWindow(3, "24 h")) },
  ],
};

When to use it

Use when

Use when protecting Next.js routes from abuse or runaway cost.

Skip it when

Skip it if you are not on Upstash Redis, or expect rate limits alone to stop abuse; they are one layer.

The thinking behind it

Every public route is a bill waiting to happen. Limit by who's calling, decide what happens when Redis is down, and abuse stops costing you.

Output contract from the skill's Output section

Report the policy table, identifier trust model, files/env names changed, outage behavior, response headers, layered controls, automated test evidence, and remaining Upstash/deployment configuration.

How it checks its own work from the instructions

  • Allowed, blocked, and reset behavior tested with a controllable clock
  • Spoofed forwarding headers are tested
  • Route isolation and anonymous versus authenticated keys are tested
  • Store timeout and outage behavior is tested

Requirements what it needs

Works in
Codex, Claude Code, Cursor
Needs
project files, terminal commands, network access

The instructions SKILL.md · 31 lines

Instructions & references

Back to overview ↑
On this page 4 sections
SKILL.md · MIT

Rate limiting with Upstash

Rate limits are one layer of abuse and cost control. Design policy before wiring middleware.

Workflow

  1. Detect Next.js/runtime/version, deployed proxy/CDN, auth/API-key model, installed Upstash versions, protected routes, operation cost, existing quotas, and whether middleware/proxy already touches the request.
  2. Define a policy table per route class: identifier, algorithm/window/burst, cost weight, user tier, response behavior, and store-outage behavior. Ask only when the threat/cost tradeoff cannot be inferred.
  3. Prefer authenticated user, API key, or tenant+user identifiers. Use IP only for anonymous traffic and only from a deployment-provided trusted source. Never trust arbitrary x-forwarded-for from the public internet; configure trusted proxy depth/platform headers. Do not collapse unknown clients to 127.0.0.1.
  4. Namespace by environment and route/policy. Do not apply blanket middleware and a per-route limiter to the same request unless deliberate layered limits use different keys.
  5. Configure explicit Upstash timeout and logging/metrics. Choose outage behavior by endpoint:
    • low-risk availability paths may fail open with degraded telemetry;
    • authentication, high-cost generation, or abuse-sensitive paths may use a local emergency limit, queue, credit reservation, or fail closed with a clear temporary response.
  6. Return 429 with a non-negative Retry-After and consistent rate-limit headers. Add headers to successful responses where useful. Do not emit misleading zero limits during fail-open degradation.
  7. For weighted work, consume tokens based on server-calculated batch/operation cost. Combine rate limits with body-size limits, concurrency controls, idempotency, budgets/credits, and provider quotas where relevant.
  8. Preserve async work such as analytics synchronization using the runtime’s waitUntil mechanism when the SDK exposes a pending promise.

Verification

Use deterministic tests with an isolated key prefix and controllable clock/window where possible. Test allowed/blocked/reset behavior, route isolation, authenticated and anonymous keys, spoofed forwarding headers, paid/free policies, concurrency, weighted requests, store timeout/outage behavior, and duplicate middleware avoidance. Run repository lint/type/test/build and inspect Upstash analytics only when enabled.

Output

Report the policy table, identifier trust model, files/env names changed, outage behavior, response headers, layered controls, automated test evidence, and remaining Upstash/deployment configuration.

View on GitHub ↗
Claude app, ChatGPT and ZIP download

local coding agent required

This skill requires project files, terminal commands, and network access. Uploading it to a chat app does not provide equivalent execution.

ChatGPT Skills

This workflow needs a local coding environment or capabilities that a chat-only Skills upload does not provide.

Package details
Package
rate-limit/SKILL.md
Author
@tushaarmehtaa
Added
20 Jun 2026
Tags
rate-limitupstashredissecurityapiabuse-prevention