How do you implement server-side rate limiting per user ID based on actual LLM token consumption rather than request count? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

How do you implement server-side rate limiting per user ID based on actual LLM token consumption rather than request count?

message-square
0
1
How do you implement server-side rate limiting per user ID based on actual LLM token consumption rather than request count?
How do you implement server-side rate limiting per user ID based on actual LLM token consumption rather than request count? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

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_tokens upfront and atomically deduct that amount from the user’s token bucket before calling the upstream provider. If the bucket lacks enough tokens, reject immediately with HTTP 429 and a Retry-After header so concurrent requests cannot race past the quota.
  • Post-response / post-stream reconciliation: Read the provider’s authoritative usage.total_tokens (via stream_options: { include_usage: true } on streaming calls or response.usage on 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 TIME clock prevents race conditions and clock drift across stateless Node.js/TypeScript server instances.

Steps to Implement Per-User Token Rate Limiting

  1. Key buckets by userId (and optionally tier/model): Store tokens and last_refill_ms under a Redis hash such as ratelimit:tpm:{userId} with a TTL proportional to the refill window.
  2. 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 determine reservedTokens.
  3. Execute an atomic reserve Lua script: Refill the user’s bucket based on elapsed server time up to capacity, check availableTokens >= reservedTokens, and deduct reservedTokens in a single atomic operation.
  4. Capture exact token usage from the LLM response: Enable stream_options: { include_usage: true } on streaming requests so the final usage chunk reports exact prompt_tokens + completion_tokens (including reasoning tokens).
  5. Reconcile the difference in a finally block: Compute delta = reservedTokens - actualTotalTokens and atomically adjust the bucket (clamped at capacity), refunding the full reservedTokens if 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 + streamedOutputTokensCountedLocally in the finally block so aborted streams still debit the tokens actually generated.