Giới hạn tốc độ theo token cho API AI trên Next.js
Giới hạn theo số yêu cầu không kiểm soát được chi phí API AI, vì một tài liệu 10.000 token tốn gấp hàng trăm lần câu "hi". Bài viết trình bày cách giới hạn theo token trên Next.js bằng Upstash Redis, kèm mã nguồn và cách xử lý lỗi 429.

Vì sao tuyến API AI cần cách giới hạn khác
Giới hạn tốc độ (rate limit) theo IP hay theo người dùng đã quen thuộc. Với tuyến API gọi mô hình ngôn ngữ lớn (LLM), vấn đề khó hơn: lượng token tiêu thụ dao động rất mạnh.
Một người gửi "hi" tốn khoảng 0,0001 USD. Một người gửi tài liệu 10.000 token tốn khoảng 0,03 USD. Nếu chỉ giới hạn theo số yêu cầu, bạn chưa thực sự giới hạn chi phí.
Cần giới hạn theo token, không phải theo yêu cầu.
Cài đặt
1. Cài Upstash Redis
Upstash có gói miễn phí và bộ công cụ phát triển (SDK) cho Next.js, phù hợp với môi trường máy chủ không trạng thái (serverless).
npm install @upstash/redis @upstash/ratelimit
Thêm vào tệp .env.local:
UPSTASH_REDIS_REST_URL=your_url
UPSTASH_REDIS_REST_TOKEN=your_token
2. Tạo bộ giới hạn tốc độ
// src/lib/rate-limit.ts
import { Ratelimit } from "@upstash/ratelimit"
import { Redis } from "@upstash/redis"
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL!,
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
})
// Giới hạn theo yêu cầu: 20 yêu cầu mỗi phút mỗi người dùng
export const requestLimiter = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(20, "1 m"),
analytics: true,
prefix: "ratelimit:requests",
})
// Giới hạn theo token: 100k token mỗi ngày mỗi người dùng
export const tokenLimiter = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(100_000, "24 h"),
analytics: true,
prefix: "ratelimit:tokens",
})
3. Gắn vào tuyến API AI
// src/app/api/chat/route.ts
import { NextRequest, NextResponse } from "next/server"
import { getServerSession } from "next-auth"
import Anthropic from "@anthropic-ai/sdk"
import { requestLimiter, tokenLimiter } from "@/lib/rate-limit"
import { authOptions } from "@/lib/auth"
const client = new Anthropic()
export async function POST(req: NextRequest) {
const session = await getServerSession(authOptions)
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
const userId = session.user.id
// Kiểm tra giới hạn theo yêu cầu
const { success: requestOk, remaining: requestsLeft } =
await requestLimiter.limit(userId)
if (!requestOk) {
return NextResponse.json(
{ error: "Too many requests. Please wait a minute." },
{
status: 429,
headers: { "Retry-After": "60" },
}
)
}
const { messages } = await req.json()
// Ước lượng token đầu vào trước khi gọi API
const estimatedInputTokens = messages
.reduce((sum: number, m: any) => sum + m.content.length / 4, 0)
// Kiểm tra hạn mức token (ước lượng thô, kiểm tra thực tế diễn ra sau)
const { success: tokenOk } = await tokenLimiter.limit(
userId,
{ rate: estimatedInputTokens }
)
if (!tokenOk) {
return NextResponse.json(
{ error: "Daily token limit reached. Resets at midnight UTC." },
{ status: 429 }
)
}
// Gọi API
const response = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages,
})
// Trừ số token thực tế đã dùng
const actualTokens = response.usage.input_tokens + response.usage.output_tokens
// Bù chênh lệch do ước lượng
const adjustment = actualTokens - estimatedInputTokens
if (adjustment > 0) {
await tokenLimiter.limit(userId, { rate: adjustment })
}
return NextResponse.json({
content: response.content[0].type === "text" ? response.content[0].text : "",
usage: response.usage,
limits: {
requestsRemaining: requestsLeft,
},
})
}
4. Hiển thị giới hạn cho người dùng
Đừng giấu giới hạn tốc độ. Người dùng biết mình sắp chạm hạn mức sẽ ít bực bội hơn người đột ngột bị chặn mà không rõ lý do.
// Trong phần giao diện
const { data } = await fetch("/api/chat", {
method: "POST",
body: JSON.stringify({ messages }),
}).then(r => r.json())
if (data.limits?.requestsRemaining < 5) {
showToast(`${data.limits.requestsRemaining} requests remaining this minute`)
}
Giới hạn theo gói dịch vụ
Nếu có gói miễn phí và gói trả phí, hãy để hạn mức phản ánh điều đó:
// src/lib/rate-limit.ts
import { getServerSession } from "next-auth"
export async function getRateLimiters(userId: string, plan: "free" | "pro") {
const limits = {
free: { requests: 10, tokens: 50_000 },
pro: { requests: 100, tokens: 500_000 },
}
const { requests, tokens } = limits[plan]
return {
requestLimiter: new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(requests, "1 m"),
prefix: `ratelimit:${plan}:requests`,
}),
tokenLimiter: new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(tokens, "24 h"),
prefix: `ratelimit:${plan}:tokens`,
}),
}
}
Xử lý lỗi 429 gọn gàng
Giao diện cần xử lý giới hạn tốc độ mà không làm hỏng trải nghiệm:
const sendMessage = async (content: string) => {
try {
const res = await fetch("/api/chat", {
method: "POST",
body: JSON.stringify({ messages: [...history, { role: "user", content }] }),
})
if (res.status === 429) {
const retryAfter = res.headers.get("Retry-After")
setError(
retryAfter
? "Rate limit hit. Try again in " + retryAfter + " seconds."
: "Daily limit reached. Resets at midnight UTC."
)
return
}
const data = await res.json()
// xử lý kết quả thành công
} catch (e) {
setError("Something went wrong. Please try again.")
}
}
Theo dõi chi phí
Giới hạn tốc độ bảo vệ bạn khỏi các đợt tăng đột biến. Theo dõi chi phí cho biết tiền đang chảy đi đâu.
Ghi lại lượng token của từng người dùng vào cơ sở dữ liệu:
// Sau mỗi lần gọi API
await db.aiUsage.create({
data: {
userId,
inputTokens: response.usage.input_tokens,
outputTokens: response.usage.output_tokens,
model: "claude-sonnet-4-6",
cost: calculateCost(response.usage),
createdAt: new Date(),
},
})
Sau đó dựng một truy vấn đơn giản cho bảng điều khiển để xem ai dùng nhiều nhất. Nếu một người tiêu 40% hạn mức token, bạn biết chính xác cần liên hệ với ai.
Góc nhìn
Cách làm này áp dụng được cho bất kỳ nhóm nào ở Việt Nam đang dựng sản phẩm AI trên Next.js và triển khai lên nền tảng serverless. Chi phí gọi mô hình tính theo token, nên hạn mức cũng phải tính theo token.
Một điểm cần lưu ý: đoạn mã ước lượng token bằng cách chia độ dài ký tự cho 4 chỉ là con số thô. Với tiếng Việt, số token thực tế có thể cao hơn ước lượng đáng kể do cách tách từ của bộ mã hóa. Nên kiểm tra lại tỷ lệ này bằng dữ liệu thật của sản phẩm trước khi đặt hạn mức.
Việc ghi log token theo người dùng còn giúp phát hiện sớm lỗi vòng lặp hoặc hành vi lạm dụng, hai nguyên nhân thường làm cháy ngân sách API trong vài giờ.
Nguồn: dev.to (bài gốc ngày 07 tháng 4, 2026) · Quy trình biên tập


