caelo

Caelo › Guides › Rate limit AI API routes

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

By Arthi Arumugam, Irth Labs · Published · Updated

Short answerPut 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

// 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

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.

OptionWhat it doesPlans
Vercel WAF rate limitingA 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 rulesDefine 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 codeLimit 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.

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. Act on a finding

Follow the fix in your report and run Caelo again. If Git could commit an untracked file containing secrets, preview a US$19 quick fix for that file.

For findings that need an engineer, Irth Labs offers a US$490 App Health Check. You receive a written report within 48 hours and a fixed repair quote. The fee counts toward the repair if you proceed.

Book the App Health Check See repair services

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