Rate Limiting AI, Auth & Email Endpoints
Every public AI wrapper, waitlist endpoint, or magic-link login route without rate limiting is a ticking financial bomb. One automated script can send 50,000 requests overnight.
AI builders almost never add rate limiting because it requires tracking request counts across invocations (Upstash Redis, Cloudflare Rate Limiting, or D1/Postgres token buckets).
- Unthrottled LLM routes can rack up hundreds or thousands of dollars in hours
- Email/OTP bombing abuses your Resend/Postmark quota and destroys domain reputation
- Credential-stuffing bots brute-force login or invite codes freely
Vulnerable Pattern vs. Production Fix
// app/api/summarize/route.ts — Anyone can call 10,000x per minute!
export async function POST(req: Request) {
const { text } = await req.json();
const output = await callOpenAI(text); // No IP/user limit, no length cap!
return Response.json({ output });
}// lib/rateLimit.ts — Lightweight Edge-compatible fixed-window guard
// For multi-region production, back this with Upstash Redis or Cloudflare Rate Limiting
const hits = new Map<string, { count: number; resetAt: number }>();
export function checkRateLimit(key: string, limit: number, windowMs: number) {
const now = Date.now();
const entry = hits.get(key);
if (!entry || now > entry.resetAt) {
hits.set(key, { count: 1, resetAt: now + windowMs });
return { ok: true, remaining: limit - 1 };
}
if (entry.count >= limit) {
return { ok: false, remaining: 0, retryAfterSec: Math.ceil((entry.resetAt - now) / 1000) };
}
entry.count += 1;
return { ok: true, remaining: limit - entry.count };
}Copy-Paste AI Fix Prompt (Cursor · Lovable · Bolt · Claude Code)
Add rate limiting and abuse caps to all expensive endpoints in this project: 1. Identify all AI/LLM, email-sending, PDF/image generation, and auth/signup routes. 2. Add per-user (or IP-based for public routes) rate limiting returning HTTP 429 with Retry-After headers. 3. Enforce strict input character limits and max_tokens output caps on every LLM call. 4. For production serverless deployments, wire Upstash Redis or Cloudflare Rate Limiting bindings so limits persist across isolates.
How to Verify Your Fix Worked
- 1Run a quick loop of 25 requests against your endpoint in staging and confirm HTTP 429 triggers cleanly.
- 2Send a 100KB payload to your AI route and confirm it rejects with HTTP 400 before calling the LLM.
- 3Set a hard monthly billing cap inside OpenAI, Anthropic, and Vercel/Cloudflare dashboards.
Frequently Asked Questions
Why isn't an in-memory Map enough for large serverless production apps?
Serverless functions spin up multiple isolated instances, so an in-memory Map resets per cold start. Use Upstash Redis, Cloudflare Rate Limiting, or a database counter for durable global limits.
How should I read the client IP safely behind Cloudflare or Vercel?
Use platform-set headers (`cf-connecting-ip` on Cloudflare or the first trusted value in `x-forwarded-for` on Vercel) — never trust arbitrary client-spoofable headers.
Should I also add Turnstile or CAPTCHA on free public AI tools?
Yes — Cloudflare Turnstile is free, invisible to most real users, and stops headless scripts from burning your free-tier AI credits.