
Rate-Limit Your AI Chat API With Upstash Before Abuse Drains Your LLM Bill
Also available in Hindi: यह लेख हिंदी में पढ़ें
Every message to your AI chatbot costs money, so an open /api/chat route is an open wallet. One script can send thousands of requests overnight. Upstash Ratelimit is a small TypeScript library that counts requests in Upstash Redis over HTTP. It works in serverless functions such as Vercel and Cloudflare Workers.
How the check works
Check the limit before you call the model. If success is false, return a 429 and never pay for the tokens.
Setup
- Create an Upstash Redis database in the Upstash console.
- Run
npm install @upstash/ratelimit @upstash/redis. - Add
UPSTASH_REDIS_REST_URLandUPSTASH_REDIS_REST_TOKENto your environment variables (on Vercel: Settings, then Environment Variables). Keep them server-side.
The route
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, "60 s"),
prefix: "ratelimit:chat",
});
export async function POST(req: Request) {
const id = req.headers.get("x-forwarded-for") ?? "anonymous";
const { success, reset } = await ratelimit.limit(id);
if (!success) {
const wait = Math.ceil((reset - Date.now()) / 1000);
return new Response("Too many requests", {
status: 429,
headers: { "Retry-After": String(wait) },
});
}
// call your LLM here
}
limit() also returns limit and remaining, and reset is a Unix time in milliseconds. If users log in, use their user ID instead of the IP address, because many people can share one IP.
Pick an algorithm
- fixedWindow is the cheapest, but bursts can slip through at window edges.
- slidingWindow smooths those edges for a little more compute.
- tokenBucket allows a short burst, then a steady rate. It is not available for multi-region setups.
Tune it for AI costs
- Free vs paid: create two limiters with different prefixes, for example 10 and 60 requests per window.
- Count tokens, not calls:
limit(id, { rate: n })subtracts n instead of 1, so heavy prompts use more of the limit. - Know the timeout: if Redis does not answer within 5 seconds (the default), the request is allowed through. Set
timeoutto change this. - Serverless: with analytics on, pass the returned
pendingpromise towaitUntilso background work can finish.
For the bigger picture, read our vibe coding security checklist, how much an AI API costs and how to deploy a vibe-coded app, or see the Upstash tool page.
Sources
- Ratelimit getting started, Upstash Docs
- Ratelimit algorithms, Upstash Docs
- Ratelimit methods, Upstash Docs
- Ratelimit features, Upstash Docs
- upstash/ratelimit-js README and source, GitHub
FAQ
Does Upstash Ratelimit work on Vercel?
Yes. It talks to Redis over HTTP, so it works in serverless and edge functions.
Should I limit by IP or user ID?
User ID or API key when you have one. IPs can be shared by many people.
What happens if Redis is down?
After the timeout, 5 seconds by default, the request is allowed through.
Can I limit by tokens?
Yes. Pass a rate value to limit() to subtract more than 1 per request.