Preventing API Wallet Drain: Implementing Upstash Redis Rate Limiting in Next.js
How to stop automated scrapers and bots from burning through your OpenAI and Anthropic token budgets.
Table of Contents7 sections
If your AI app lets users generate text, analyze PDFs, synthesize voice, or create images, every single HTTP request costs you real money.
Unlike traditional web applications where a database read costs fractions of a millicent, a single GPT-4o or Claude 3.5 Sonnet request can cost between $0.02 and $0.15.
If an automated bot finds your endpoint and fires 5,000 requests over the weekend, you will wake up on Monday morning to a $500 to $1,000 credit card charge and a blocked API key.
In this tutorial, you will learn how to implement an enterprise-grade, sliding-window rate limiter in Next.js using Upstash Redis—with zero database management, sub-millisecond latency, and privacy-preserving IP hashing.
Why In-Memory Limiters Fail on Serverless
When developers ask AI tools for a rate limiter, the model often suggests an in-memory Map:
// VULNERABLE SERVERLESS PATTERN (Do not use on Vercel/Netlify)
const requestCounts = new Map<string, number>();
export async function POST(req: Request) {
// This fails completely in serverless!
// Every request spins up a separate isolated container with an empty Map!
}On platforms like Vercel, serverless functions run in ephemeral micro-containers. Each incoming request may hit a completely new container instance. An in-memory Map has zero shared state, meaning an attacker can send 1,000 concurrent requests across 1,000 serverless instances and never hit the in-memory limit.
You need a fast, centralized, distributed store. Upstash Redis is the gold standard for serverless because it communicates over HTTP (no persistent TCP connection bottlenecks) and scales automatically.
Step 1: Setting Up Upstash Redis
First, install the Upstash SDKs:
bun add @upstash/redis @upstash/ratelimitAdd your Upstash REST credentials to your .env.local:
UPSTASH_REDIS_REST_URL="https://your-database.upstash.io"
UPSTASH_REDIS_REST_TOKEN="AYF..."
RATE_LIMIT_SECRET="a-random-32-character-secret-salt"Step 2: Privacy-Preserving IP Hashing
Under privacy regulations like GDPR and CCPA, a visitor's raw IP address is classified as Personal Identifiable Information (PII). Storing raw IP addresses in your Redis database creates compliance liabilities.
Instead, create a one-way HMAC hash of the IP address with a secret salt:
// server/rate-limit.ts
import crypto from "node:crypto";
import { headers } from "next/headers";
import { Redis } from "@upstash/redis";
import { Ratelimit } from "@upstash/ratelimit";
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL!,
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
});
// Create sliding window ratelimiter: 10 requests per 10 minutes
export const aiRateLimiter = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(10, "10 m"),
analytics: true,
prefix: "rl:ai",
});
/**
* Returns a privacy-safe identifier for the incoming request.
*/
export async function getClientIdentifier(userId?: string): Promise<string> {
// If user is authenticated, rate limit by their user ID
if (userId) {
return `user:${userId}`;
}
// Otherwise, hash the incoming IP address with a secret salt
const headerList = await headers();
const forwardedFor = headerList.get("x-forwarded-for");
const rawIp = forwardedFor ? forwardedFor.split(",")[0].trim() : "127.0.0.1";
const secret = process.env.RATE_LIMIT_SECRET;
if (!secret) {
throw new Error("RATE_LIMIT_SECRET must be configured");
}
const hashedIp = crypto
.createHmac("sha256", secret)
.update(rawIp)
.digest("hex")
.slice(0, 24);
return `ip:${hashedIp}`;
}Step 3: Protecting the Route Handler
Now, wire the rate limiter into your AI route handler:
// app/api/ai-chat/route.ts
import { NextResponse } from "next/server";
import { aiRateLimiter, getClientIdentifier } from "@/server/rate-limit";
import { auth } from "@/server/auth";
import { headers } from "next/headers";
export async function POST(req: Request) {
// 1. Check optional user session
const session = await auth.api.getSession({ headers: await headers() });
const identifier = await getClientIdentifier(session?.user?.id);
// 2. Evaluate rate limit
const { success, limit, remaining, reset } = await aiRateLimiter.limit(identifier);
if (!success) {
const retryAfterSeconds = Math.ceil((reset - Date.now()) / 1000);
return NextResponse.json(
{
error: "Too many requests. You have reached your temporary AI generation limit.",
retryAfter: retryAfterSeconds,
},
{
status: 429,
headers: {
"Retry-After": retryAfterSeconds.toString(),
"X-RateLimit-Limit": limit.toString(),
"X-RateLimit-Remaining": remaining.toString(),
"X-RateLimit-Reset": reset.toString(),
},
}
);
}
// 3. Process AI generation safely...
return NextResponse.json({ result: "Generation complete" });
}Step 4: Tiered Limits: Guests vs. Paid Users
In a commercial SaaS, you want different limits for anonymous visitors, free registered users, and paying Pro subscribers.
You can instantiate multiple rate limiters:
// Strict for guests: 3 requests per hour
const guestLimiter = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(3, "1 h"),
prefix: "rl:guest",
});
// Moderate for free accounts: 20 requests per hour
const freeLimiter = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(20, "1 h"),
prefix: "rl:free",
});
// Generous for pro subscribers: 200 requests per hour
const proLimiter = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(200, "1 h"),
prefix: "rl:pro",
});Summary
Rate limiting is not an optional performance optimization—it is your application's financial firewall. By combining Upstash Redis with HMAC IP hashing:
- Your token budget is protected from malicious scraping.
- Honest users get fair access without server crashes.
- You stay fully compliant with privacy laws by never storing raw customer IP addresses.
Don't let a hidden bug derail your launch.
vibesupport scans your AI-built codebase or live website for exposed secrets, missing database RLS, and broken access controls—then pairs you with senior engineers to fix them directly in GitHub.