# How to rate limit API routes in an AI app, and cap your model bill

Canonical: https://caelo.sh/guides/rate-limit-ai-app-api-routes
Published: 2026-11-27 · Updated: 2026-11-27 · Arthi Arumugam, Caelo by Irth Labs

**Short answer:** Put a per-user or per-IP limit in front of every route that calls a paid model, for example 10 requests per 10 seconds with @upstash/ratelimit, or a WAF rate limit rule on Vercel or Cloudflare. Then set a provider spend limit with enforcement on, because OpenAI says a limit you only monitor does not stop requests.

## Why AI routes need a limit first

A route such as `/api/chat` that calls a model on every request spends your money on every request. If it has no sign-in check and no limit, anyone who finds it can call it in a loop. OpenAI's community forum has threads from developers whose stolen keys ran far past the limits they had set.

## The vulnerable pattern and the fix

Vulnerable: anyone, any number of times

```ts
// app/api/chat/route.ts
export async function POST(req: Request) {
  const { message } = await req.json();
  return Response.json(await callModel(message));
}
```

Fixed: signed-in users only, 10 requests per 10 seconds each

```ts
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(10, "10 s"),
});

export async function POST(req: Request) {
  const userId = await getSignedInUserId(req); // your own auth check
  if (!userId) return new Response("Sign in first", { status: 401 });

  const { success } = await ratelimit.limit(userId);
  if (!success) return new Response("Too many requests", { status: 429 });

  const { message } = await req.json();
  return Response.json(await callModel(String(message).slice(0, 4000)));
}
```

The limiter setup is the example from the @upstash/ratelimit README. The counter lives in Redis, so it holds across every serverless instance. An in-memory counter does not: each instance keeps its own count. Cap the input length and the model's output tokens too, so one request cannot cost much.

## Platform limits: Vercel and Cloudflare

A WAF rule sees requests, not users, so it is good for limiting by IP on public routes. Use a limit in code when you need one per signed-in user.

| Option | What it does | Plans |
| --- | --- | --- |
| Vercel WAF rate limiting | A custom firewall rule with the Rate Limit action, matched by path, IP and other request fields. Windows from 10 seconds to 10 minutes; the default response is 429. | All plans. Hobby gets 1 rate limit rule per project, Pro 40, Enterprise 250. |
| Cloudflare WAF rate limiting rules | Define a rate limit for requests matching an expression, and the action when it is reached. | All plans, with more rules and options on higher plans. |
| @upstash/ratelimit in your code | Limit by user ID, API key or IP, with sliding window, fixed window or token bucket. | Your Upstash Redis plan. |

## Set it up, step by step

1. List every route that calls a paid API: model providers, email, SMS, image generation.
2. Require a signed-in user on each one, unless it is truly public.
3. Add a per-user limit in code. For public routes, limit by IP as your host reports it.
4. Add a WAF rate limit rule on the same paths as a second layer.
5. At OpenAI, set a project spend limit and turn on "Enforce a hard limit". OpenAI says enforcement is not instantaneous, so recorded spend can slightly exceed it, and spend alerts notify you without stopping requests.
6. Keep the model key on the server only, so nobody can skip your routes and call the provider directly.

## Can a scanner find this?

Caelo does not check rate limits. It does flag what makes a missing limit worse: an OpenAI, Anthropic or other server-only key written in your files or exposed behind a `VITE_` or `NEXT_PUBLIC_` name, which lets people skip your routes entirely.

- [Install Caelo: npx caelo . or the MCP server](/)
- [How Caelo compares with gitleaks, TruffleHog, Semgrep and others](/compare)

## Check your own app

1. Run the free local check: `npx caelo .` Caelo is a free, open source (MIT) command line tool and MCP server from Irth Labs that checks the files of an AI-built app for exposed API keys, Supabase and Firebase misconfigurations and `.env` files with real values. It runs on your machine, uploads nothing and uses no AI model. Each finding comes with a plain-English fix.
2. Follow the fix in the report and rerun Caelo. For an untracked, unignored file containing secrets, preview the US$19 quick fix. https://caelo.sh/fix
3. For an engineer's assessment, book the US$490 App Health Check. Irth Labs delivers a report and fixed repair quote, with credit toward the repair. https://www.irthlabs.com/start?service=app-health-check

## Questions

### Is a spend limit at OpenAI enough?

No. It caps the damage after money is spent, and OpenAI says enforcement is not instantaneous. A rate limit stops abuse before it costs you, and the spend limit is the backstop.

### Can I rate limit with a variable in memory?

Only on a single long-running server. On serverless hosts each instance has its own memory, so the count resets and splits across instances. Use Redis or your platform's firewall.

### What limit should I pick?

Start from what a real user needs. For a chat feature, a few requests per minute per user plus a daily cap is common. Watch the 429 count and adjust.

## Sources

- [Upstash ratelimit-js README.](https://github.com/upstash/ratelimit-js)
- [Vercel docs: WAF rate limiting.](https://vercel.com/docs/vercel-firewall/vercel-waf/rate-limiting)
- [Cloudflare docs: Rate limiting rules.](https://developers.cloudflare.com/waf/rate-limiting-rules/)
- [OpenAI Help Center: Managing projects in the API platform (spend limits).](https://help.openai.com/en/articles/9186755-managing-projects-in-the-api-platform)
- [OpenAI community: The API key has been stolen. Why didn't the maximum limit I set take effect?](https://community.openai.com/t/the-api-key-has-been-stolen-why-didnt-the-maximum-limit-i-set-take-effect/721376)

## Related guides

- [Security checklist for apps built with Lovable, Bolt, Cursor, Replit or v0](https://caelo.sh/guides/vibe-coded-app-security-checklist)
- [Can users get my AI-built app's paid features for free? Checking Stripe payments](https://caelo.sh/guides/stripe-webhook-security-ai-built-app)
- [Is my Replit app secure? Checks to run before you publish](https://caelo.sh/guides/is-my-replit-app-secure)
- [OpenAI API key exposed in client-side code: how to fix it](https://caelo.sh/guides/openai-api-key-exposed-frontend)
- [Prompt injection in a vibe-coded app: what it is and how to limit the damage](https://caelo.sh/guides/prompt-injection-ai-app-features)
