To add rate limiting to an AI-built app, list the endpoints that spend money or protect accounts, then enforce a limit on each one on the server, in a shared store, keyed by both IP address and account. Give large language model (LLM) endpoints a per-user usage budget on top of a request limit, return HTTP 429 with a Retry-After header, and test every limit before launch.
Cursor, Lovable, Bolt and Replit build the happy path: one user, one click, one request. Nobody asked what happens when a script sends that request ten thousand times, so the generated code has no answer.
Which endpoints in an AI-built app need rate limiting
Every endpoint that sends something, spends something or checks a secret needs its own limit.
| Endpoint | What abuse looks like | Count by |
|---|---|---|
| Login and token refresh | Password guessing, credential stuffing | Account and IP |
| Signup | Fake accounts, free-tier farming | IP and device signals |
| Password reset, magic links, one-time passwords (OTPs) | Email or SMS floods | Target account and IP |
| Code verification | Guessing one-time codes | Account or session |
| LLM chat and generation | Runaway model bills | Account, plus a usage budget |
| Contact forms | Spam, damaged email reputation | IP |
| Search and export | Scraping, slow queries | Account |
OWASP's API4:2023 Unrestricted Resource Consumption describes the costly version: a script calls a password reset flow that sends SMS codes through a paid provider tens of thousands of times. Its fixes include per-user limits on single operations, such as reset requests, and spending limits or billing alerts with every provider.
Choose what to count: IP address, account or both
An IP-only limit is easy to get around. OWASP's Authentication Cheat Sheet says the failed-login counter should belong to the account, not the source IP, so attempts spread over many addresses still add up. Credential stuffing tools route requests through proxy networks for exactly this reason.
An account-only limit does nothing before sign-in, and lockouts can be turned against users: if ten wrong passwords lock an account, anyone who knows an email address can lock its owner out. The same cheat sheet suggests keeping password reset available for locked accounts.
Use both: per IP for one machine trying many accounts, per account for many machines aiming at one. For signed-in endpoints, key on the user ID from the server-side session.
Read the IP from a header your host controls. Vercel overwrites X-Forwarded-For to prevent spoofing. A self-hosted server behind a misconfigured proxy may pass through whatever the client sent.
How to add rate limiting to an AI-built app
Generated code often counts requests in an in-memory Map. On serverless platforms each instance has its own memory and instances come and go, so the count resets unpredictably. Keep counts in a shared store such as Redis. An example Next.js route handler for an LLM endpoint, using @upstash/ratelimit:
// app/api/chat/route.ts (example)
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
const redis = Redis.fromEnv();
const perIp = new Ratelimit({ redis, prefix: "chat:ip", limiter: Ratelimit.slidingWindow(30, "1 m") });
const perUser = new Ratelimit({ redis, prefix: "chat:user", limiter: Ratelimit.slidingWindow(50, "1 d") });
function tooMany(reset: number) {
const seconds = Math.max(1, Math.ceil((reset - Date.now()) / 1000));
return new Response("Too many requests", { status: 429, headers: { "Retry-After": String(seconds) } });
}
export async function POST(request: Request) {
const ip = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
const byIp = await perIp.limit(ip);
if (!byIp.success) return tooMany(byIp.reset);
const user = await requireUser(); // from the server-side session
const byUser = await perUser.limit(user.id);
if (!byUser.success) return tooMany(byUser.reset);
// check input length, then call the model with an output token cap
}The numbers are placeholders. Set them from what your heaviest legitimate users do in a day, with headroom.
A fixed window lets bursts through at each boundary, because counts reset on the clock; a sliding window smooths that out. Some limiters can also allow requests when the store doesn't answer in time, which removes the limit during an outage. Decide that per endpoint and alert on store errors.
Firewall rules at your host or content delivery network (CDN) stop floods before they reach your code, but they can't see accounts, so per-user limits stay in the application.
Rate limits for login, signup and password reset
Read your auth provider's limits first. Supabase's Auth rate limits page lists per-IP limits on sign-up, sign-in, verification and token endpoints, a 60-second wait between OTP, confirmation and password reset requests for the same user, and a low hourly cap on emails from the built-in email provider. Most are adjustable under Authentication > Rate Limits.
One trap catches server-rendered apps. When your Next.js server calls Supabase Auth, the per-IP limits see your server's IP, so all users share one bucket. Supabase can read the end-user IP from an Sb-Forwarded-For header instead; new projects must enable this, and it requires a secret API key.
Supabase Auth also supports CAPTCHA, with hCaptcha or Cloudflare Turnstile, on sign-up, sign-in and password reset. OWASP treats CAPTCHA as defense in depth, since many implementations can be solved by automated tools or outsourced solvers. Showing it only after a few failed attempts spares most users.
Limit LLM endpoints by usage, not only by requests
A request limit treats a one-line question and a pasted 50-page document the same. Model providers bill by tokens, so limit size and usage too:
- Cap input length on the server and set an output token limit on every model call.
- Give each account a daily token budget, counted from the usage the provider reports per response.
- Block anonymous access to model endpoints, or give it a much smaller budget.
- Cap tool calls and loop iterations per task in agent features.
- Set a spending limit or billing alert with the provider as the last line of defense.
Some limiter libraries let one request consume several units, so you can charge each request the tokens it used. Our guide to testing an LLM feature before launch includes abuse and runaway usage tests for these limits.
Return 429 responses that clients can handle
A blocked request should get HTTP 429 Too Many Requests, with a Retry-After header in seconds. Then check the client: generated front-end code often retries failures immediately in a loop, turning one limit into a self-inflicted flood. Read Retry-After, back off, and show a clear message.
Log each block with the endpoint and key type. A spike on login is an incident signal. A steady trickle on an ordinary page means the limit may be too low.
Common rate limiting mistakes in AI-generated code
- Counting in memory on serverless, so the limit never holds.
- Throttling in the React component while the API stays open.
- Limiting the page but not the API route, server action or Edge Function behind it.
- Keying on a client-supplied header the host doesn't overwrite.
- One global limit, too loose for login and too strict for reads.
- Calling the paid provider before the limit check.
- Account lockout with no recovery path.
Firebase apps often query the database straight from the browser, so an API limit never sees that traffic. There, App Check and Security Rules are the controls, covered in our list of Firebase Security Rules mistakes.
How to test rate limits before launch
Run these against staging with a script and two test accounts:
- Send 100 wrong passwords for one account from one IP. Blocks start at your threshold.
- Repeat from several IPs, and once with a forged
X-Forwarded-Forheader. The per-account limit still fires. - Request ten password resets for one address within a minute. Only as many emails as your limit allows go out.
- Call the LLM endpoint directly with a very long input. It's rejected before the model call.
- Use up one account's daily budget. The second account still works.
- Make the limit store unreachable. The app behaves the way you decided, and an alert fires.
Rate limits belong on the same launch list as backups and spending alerts in our guide to taking an AI-built prototype to production, and item 16 of our security checklist for AI-built apps covers them. Our security audit for AI-built apps reviews authentication, exposed endpoints and LLM features, with a written report and a prioritized fix list.
Frequently asked questions
What rate limit should I set for a login endpoint?
There's no universal number. Allow a handful of failed attempts per account in a short window, then add a growing delay or a CAPTCHA. Keep the per-IP limit looser, since offices and mobile networks put many users behind one address.
Is a CAPTCHA enough to stop bots?
No. Many CAPTCHAs can be solved by automated tools or paid solving services. Use one as a layer next to rate limits, account-based counters and monitoring.
Do I need my own rate limiting if my auth provider has it?
Yes. Supabase's Auth limits cover Auth endpoints only. Your API routes, server actions, Edge Functions and LLM calls need their own.
Should a rate-limited request get a 429 or a 403?
Use 429 for "slow down", with Retry-After, so clients can recover. Keep 403 for requests you refuse regardless of rate, such as a blocked IP or a missing permission.