How Token-Based Rate Limiting Works Per User ID
Request-count limits (RPM) fail for LLM APIs because a single prompt with a large context and max completion budget can consume orders of magnitude more compute than a short chat message. Enforcing actual token budgets (TPM / TPD) requires a two-phase reservation and reconciliation pattern backed by atomic Redis operations:
- Preflight reservation before dispatch: Estimate
input_tokens + reserved_output_tokensupfront and atomically deduct that amount from the user’s token bucket before calling the upstream provider. If the bucket lacks enough tokens, reject immediately withHTTP 429and aRetry-Afterheader so concurrent requests cannot race past the quota. - Post-response / post-stream reconciliation: Read the provider’s authoritative
usage.total_tokens(viastream_options: { include_usage: true }on streaming calls orresponse.usageon non-streaming calls) and refund unused reserved tokens (reserved - actual)—or debit any overrun—back into the user’s bucket. - Atomic Redis Lua execution: Running the refill, balance check, deduction, and refund inside Redis Lua scripts using Redis’s internal
TIMEclock prevents race conditions and clock drift across stateless Node.js/TypeScript server instances.
Steps to Implement Per-User Token Rate Limiting
- Key buckets by
userId(and optionally tier/model): Storetokensandlast_refill_msunder a Redis hash such asratelimit:tpm:{userId}with a TTL proportional to the refill window. - Calculate worst-case preflight token cost: Estimate prompt tokens locally (or via a token count endpoint) plus
max_completion_tokens(capped to a reasonable bound) to determinereservedTokens. - Execute an atomic reserve Lua script: Refill the user’s bucket based on elapsed server time up to
capacity, checkavailableTokens >= reservedTokens, and deductreservedTokensin a single atomic operation. - Capture exact token usage from the LLM response: Enable
stream_options: { include_usage: true }on streaming requests so the final usage chunk reports exactprompt_tokens + completion_tokens(including reasoning tokens). - Reconcile the difference in a
finallyblock: Computedelta = reservedTokens - actualTotalTokensand atomically adjust the bucket (clamped atcapacity), refunding the fullreservedTokensif the upstream call failed before generating tokens.
TypeScript Example: Atomic Redis Token Bucket with Preflight Reserve & Stream Reconciliation
import Redis from "ioredis";
import OpenAI from "openai";
const redis = new Redis(process.env.REDIS_URL!);
const openai = new OpenAI();
// Atomic reserve script: refills bucket using Redis TIME and deducts reserved tokens if available
const RESERVE_TOKENS_LUA = `
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_per_ms = tonumber(ARGV[2])
local requested = tonumber(ARGV[3])
local ttl_ms = tonumber(ARGV[4])
local time = redis.call("TIME")
local now_ms = (tonumber(time[1]) * 1000) + math.floor(tonumber(time[2]) / 1000)
local data = redis.call("HMGET", key, "tokens", "ts")
local tokens = tonumber(data[1])
local last_ts = tonumber(data[2])
if tokens == nil or last_ts == nil then
tokens = capacity
last_ts = now_ms
else
local elapsed = math.max(0, now_ms - last_ts)
tokens = math.min(capacity, tokens + (elapsed * refill_per_ms))
last_ts = now_ms
end
if tokens < requested then
redis.call("HMSET", key, "tokens", tokens, "ts", last_ts)
redis.call("PEXPIRE", key, ttl_ms)
local deficit = requested - tokens
local retry_after_sec = math.ceil((deficit / refill_per_ms) / 1000)
return { 0, math.floor(tokens), retry_after_sec }
end
tokens = tokens - requested
redis.call("HMSET", key, "tokens", tokens, "ts", last_ts)
redis.call("PEXPIRE", key, ttl_ms)
return { 1, math.floor(tokens), 0 }
`;
// Atomic reconcile script: refunds unused reserved tokens (or deducts overrun) clamped to capacity
const RECONCILE_TOKENS_LUA = `
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local delta = tonumber(ARGV[2])
local ttl_ms = tonumber(ARGV[3])
local current = tonumber(redis.call("HGET", key, "tokens"))
if current == nil then
return 0
end
local updated = math.min(capacity, math.max(0, current + delta))
redis.call("HSET", key, "tokens", updated)
redis.call("PEXPIRE", key, ttl_ms)
return math.floor(updated)
`;
export interface UserTokenQuota {
tokensPerMinute: number;
burstCapacity: number;
}
export async function streamChatWithTokenRateLimit(
userId: string,
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
quota: UserTokenQuota,
maxCompletionTokens = 1024
) {
const key = `ratelimit:llm:tokens:\${userId}`;
const refillPerMs = quota.tokensPerMinute / 60_000;
const ttlMs = Math.ceil((quota.burstCapacity / refillPerMs) * 2);
// Rough preflight input estimate (~4 chars/token + framing overhead); swap in tiktoken for exactness
const estimatedInputTokens = messages.reduce((sum, msg) => {
const raw = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content ?? "");
return sum + Math.ceil(raw.length / 4) + 12;
}, 0);
const reservedTokens = estimatedInputTokens + maxCompletionTokens;
const [allowed, remaining, retryAfterSec] = (await redis.eval(
RESERVE_TOKENS_LUA,
1,
key,
quota.burstCapacity,
refillPerMs,
reservedTokens,
ttlMs
)) as [number, number, number];
if (allowed === 0) {
const err = new Error(`Token rate limit exceeded for user \${userId}. Retry in \${retryAfterSec}s.`);
(err as Error & { status?: number; retryAfter?: number }).status = 429;
(err as Error & { status?: number; retryAfter?: number }).retryAfter = retryAfterSec;
throw err;
}
let actualTotalTokens: number | null = null;
try {
const stream = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages,
max_completion_tokens: maxCompletionTokens,
stream: true,
stream_options: { include_usage: true },
});
for await (const chunk of stream) {
if (chunk.usage?.total_tokens != null) {
actualTotalTokens = chunk.usage.total_tokens;
}
const delta = chunk.choices[0]?.delta?.content;
if (delta) {
process.stdout.write(delta);
}
}
return { remainingBeforeReconcile: remaining, actualTotalTokens };
} finally {
// Refund full reservation if request errored before usage arrived, or refund unused remainder
const used = actualTotalTokens ?? 0;
const refundDelta = reservedTokens - used;
if (refundDelta !== 0) {
await redis.eval(RECONCILE_TOKENS_LUA, 1, key, quota.burstCapacity, refundDelta, ttlMs);
}
}
}
Helpful Tips for Production Token Rate Limiters
- Pair token limits (TPM) with request/concurrency limits: A user sending dozens of tiny requests or holding 20 open SSE streams can exhaust worker sockets even under a low token budget—combine TPM with an RPM and in-flight concurrency cap.
- Weight expensive models or output tokens by cost: If your router serves both cheap mini models and expensive frontier/reasoning models, normalize consumption into “credits” (for example,
1 input token = 1 credit,1 output token = 4 credits) so one bucket governs spend fairly across models. - Handle client disconnects cleanly during streaming: When a user aborts mid-stream, some providers omit the final usage chunk; fall back to
estimatedInputTokens + streamedOutputTokensCountedLocallyin thefinallyblock so aborted streams still debit the tokens actually generated.
You must log in or register to comment.
